- 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 Java from the credited upstream file 2384.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 4 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 String largestPalindromic(String num) {3 Map<Character, Integer> count = new HashMap<>();4 5 for (final char c : num.toCharArray())6 count.merge(c, 1, Integer::sum);7 8 final String firstHalf = getFirstHalf(count);9 final String mid = getMid(count);10 final String ans = firstHalf + mid + reversed(firstHalf);11 return ans.isEmpty() ? "0" : ans;12 }13 14 private String getFirstHalf(Map<Character, Integer> count) {15 StringBuilder sb = new StringBuilder();16 for (char c = '9'; c >= '0'; --c) {17 final int freq = count.getOrDefault(c, 0);18 sb.append(String.valueOf(c).repeat(freq / 2));19 }20 final int index = firstNotZeroIndex(sb);21 return index == -1 ? "" : sb.substring(index);22 }23 24 private int firstNotZeroIndex(StringBuilder sb) {25 for (int i = 0; i < sb.length(); ++i)26 if (sb.charAt(i) != '0')27 return i;28 return -1;29 }30 31 private String getMid(Map<Character, Integer> count) {32 StringBuilder sb = new StringBuilder();33 for (char c = '9'; c >= '0'; --c) {34 final int freq = count.getOrDefault(c, 0);35 if (freq % 2 == 1)36 return String.valueOf(c);37 }38 return "";39 }40 41 private String reversed(final String s) {42 return new StringBuilder(s).reverse().toString();43 }44}45