Python Program to Check Palindrome Using While Loop
while start < end: if s[start] != s[end]: return False; start += 1; end -= 1.Examples
How to Think About It
Algorithm
Code
s = input('Enter a string: ') start = 0 end = len(s) - 1 is_palindrome = True while start < end: if s[start] != s[end]: is_palindrome = False break start += 1 end -= 1 if is_palindrome: print(f'{s} is a palindrome') else: print(f'{s} is not a palindrome')
Dry Run
Let's trace the input 'madam' through the code
Initialize pointers
start = 0, end = 4 (length of 'madam' - 1)
Compare characters at start and end
s[0] = 'm', s[4] = 'm' (match, continue)
Move pointers inward
start = 1, end = 3
Compare characters again
s[1] = 'a', s[3] = 'a' (match, continue)
Move pointers inward
start = 2, end = 2
Pointers meet or cross
Loop ends, no mismatches found
| start | end | s[start] | s[end] | match |
|---|---|---|---|---|
| 0 | 4 | m | m | yes |
| 1 | 3 | a | a | yes |
| 2 | 2 | d | d | loop ends |
Why This Works
Step 1: Two pointers approach
We use two pointers to compare characters from the start and end of the string moving towards the center.
Step 2: Character comparison
If any pair of characters does not match, the string cannot be a palindrome.
Step 3: Loop termination
If the pointers cross without mismatches, the string is confirmed as a palindrome.
Alternative Approaches
s = input('Enter a string: ') if s == s[::-1]: print(f'{s} is a palindrome') else: print(f'{s} is not a palindrome')
def is_palindrome(s, start, end): if start >= end: return True if s[start] != s[end]: return False return is_palindrome(s, start + 1, end - 1) s = input('Enter a string: ') if is_palindrome(s, 0, len(s) - 1): print(f'{s} is a palindrome') else: print(f'{s} is not a palindrome')
Complexity: O(n) time, O(1) space
Time Complexity
The program compares characters from both ends once, so it runs in linear time proportional to the string length.
Space Complexity
Only a few variables are used for pointers and flags, so space usage is constant.
Which Approach is Fastest?
String slicing is fastest and simplest but does not use a while loop. The while loop method is efficient and clear for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(n) | O(1) | Learning loops and manual checking |
| String slicing | O(n) | O(n) | Quick palindrome check with less code |
| Recursion | O(n) | O(n) | Understanding recursion but uses more memory |