Posts

Showing posts with the label Stack

Next Greater Element

Next Greater Element – Understanding Element Relationships in Arrays Problem Statement Given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 , return an array of the next greater element for each element in nums1 corresponding to its position in nums2 . The next greater element of a number x in nums2 is the first greater number to the right of x in nums2 . If it does not exist, return -1 Example Input: nums1 = [4,1,2] nums2 = [1,3,4,2] Output: [-1, 3, -1] Explanation: For 4 , there is no number greater than it to its right in nums2 . For 1 , the next greater number is 3 . For 2 , there is no greater number to the right. Best Data Structure for the Job To efficiently solve this problem, we use a stack in combination with a hash map . The stack helps us track elements in a decreasing order while scanning nums2 from right to left, enabling us to find the next greater element for each number efficiently. The hash map i...

Bracket Up, Stack Down – Valid Parentheses

Valid Parentheses – Keeping Brackets in Check Problem Statement Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' , and ']' , determine if the input string is valid . A string is valid if: Open brackets are closed by the same type of brackets. Open brackets are closed in the correct order. Every close bracket has a corresponding open bracket. Best Data Structure for the Job Stack is the MVP here. Why? Perfect for Last In, First Out (LIFO) logic Helps track nested and sequential brackets Efficient and intuitive for validation problems like this on Different Approaches 1)Brute Force with Replacements Keep removing valid pairs like "()" , "{}" , and "[]" until nothing can be removed. If the string becomes empty, it was valid. public boolean isValid (String s) { while (s.contains( "()" ) || s.contains( "[]" ) || s.contains( "{}" ))...