Arrays & Hashing · Pattern 23 of 26
Generate a few candidates, keep the best
When the answer must be one of a small set of shapes, build every candidate and compare them, instead of searching the whole space.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The answer is "near" the input in a structured way
- Only a few split points or shapes are possible
The template
// closest palindrome (not n itself): mirror the left half of n, n ± 1 in the middle, and edge cases
String nearestPalindromic(String n) {
int len = n.length();
long num = Long.parseLong(n);
List<Long> cands = new ArrayList<>();
cands.add((long) Math.pow(10, len - 1) - 1); // 99...9 (one digit shorter)
cands.add((long) Math.pow(10, len) + 1); // 10...01 (one digit longer)
long prefix = Long.parseLong(n.substring(0, (len + 1) / 2));
for (long p = prefix - 1; p <= prefix + 1; p++) {
String left = Long.toString(p);
String right = new StringBuilder(left.substring(0, len / 2 <= left.length() ? len / 2 : left.length())).reverse().toString();
cands.add(Long.parseLong(left + right));
}
long best = -1;
for (long c : cands) {
if (c == num || c < 0) continue;
if (best == -1 || Math.abs(c - num) < Math.abs(best - num) || (Math.abs(c - num) == Math.abs(best - num) && c < best)) best = c;
}
return Long.toString(best);
} def nearest_palindromic(n):
length, num = len(n), int(n)
cands = {10 ** (length - 1) - 1, 10 ** length + 1} # 99...9 and 10...01
prefix = int(n[:(length + 1) // 2])
for p in (prefix - 1, prefix, prefix + 1): # mirror the left half
left = str(p)
cands.add(int(left + left[:length // 2][::-1]))
cands.discard(num)
return str(min(cands, key=lambda c: (abs(c - num), c))) // closest palindrome (not n itself): mirror the left half of n, n ± 1 in the middle, and edge cases
string nearestPalindromic(string n) {
int len = n.size();
long long num = stoll(n);
vector<long long> cands = {(long long)pow(10, len - 1) - 1, (long long)pow(10, len) + 1};
long long prefix = stoll(n.substr(0, (len + 1) / 2));
for (long long p = prefix - 1; p <= prefix + 1; p++) {
string left = to_string(p);
string right = left.substr(0, min((int)left.size(), len / 2));
reverse(right.begin(), right.end());
cands.push_back(stoll(left + right));
}
long long best = -1;
for (long long c : cands) {
if (c == num || c < 0) continue;
if (best == -1 || llabs(c - num) < llabs(best - num) || (llabs(c - num) == llabs(best - num) && c < best)) best = c;
}
return to_string(best);
} // closest palindrome (not n itself): mirror the left half of n, n ± 1 in the middle, and edge cases
function nearestPalindromic(n) {
const len = n.length, num = BigInt(n); // BigInt: n can be up to 10^18
const cands = [10n ** BigInt(len - 1) - 1n, 10n ** BigInt(len) + 1n];
const prefix = BigInt(n.slice(0, (len + 1) >> 1));
for (let p = prefix - 1n; p <= prefix + 1n; p++) {
const left = p.toString();
cands.push(BigInt(left + [...left.slice(0, len >> 1)].reverse().join('')));
}
const abs = (x) => (x < 0n ? -x : x);
let best = -1n;
for (const c of cands) {
if (c === num || c < 0n) continue;
if (best === -1n || abs(c - num) < abs(best - num) || (abs(c - num) === abs(best - num) && c < best)) best = c;
}
return best.toString();
} The variations
-
1A few smart candidates
The nearest palindrome mirrors the left half, the left half ± 1, or changes length (99…9, 10…01). Compare five numbers.
-
2Try every split
When the input is short, try every position for the parentheses (or cut) and evaluate each, keeping the best.
Mistakes to avoid
- Missing the length-changing candidates (99 → 101, 1000 → 999).
- Returning n itself when n is already a palindrome.
- Overflow in JavaScript numbers above 2⁵³: use BigInt.
Lesson done
Next: Fenwick tree: prefix sums with updates →Mark it done once you can write the template from memory and you have solved the worked examples yourself.