Placement Prep

Palindrome Program in Python: Check Numbers and Strings

Five methods to check palindromes in Python: integer reversal, slicing, two-pointer, and recursion. Step-traces, complexity table, and placement context included.

By FACE Prep Team 5 min read
python palindrome placement-prep tcs-nqt coding-interview string-manipulation programming

A palindrome reads the same forwards and backwards, and palindrome checks appear in the coding sections of TCS NQT, Infosys Specialist Programmer, and Wipro NLTH.

This tutorial covers five Python methods across two problem variants: integer palindromes checked without string conversion, and string palindromes using slicing, two-pointer comparison, and recursion. Every method includes a step-by-step trace so you can follow the logic without running the code.

What is a palindrome?

A palindrome is any sequence that is identical when reversed. The reversal must be exact: character order, not meaning.

Common examples:

  • Numbers: 121, 1331, 404, 9009
  • Strings: “madam”, “racecar”, “level”, “noon”
  • Phrases (after stripping spaces and punctuation): “step on no pets”, “a man a plan a canal panama”

Non-palindromes: 123 (reversed is 321), “hello” (reversed is “olleh”).

Two distinct problems arise depending on input type. When the input is an integer, you can either reverse the digits mathematically or convert to a string first. When the input is a string, you have three clean options: slicing, two-pointer, or recursion. Both problem types show up in placement coding rounds, often in the same question set.

Palindrome check for a number in Python

Method 1: Integer digit reversal using a while loop

This approach reverses the number by extracting digits with the modulo operator and rebuilding the reversed value digit by digit. No str() call is involved. Interviewers often prefer this because it shows you understand base-10 arithmetic, not just Python’s string shortcuts.

def is_palindrome_number(n):
    if n < 0:
        return False
    original = n
    reversed_n = 0
    while n != 0:
        digit = n % 10
        reversed_n = reversed_n * 10 + digit
        n //= 10
    return original == reversed_n

print(is_palindrome_number(121))   # True
print(is_palindrome_number(456))   # False
print(is_palindrome_number(-121))  # False

Step trace for n = 121:

  • Start: original = 121, reversed_n = 0
  • Iteration 1: digit = 121 % 10 = 1, reversed_n = 0 * 10 + 1 = 1, n = 121 // 10 = 12
  • Iteration 2: digit = 12 % 10 = 2, reversed_n = 1 * 10 + 2 = 12, n = 12 // 10 = 1
  • Iteration 3: digit = 1 % 10 = 1, reversed_n = 12 * 10 + 1 = 121, n = 1 // 10 = 0
  • Loop ends: original (121) equals reversed_n (121), return True

The modulo-and-quotient pattern here is the same one used in the Armstrong number check. Recognising that the two problems share a digit-extraction loop speeds up problem-solving when both appear in the same coding test.

Method 2: Convert to string and slice

When the problem statement does not restrict string conversion, this is the shortest version:

n = int(input("Enter a number: "))
print("Palindrome" if str(n) == str(n)[::-1] else "Not a Palindrome")

Python’s sequence slicing with [::-1] reverses any sequence in one step. For integers in a placement context, check whether the problem says “without using string operations” before using this form. If it does, fall back to Method 1.

Palindrome check for a string in Python

Method 1: Slicing with s[::-1]

def is_palindrome_slice(s):
    return s == s[::-1]

print(is_palindrome_slice("madam"))   # True
print(is_palindrome_slice("python"))  # False

s[::-1] creates a new string that is the reversed copy of s. If the copy equals the original, the string is a palindrome. This is the clearest code to write, but it allocates O(n) extra space for the reversed copy. In a timed coding test where brevity matters, this is the right default.

Method 2: Two-pointer comparison

The two-pointer approach compares characters from both ends of the string and moves inward. It returns False as soon as it finds a mismatch, so it stops early on non-palindromes instead of reversing the entire string first.

