25Validate balanced parentheses/brackets, and explain the stack pattern.▼easy★ EssentialGoogleMetaAmazon2 replies◆ premiumA warm-up that screens for the stack instinct. The signal is recognizing last-opened-first-closed maps to a stack, and handling the edge cases (leftover opens, early close). Here is the pattern.Open full answer →
87Find the next greater element for each item in an array using a monotonic stack.▼mediumAmazonMetaGoogle1 replies◆ premiumThe brute force is O(n squared) nested scans. A monotonic stack does it in one O(n) pass by keeping only the candidates that can still be a future answer. Here is the pattern and why each element is pushed and popped exactly once.Open full answer →
94Implement a basic calculator that evaluates a string with +, -, *, /, and parentheses.▼hardGoogleMetaAmazon2 replies◆ premiumEvaluating arithmetic with precedence and nested parentheses is a parsing problem, and a stack handles both cleanly. The traps are operator precedence, multi-digit numbers, and the sign of truncated division. Here is a single-pass solution.Open full answer →