Stack

Validate Stack Sequences

January 26, 2024
easy
Stack

Problem Statement # Given two sequences pushed and popped, each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, otherwise false. Example: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: True Explanation: We can push 1, 2, 3, 4, and 5 and then pop them in the order [4,5,3,2,1]. Solution Approach # The solution involves simulating the push and pop operations on a stack. ...

Next Greater Element

January 10, 2024
medium
Stack

Problem # Given an array nums, for each element, find the next greater element within the array. The next greater element for an element x is the first greater element on the right side of x in the array. If it does not exist, output -1 for this element. Example: Input: nums = [2, 1, 3, 5, 6, 4] Output: [3, 3, 5, 6, -1, -1] Solution # The solution involves using a stack to efficiently find the next greater element for each element in the array. ...