- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 45 lines of C++ from the credited upstream file 2384.cpp.
- The implementation visibly relies on hash lookup.
- 3 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string largestPalindromic(string num) {4 unordered_map<char, int> count;5 6 for (const char c : num)7 ++count[c];8 9 const string firstHalf = getFirstHalf(count);10 const string mid = getMid(count);11 const string ans = firstHalf + mid + reversed(firstHalf);12 return ans.empty() ? "0" : ans;13 }14 15 private:16 string getFirstHalf(const unordered_map<char, int>& count) {17 string firstHalf;18 for (char c = '9'; c >= '0'; --c) {19 const auto it = count.find(c);20 if (it == count.cend())21 continue;22 const int freq = it->second;23 firstHalf += string(freq / 2, c);24 }25 const int index = firstHalf.find_first_not_of('0');26 return index == string::npos ? "" : firstHalf.substr(index);27 }28 29 string getMid(const unordered_map<char, int>& count) {30 for (char c = '9'; c >= '0'; --c) {31 const auto it = count.find(c);32 if (it == count.cend())33 continue;34 const int freq = it->second;35 if (freq % 2 == 1)36 return string(1, c);37 }38 return "";39 }40 41 string reversed(const string& s) {42 return {s.rbegin(), s.rend()};43 }44};45