Dsa
Stack
Easy
The Gravity Stack
In a 'Gravity Stack', items are either Heavy (Uppercase) or Light (Lowercase).
1. A Heavy item added to the stack first 'crushes' (removes) all Light items currently at the top of the stack until it hits another Heavy item or the bottom.
2. A Light item can only be added to the stack if there is at least one Heavy item already in the stack to 'anchor' it. If the stack is empty or contains only Light items (which shouldn't happen), the incoming Light item is ignored.
Input: A space-separated sequence of characters.
Output: The final stack from bottom to top.
Example:
Input: b A c d B e
Output: A B e
(Explanation: 'b' is ignored (no Heavy). 'A' is pushed. 'c' and 'd' are pushed because 'A' is below. 'B' crushes 'c' and 'd', then 'B' is pushed. 'e' is pushed because 'B' is below.)
Key concepts
stacklogic
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now