Next Greater Element in Subset Array

Day - 75 Next Greater Element I The problem - Given two arrays nums1 and nums2 where nums1 is a subset of nums2, for each element in nums1, find the next greater element in nums2. The next greater element is the first greater element to the right. If it doesn't exist, return -1. Brute Force - For each element in nums1, find its position in nums2, then scan right to find the first greater element. This gives O(n × m) time complexity where n = length of nums1 and m = length of nums2. Approach Used - •) Create array nextGreater[10001] to store next greater element for each number and a Stack<Integer> for tracking elements. •) Traverse nums2 from right to left (i = length-1 to 0), 1 - While stack is not empty && stack.peek() ≤ nums2[i], pop from stack. 2 - If stack is empty, nextGreater[nums2[i]] = -1, else nextGreater[nums2[i]] = stack.peek(). 3 - Push nums2[i] onto stack. •) For each element in nums1, replace it with nextGreater[nums1[i]], return nums1. Complexity - Time - O(n + m) where n = nums1.length, m = nums2.length. Space - O(m), for stack and nextGreater array. Note - Using a monotonic decreasing stack while traversing right to left allows us to efficiently find the next greater element. Elements smaller than current are popped (they can't be next greater for anyone), and the remaining top element is the answer. The array acts as a lookup table for O(1) retrieval. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories