← Microsoft bank

Microsoft · Question 31 · Stacks

Next Greater Element I

StacksJavacode⏱ O(n+m)💾 O(n)
Product-based

Problem

Given two arrays, find the next greater element of each number in nums1 from nums2.

Approach

One monotonic pass over nums2 maps every value to its next greater.

Time O(n+m)Space O(n)

How it works

  1. 1Sweep nums2 maintaining a decreasing stack.
  2. 2Each popped value maps to its next greater.
  3. 3Answer nums1 by lookup, defaulting to -1.

Sample input / output

Input:
3 4
4 1 2
1 3 4 2
Output:
[-1, 3, -1]

Constraints

1 <= lengths <= 1000; all values unique across arrays.

Solution — read it, then walk it

Time O(n+m)Space O(n)Loops 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]nextGreaterElement(int[]nums1, int[] nums2)Map<Integer, Integer> map =new HashMap<>()Stack<Integer> stack = newStack<>()for (int num : nums2)while(!stack.isEmpty() &&num > stack.peek())map.put(stack.pop(), num)stack.push(num)DEFINE [] res = newint[nums1.length]for (int i = 0; i <nums1.length; i++)res[i] =map.getOrDefault(nums1[i],-1)RETURN resDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n1 = sc.nextInt();int n2 = sc.nextInt()DEFINE [] nums1 = newint[n1]; for (int i = 0; i< n1; i++) nums1[i] …DEFINE [] nums2 = newint[n2]; for (int i = 0; i< n2; i++) nums2[i] …System.out.println(Arrays.toString(nextGreaterElement(nums1,nums2)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/20

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits