Bird
Raised Fist0
Interview Prepmath-geometryeasyAmazonGoogleFacebook

Palindrome Number

Choose your preparation mode4 modes available
📋
Problem

Imagine you are building a system that validates user IDs which must read the same forwards and backwards to ensure symmetry and ease of recall.

Given an integer x, determine whether it is a palindrome. An integer is a palindrome when it reads the same backward as forward. Return true if x is a palindrome, and false otherwise.

-2^31 <= x <= 2^31 - 1
Edge cases: 0 → true (single digit is always palindrome)-101 → false (negative number)1001 → true (even length palindrome)
</>
IDE
def is_palindrome(x: int) -> bool:public boolean isPalindrome(int x)bool isPalindrome(int x)function isPalindrome(x)
def is_palindrome(x: int) -> bool:
    # Write your solution here
    pass
class Solution {
    public boolean isPalindrome(int x) {
        // Write your solution here
        return false;
    }
}
#include <vector>
using namespace std;

bool isPalindrome(int x) {
    // Write your solution here
    return false;
}
function isPalindrome(x) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: true for negative numbersDid not check for negative input and returned true incorrectly.✅ Add condition: if x < 0: return false
Wrong: true for numbers with trailing zeros like 100Failed to handle trailing zero edge case causing false positives.✅ Return false if x % 10 == 0 and x != 0
Wrong: true for non-palindromes like 10Used greedy approach comparing only first and last digits.✅ Compare all digit pairs from both ends until pointers meet.
Wrong: false for palindrome numbers with even length like 123321Confused full reversal with half reversal approach causing incorrect result.✅ Reverse only half the digits and compare with remaining half.
Wrong: TLE on large inputsUsed full string conversion or full reversal causing O(n) or worse complexity.✅ Implement half reversal method with O(log n) complexity.
✓
Test Cases
t1_01basic
Input{"x":121}
Expectedtrue

Reading 121 from left to right and right to left is the same.

t1_02basic
Input{"x":12321}
Expectedtrue

12321 reads the same forwards and backwards, so it is a palindrome.

t2_01edge
Input{"x":0}
Expectedtrue

Single digit 0 is always a palindrome.

t2_02edge
Input{"x":-101}
Expectedfalse

Negative numbers are not palindromes due to the minus sign.

t2_03edge
Input{"x":1001}
Expectedtrue

1001 reads the same forwards and backwards, even length palindrome.

t2_04edge
Input{"x":100}
Expectedfalse

100 is not a palindrome because trailing zeros break symmetry.

t3_01corner
Input{"x":10}
Expectedfalse

10 is not a palindrome; digits differ when reversed.

t3_02corner
Input{"x":123321}
Expectedtrue

123321 is a palindrome with even length, reversed half matches other half.

t3_03corner
Input{"x":2147447412}
Expectedtrue

Large palindrome number within 32-bit range, tests overflow handling.

