Smallest Palindrome Strictly Greater Than K
Company: Two Sigma
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to manipulate numeric digit representations, design an efficient constructive algorithm for special-form numbers, and reason about edge cases and complexity constraints.
Constraints
- 1 <= K < 10^18 (K and the answer both fit in a signed 64-bit integer)
- Solution must run in time proportional to the number of digits of K (up to a small polynomial factor)
- Brute-force increment-and-check is too slow: gaps between consecutive palindromes near 10^18 can be ~10^9
Examples
Input: 123
Expected Output: 131
Explanation: 121 <= 123, so increment the prefix 12 -> 13 and mirror to 131.
Input: 99
Expected Output: 101
Explanation: 99 is a palindrome but not strictly greater; the prefix 9 carries to 10, adding a digit -> 101.
Input: 131
Expected Output: 141
Explanation: 131 mirrors to itself (not strictly greater), so increment prefix 13 -> 14 and mirror to 141.
Input: 12932
Expected Output: 13031
Explanation: Mirroring left half 129 gives 12921 (too small); increment prefix to 130 and mirror to 13031.
Input: 9999
Expected Output: 10001
Explanation: All 9s: prefix 99 carries to 100, so the answer grows one digit to 10001.
Input: 1
Expected Output: 2
Explanation: Smallest single-digit case; the next palindrome strictly greater than 1 is 2.
Input: 9
Expected Output: 11
Explanation: 9 mirrors to itself; prefix carries from 9 to 10, producing the two-digit palindrome 11.
Input: 808
Expected Output: 818
Explanation: 808 mirrors to itself; increment middle prefix 80 -> 81 and mirror to 818.
Input: 999
Expected Output: 1001
Explanation: Odd-length all 9s: prefix 99 carries, answer grows a digit to 1001.
Input: 999999999999999999
Expected Output: 1000000000000000001
Explanation: Eighteen 9s (< 10^18); the answer is 10^18 + 1, which is a palindrome and still fits in a signed 64-bit integer.
Hints
- The left half of K determines the palindrome: mirror it onto the right half to get a candidate palindrome of the same length.
- If the mirrored candidate is not strictly greater than K, increment the left-half prefix (including the middle digit for odd lengths) by one, then mirror again.
- Watch the carry: if incrementing the prefix adds a digit (K is all 9s, like 999 or 9999), the answer has one more digit and looks like 1 followed by zeros followed by 1 (e.g. 1001, 10001).