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.

2 variations · 2 problems

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

Candidate Generation
// 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);
}

The variations

  1. 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.

  2. 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.
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.