Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
You are given a string num consisting of digits only.
Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.
Notes:
num, but you must use at least one digit.Example 1:
Input: num = "444947137" Output: "7449447" Explanation: Use the digits "4449477" from "444947137" to form the palindromic integer "7449447". It can be shown that "7449447" is the largest palindromic integer that can be formed.
Example 2:
Input: num = "00009" Output: "9" Explanation: It can be shown that "9" is the largest palindromic integer that can be formed. Note that the integer returned should not contain leading zeroes.
Constraints:
1 <= num.length <= 105num consists of digits.Problem summary: You are given a string num consisting of digits only. Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes. Notes: You do not need to use all the digits of num, but you must use at least one digit. The digits can be reordered.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Greedy
"444947137"
"00009"
longest-palindrome)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2384: Largest Palindromic Number
class Solution {
public String largestPalindromic(String num) {
int[] cnt = new int[10];
for (char c : num.toCharArray()) {
++cnt[c - '0'];
}
String mid = "";
for (int i = 9; i >= 0; --i) {
if (cnt[i] % 2 == 1) {
mid += i;
--cnt[i];
break;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; ++i) {
if (cnt[i] > 0) {
cnt[i] >>= 1;
sb.append(("" + i).repeat(cnt[i]));
}
}
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') {
sb.deleteCharAt(sb.length() - 1);
}
String t = sb.toString();
String ans = sb.reverse().toString() + mid + t;
return "".equals(ans) ? "0" : ans;
}
}
// Accepted solution for LeetCode #2384: Largest Palindromic Number
func largestPalindromic(num string) string {
cnt := make([]int, 10)
for _, c := range num {
cnt[c-'0']++
}
ans := ""
for i := 9; i >= 0; i-- {
if cnt[i]%2 == 1 {
ans = strconv.Itoa(i)
cnt[i]--
break
}
}
for i := 0; i < 10; i++ {
if cnt[i] > 0 {
cnt[i] >>= 1
s := strings.Repeat(strconv.Itoa(i), cnt[i])
ans = s + ans + s
}
}
ans = strings.Trim(ans, "0")
if ans == "" {
return "0"
}
return ans
}
# Accepted solution for LeetCode #2384: Largest Palindromic Number
class Solution:
def largestPalindromic(self, num: str) -> str:
cnt = Counter(num)
ans = ''
for i in range(9, -1, -1):
v = str(i)
if cnt[v] % 2:
ans = v
cnt[v] -= 1
break
for i in range(10):
v = str(i)
if cnt[v]:
cnt[v] //= 2
s = cnt[v] * v
ans = s + ans + s
return ans.strip('0') or '0'
// Accepted solution for LeetCode #2384: Largest Palindromic Number
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2384: Largest Palindromic Number
// class Solution {
// public String largestPalindromic(String num) {
// int[] cnt = new int[10];
// for (char c : num.toCharArray()) {
// ++cnt[c - '0'];
// }
// String mid = "";
// for (int i = 9; i >= 0; --i) {
// if (cnt[i] % 2 == 1) {
// mid += i;
// --cnt[i];
// break;
// }
// }
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 10; ++i) {
// if (cnt[i] > 0) {
// cnt[i] >>= 1;
// sb.append(("" + i).repeat(cnt[i]));
// }
// }
// while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') {
// sb.deleteCharAt(sb.length() - 1);
// }
// String t = sb.toString();
// String ans = sb.reverse().toString() + mid + t;
// return "".equals(ans) ? "0" : ans;
// }
// }
// Accepted solution for LeetCode #2384: Largest Palindromic Number
function largestPalindromic(num: string): string {
const count = new Array(10).fill(0);
for (const c of num) {
count[c]++;
}
while (count.reduce((r, v) => (v % 2 === 1 ? r + 1 : r), 0) > 1) {
for (let i = 0; i < 10; i++) {
if (count[i] % 2 === 1) {
count[i]--;
break;
}
}
}
let res = [];
let oddIndex = -1;
for (let i = 9; i >= 0; i--) {
if (count[i] % 2 == 1) {
oddIndex = i;
count[i] -= 1;
}
res.push(...new Array(count[i] >> 1).fill(i));
}
if (oddIndex !== -1) {
res.push(oddIndex);
}
const n = res.length;
for (let i = 0; i < n; i++) {
if (res[i] !== 0) {
res = res.slice(i);
if (oddIndex !== -1) {
res.push(...[...res.slice(0, res.length - 1)].reverse());
} else {
res.push(...[...res].reverse());
}
return res.join('');
}
}
return '0';
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.