Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Palindrome String | Recursive & Iterative Python Solutions
    Data Structures & Algorithms

    Palindrome String | Recursive & Iterative Python Solutions

    codeanddebugBy codeanddebug9 June 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured Image of a question to check if a string is a palindrome or not
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Learn two easy ways to test a Palindrome String: a clean recursive method and a space saving two-pointer loop. Includes code with comments, step-by-step explanation, dry run, and Big-O analysis.

    The [Problem Link] is given here for your quick reference.

    Contents:
     [show]
    • 1 What does the problem ask?
    • 2 Examples
    • 3 Intuition & Approach
      • Key idea for both methods
    • 4 Code 1 – Recursive (unchanged lines, comments added)
    • 5 Code 2 – Iterative Two Pointers (unchanged lines, comments added)
    • 6 Code Walk-through
      • Recursive method
      • Iterative method
    • 7 Dry Run (iterative method on “abba”)
    • 8 Complexity
    • 9 Conclusion

    What does the problem ask?

    Given a string s, tell whether it reads the same forwards and backwards.
    Return True if it is a palindrome, or False otherwise.


    Examples

    InputOutputReason
    "abba"TrueSame letters from both ends.
    "racecar"TrueReads the same both ways.
    "abc"Falsea ≠ c.
    "a"TrueOne letter is always a palindrome.

    Intuition & Approach

    Key idea for both methods

    Compare matching characters from the left and right ends and move inwards:

    • If every pair matches → palindrome.
    • If any pair differs → not a palindrome.

    We show two ways to do this:

    1. Recursive – a clean self-calling check.
    2. Iterative (two pointers) – a simple while loop.

    Code 1 – Recursive

    class Solution:
        # helper that checks s[left .. right]
        def solve(self, s, left, right):
            if left >= right:        # crossed over → all pairs matched
                return True
            if s[left] != s[right]:  # mismatch
                return False
            # move both pointers inward
            return self.solve(s, left + 1, right - 1)
    
        def isPalindrome(self, s: str) -> bool:
            # check the whole string
            return self.solve(s, 0, len(s) - 1)

    Code 2 – Iterative Two Pointers

    class Solution:
        def isPalindrome(self, s: str) -> bool:
            n = len(s)
            left = 0
            right = n - 1
            while left < right:
                if s[left] != s[right]:   # mismatch
                    return False
                left += 1                 # move inward
                right -= 1
            return True                   # all pairs matched

    Code Walkthrough

    Recursive method

    • Base cases
      • left >= right → checked all pairs → return True.
      • Characters differ → return False.
    • Recursive step
      Move left rightward and right leftward and call again.

    Iterative method

    • Set two pointers: left at start, right at end.
    • While they have not crossed:
      • If characters differ → not a palindrome.
      • Else move both pointers inward.
    • Loop ends without a mismatch → palindrome.

    Dry Run (iterative method on "abba")

    leftrights[left]s[right]Action
    03aamatch → move inward
    12bbmatch → move inward
    21––pointers crossed → stop
    ReturnTrue

    Complexity

    MethodTimeSpace
    RecursiveO(n)O(n) – call stack can be n/2 deep
    IterativeO(n)O(1) – only pointers

    n is the length of the string.


    Conclusion

    A palindrome check needs only a linear scan from both ends.

    • The recursive version is short and clear but uses extra stack space.
    • The iterative two-pointer version saves space and is often preferred in practice.

    Choose the one that best fits your style or memory limits.

    Join our FREE Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Easy Recursion Strings
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleDetect Cycle in a Directed Graph – Kahn’s Algorithm (BFS Topological Check) in Python
    Next Article Fibonacci Number | Recursive Python Solution
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python

    13 June 2025
    Data Structures & Algorithms

    Check if array is sorted | Explained using Python Code

    13 June 2025
    Data Structures & Algorithms

    Find the second largest and second smallest element in an Array | Explained

    13 June 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (49)
      • Beginner (24)
      • Expert (9)
      • Intermediate (16)
    • Uncategorised (1)
    Recent Posts

    Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python

    13 June 2025

    Check if array is sorted | Explained using Python Code

    13 June 2025

    Find the second largest and second smallest element in an Array | Explained

    13 June 2025

    Quick Sort Algorithm in Python | Explained

    13 June 2025

    Merge Sort Algorithm in Python | Explained

    13 June 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.