t4_01performance
Input{"_description":"n=100 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

Input size n=100 digits (max length for 32-bit int) must complete in O(log n) time within 2 seconds.

Practice

(1/5)
1. You are given a string representing a column title as it appears in an Excel sheet (e.g., "A", "AB", "ZY"). Which algorithmic approach guarantees an optimal and efficient conversion of this title to its corresponding column number?
easy
A. Greedy approach that picks the highest value letter first and sums values
B. Iterative conversion treating the string as a base-26 number and accumulating the result
C. Dynamic programming to store intermediate sums for all prefixes
D. Recursive backtracking to try all possible letter combinations

Solution

  1. Step 1: Understand the problem as base-26 conversion

    The Excel column title can be viewed as a number in base 26, where 'A' = 1, 'B' = 2, ..., 'Z' = 26.
  2. Step 2: Identify the approach that accumulates values iteratively

    The iterative approach multiplies the current result by 26 and adds the value of the current character, effectively converting base-26 to decimal.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Iterative base-26 conversion matches Excel column numbering [OK]
Hint: Treat the string as a base-26 number [OK]
Common Mistakes:
  • Using greedy or DP unnecessarily
  • Recursion causes overhead
  • Misinterpreting letter values
2. Given the following Python code to find the nth ugly number, what is the output when calling nthUglyNumber(4)?
import heapq

def nthUglyNumber(n):
    heap = [1]
    seen = {1}
    ugly = 1
    for _ in range(n):
        ugly = heapq.heappop(heap)
        for factor in [2, 3, 5]:
            new_ugly = ugly * factor
            if new_ugly not in seen:
                seen.add(new_ugly)
                heapq.heappush(heap, new_ugly)
    return ugly

print(nthUglyNumber(4))
easy
A. 6
B. 5
C. 8
D. 4

Solution

  1. Step 1: Trace heap pops and pushes for n=4

    Initial heap: [1]. Iteration 1 pops 1, pushes 2,3,5. Iteration 2 pops 2, pushes 4,6,10. Iteration 3 pops 3, pushes 6 (already seen), 9, 15. Iteration 4 pops 4, pushes 8,12,20.
  2. Step 2: Identify the 4th popped ugly number

    The popped numbers in order are 1, 2, 3, 4. The 4th ugly number is 4, so nthUglyNumber(4) returns 4.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    4 is the 4th ugly number generated by the heap [OK]
Hint: Heap pops nth ugly number in ascending order [OK]
Common Mistakes:
  • Confusing the iteration count with the returned value
  • Forgetting duplicates are skipped
  • Miscounting the order of popped elements
3. The following code attempts to count primes less than n using an optimized sieve. Identify the line containing the subtle bug that causes incorrect results or inefficiency.
def countPrimes(n):
    if n <= 2:
        return 0
    is_prime = [True] * (n // 2)
    is_prime[0] = False  # 1 is not prime
    for i in range(3, int(n**0.5) + 1, 2):
        if is_prime[i // 2]:
            for j in range(i, n, 2 * i):  # Bug here
                is_prime[j // 2] = False
    return 1 + sum(is_prime)  # add prime 2
medium
A. Line setting is_prime[0] = false
B. Line returning 1 + sum(is_prime)
C. Line starting the inner loop from j = i instead of i * i
D. Line checking if n <= 2 and returning 0

Solution

  1. Step 1: Understand inner loop start

    The inner loop should start marking multiples from i*i, not i, to avoid redundant marking.
  2. Step 2: Identify impact of bug

    Starting from i causes marking the prime number i itself as non-prime, corrupting results.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct sieve starts marking from i*i to preserve prime i [OK]
Hint: Mark multiples from i*i to avoid marking primes themselves [OK]
Common Mistakes:
  • Starting marking from i instead of i*i
  • Mislabeling 1 as prime
  • Forgetting to add prime 2
4. Consider this buggy recursive reverse integer code snippet:
def reverse(x: int) -> int:
    INT_MAX = 2**31 - 1
    INT_MIN = -2**31
    sign = -1 if x < 0 else 1
    x = abs(x)

    def helper(num, rev):
        if num == 0:
            return rev
        pop = num % 10
        # Bug: Missing overflow check here
        rev = rev * 10 + pop
        return helper(num // 10, rev)

    rev = helper(x, 0)
    return sign * rev if rev != 0 else 0
What is the root cause of incorrect behavior in this code?
medium
A. Line 'rev = rev * 10 + pop' lacks overflow check before multiplication
B. Line with 'sign = -1 if x < 0 else 1' does not handle zero correctly
C. Line 'pop = num % 10' incorrectly extracts digits for negative numbers
D. Line 'return sign * rev if rev != 0 else 0' returns zero incorrectly for valid reversed zero

Solution

  1. Step 1: Identify missing overflow check

    The code multiplies rev by 10 and adds pop without checking if rev will overflow 32-bit integer limits.
  2. Step 2: Consequence of missing check

    Without overflow check before multiplication, the reversed integer can exceed INT_MAX causing incorrect results or runtime errors.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Overflow check must precede rev update to avoid errors [OK]
Hint: Overflow check must happen before rev update [OK]
Common Mistakes:
  • Ignoring overflow before multiplying rev by 10
  • Assuming sign handling fixes overflow
  • Misunderstanding digit extraction for negatives
5. Suppose you want to count primes less than n but now the input n can be up to 10^12, too large for a standard sieve. Which approach is best suited to handle this scenario efficiently?
hard
A. Use a segmented sieve that processes ranges of size sqrt(n) to reduce memory usage.
B. Use the standard sieve of Eratosthenes with a larger memory allocation.
C. Use brute force primality checks for each number up to n.
D. Use a dynamic programming approach to store prime counts up to n.

Solution

  1. Step 1: Understand memory constraints

    Standard sieve requires O(n) space, which is infeasible for n=10^12.
  2. Step 2: Identify suitable algorithm

    Segmented sieve divides the range into manageable blocks, using O(sqrt(n)) memory and still marking primes efficiently.
  3. Step 3: Compare alternatives

    Brute force is too slow, DP is not applicable, and standard sieve is too large.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Segmented sieve is standard for large n prime counting [OK]
Hint: Segmented sieve handles large n with limited memory [OK]
Common Mistakes:
  • Trying standard sieve for huge n
  • Using brute force for large ranges
  • Misapplying DP to prime counting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard