Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Make Palindrome

#include <bits/stdc++.h>
using namespace std;

void solve(string &str) {
    int n = str.length();

    map<char, int> freq;
    for (int i = 0; i < n; i++) {
        freq[str[i]]++;
    }

    vector<char> isolated;
    for (auto kv : freq) {
        if (kv.second % 2 != 0) {
            isolated.push_back(kv.first);
        }
    }

    int i = 0, j = (int)isolated.size() - 1;
    while (i < j) {
        freq[isolated[i]]++;
        freq[isolated[j]]--;
        i++;
        j--;
    }

    string res;
    char odd_ch = '#';
    for (auto kv : freq) {
        // Be careful with this case in string problems.
        if (kv.second == 0) {
            continue;
        }
        if (kv.second % 2 != 0) {
            odd_ch = kv.first;
        }
        for (int i = 0; i < kv.second / 2; i++) {
            res += kv.first;
        }
    }

    string copy = res;
    reverse(copy.begin(), copy.end());

    if (odd_ch != '#') {
        res += odd_ch;
    }
    res += copy;

    cout << res << endl;
}

int main() {
    string str;
    cin >> str;
    solve(str);
    return 0;
}

// Tricky Test Case: aabbcccdd