def is_palindrome_two_pointer(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

print(is_palindrome_two_pointer("racecar"))  # True
print(is_palindrome_two_pointer("hello"))    # False

Step trace for s = "racecar" (length 7, indices 0 to 6):

  • left = 0, right = 6: s[0] = ‘r’, s[6] = ‘r’, match, advance
  • left = 1, right = 5: s[1] = ‘a’, s[5] = ‘a’, match, advance
  • left = 2, right = 4: s[2] = ‘c’, s[4] = ‘c’, match, advance
  • left = 3, right = 3: left is not less than right, exit loop
  • Return True

This uses O(1) extra space because no copy of the string is created. When an interviewer says “can you optimise for memory?”, two-pointer is the answer.

Method 3: Recursive check

def is_palindrome_recursive(s, left=0, right=None):
    if right is None:
        right = len(s) - 1
    if left >= right:
        return True
    if s[left] != s[right]:
        return False
    return is_palindrome_recursive(s, left + 1, right - 1)

print(is_palindrome_recursive("level"))   # True
print(is_palindrome_recursive("world"))   # False

Step trace for s = "level" (length 5, indices 0 to 4):

  • Call with left = 0, right = 4: s[0] = ‘l’, s[4] = ‘l’, match, recurse(1, 3)
  • Call with left = 1, right = 3: s[1] = ‘e’, s[3] = ‘e’, match, recurse(2, 2)
  • Call with left = 2, right = 2: left equals right, return True

The call stack goes half the string’s length deep for a confirmed palindrome. For strings well under a thousand characters, this is not an issue in practice. Python’s default recursion limit is 1,000 calls, adjustable via sys.setrecursionlimit(). The recursive form is useful to include in your answer when an interviewer asks you to demonstrate a divide-and-conquer approach on a simple example.

Method comparison

MethodTimeSpaceBest for
Integer while loop (no str)O(d), d = digit countO(1)Number palindromes when conversion is restricted
String conversion + slicingO(n)O(n)Number palindromes when conversion is allowed
Slicing s[::-1]O(n)O(n)String palindromes, quick to write
Two-pointerO(n)O(1)String palindromes, optimal space
RecursiveO(n)O(n) stackDemonstrating recursion; not optimal for production

For most placement problems, the expected answer for strings is slicing (fast to code) or two-pointer (optimal space). For numbers, the while-loop digit reversal is expected unless the question explicitly allows str().

Palindrome problems in placement exams

Palindrome checks appear in placement coding rounds in three forms:

  • Basic check: given a number or string, return True or False
  • Phrase palindrome: given a sentence, ignore spaces and punctuation and check
  • Variant problems: count palindromic substrings, or find the next palindrome after a given number

The TCS NQT portal includes sample coding problems, and the basic palindrome check appears in both Level 1 and Level 2 sets. Infosys Specialist Programmer and Wipro NLTH include similar string-handling checks in their first coding sections.

Two follow-up questions come up in most technical interviews after you submit a working palindrome solution:

  • “What happens with negative numbers?” Add if n < 0: return False before the loop.
  • “Can you do it without extra space?” Switch from slicing to two-pointer.

For phrase palindromes, the standard preprocessing step uses .isalnum() to filter characters. The same character-classification approach is covered in the uppercase/lowercase/digit character check. The cleaned form for “step on no pets” becomes “steponnopets”, which then passes through any of the five methods above.

def is_palindrome_phrase(s):
    cleaned = "".join(c.lower() for c in s if c.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome_phrase("step on no pets"))  # True
print(is_palindrome_phrase("hello world"))       # False

The full collection of Python basic programs covers other common patterns that appear alongside palindrome checks in placement coding rounds, including Armstrong numbers and prime checks.

The two-pointer method’s O(1) space usage and its early-exit on mismatches are the kind of implementation details that distinguish a polished coding-round answer from a working-but-unoptimised one. Once you have these fundamentals in place, the next practical step is building projects that use these patterns in larger systems. TinkerLLM gives you direct LLM API access at ₹299, which is where you move from solving palindrome checks to integrating them into text-processing pipelines that go on a resume.

Primary sources

Frequently asked questions

Does the integer palindrome check work for negative numbers?

No. Negative numbers are never palindromes because the minus sign makes the reversed form different from the original. Add an early guard 'if n < 0: return False' before the while loop to handle this correctly.

How do I check a phrase like 'step on no pets' as a palindrome?

Strip spaces and non-alphanumeric characters first, then lowercase everything: s = ''.join(c.lower() for c in s if c.isalnum()). After that, apply any of the five string methods above.

Which palindrome method uses the least memory?

The two-pointer approach uses O(1) auxiliary space because it compares characters in place without ever creating a reversed copy. Slicing with s[::-1] creates an O(n) copy of the string.

Is the string palindrome check case-sensitive by default?

Yes. 'Racecar' and 'racecar' are treated as different strings because 'R' does not equal 'r'. Add .lower() before comparing if you want a case-insensitive check.

Do palindrome problems appear in the TCS NQT coding section?

Yes. String and number palindrome checks are standard question types in TCS NQT Level 1 and Level 2. Knowing at least two methods, one for integers and one for strings, covers the common variants you will see there.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF