Data Structures · Stack

Question 1: Stack Application — Palindrome Checker

🔤 The input string s

index 0 … n−1 (left to right)
Output: (not computed yet)

📚 The helper stack stack<char>

↑ top — push / pop happen here LIFO last-in-first-out
whatever goes in first sits lowest,
the last one in comes out first
reversed string rev (built from the pops)

🔍 Compare rev == s

rev
s (original)
equal different → immediately not a palindrome being compared
The library’s rev == s also compares left to right and stops at the first different character, so the animation stops there too.

💬 Current step

💻 The C++ program (std::stack<char>)

Yellow = current line. Three steps: push everything → pop to build the reversed string → compare with the original.

📄 The question’s wording & key points

Problem Description: a palindrome is a word that reads the same backward as forward (for example, "madam" or "racecar"). Write a C++ function isPalindrome that takes a string and uses a std::stack<char> to check whether it is a palindrome.
A palindrome is a word that reads the same backward as forward (for example, "madam" or "racecar").
Hint: push all characters onto the stack, then pop them one by one to form the reversed string, and compare it with the original string.
Push all characters onto the stack, then pop them one by one to form the reversed string, and compare it with the original string.
1Push every character — n pushes
2Pop to build the reversed string — LIFO flips the order for you
3Compare rev with s character by character — all equal means it is a palindrome
Why a stack? A palindrome has to read the same backwards, and LIFO flips the order for you — one pass of pushes and pops, no manual index arithmetic.
Complexity: each character is pushed once, popped once and compared once → O(n) time, O(n) extra space (the size of the stack).
Can it be faster? Push only the first half and compare each pop with the second half — half the space and half the comparisons (see the closing note).
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result