Pages

Friday, March 13, 2026

Next Greater element 1 - monotonic stack problem - LEETCODE 496

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> map = new HashMap();
        Deque<Integer> stack = new ArrayDeque<>(); // faster than stack

        for(int num : nums2) { // scans each no. in nums2
           
            while(!stack.isEmpty() && stack.peek() < num) {
                map.put(stack.pop(), num);
            }
            stack.push(num);
           
        }

        int[] result = new int[nums1.length]; // num1 jitna length ka answer hona chaiye!
       
        for(int i=0; i<nums1.length; i++) {
            result[i] = map.getOrDefault(nums1[i], -1); // if it exists, return value nums1[i] else return -1
        }

        return result;
       
           
        }
    }

No comments:

Post a Comment

NEW TO TECH WORLD: natural progression path: when to choose backend, sre, platform engieering? clear all your buzzwords doubts here!

🤔 Feeling Confused? Good. That’s normal. The tech world throws around a lot of buzzwords. So instead of thinking: “Which role should I...