Q.Write a python program to check whether the given string is palindrome or not, using deque. (Hint : refer to algorithm 4.1)
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →A palindrome reads the same from both ends, so the natural data structure is a double-ended queue. Push all the characters into a deque, then repeatedly take one character off the front (popleft()) and one off the rear (pop()) and compare them. Any mismatch → not a palindrome; if you run out of characters, it is one.
Concept understanding
A queue removes only from the front; a deque (double-ended queue) removes from either end in O(1). That is precisely the operation a palindrome check needs — first vs last, second vs second-last, and so on inward. Using a plain list with pop(0) would also work but costs O(n) per removal because every remaining element shifts left; deque.popleft() is O(1).
We stop when len(dq) <= 1, because a single leftover middle character (odd-length string) has nothing to compare against and never breaks a palindrome.
Algorithm 4.1 applied
- Read the string.
- Keep only the alphanumeric characters and convert them to lower case (so
Nurses runandMadamare judged on letters alone). - Insert all these characters into a deque.
- While the deque holds more than one character:
a.
front = dq.popleft()b.rear = dq.pop()c. Iffront != rear→ returnFalse. - If the loop finishes → return
True.
Program
from collections import deque
def is_palindrome(text):
'''Return True if text is a palindrome, using a deque.'''
letters = [ch.lower() for ch in text if ch.isalnum()]
dq = deque(letters)
while len(dq) > 1:
front = dq.popleft() # remove from the FRONT
rear = dq.pop() # remove from the REAR
if front != rear:
return False
return True
# ---- driver ----
for s in ['MADAM', 'Nurses run', 'PYTHON', 'Level']:
if is_palindrome(s):
print(repr(s), 'is a palindrome')
else:
print(repr(s), 'is NOT a palindrome')
Output
'MADAM' is a palindrome
'Nurses run' is a palindrome
'PYTHON' is NOT a palindrome
'Level' is a palindrome
Dry run — MADAM
Deque starts as ['m','a','d','a','m'].
| Iteration | Deque before | popleft() | pop() | Equal? | Deque after |
|---|---|---|---|---|---|
| 1 | m a d a m | m | m | yes | a d a |
| 2 | a d a | a | a | yes | d |
| — | d | — | — | loop ends (len = 1) | d |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.