← Microsoft bank

Microsoft · Question 32 · Stacks

Next Greater Element II

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

Problem

Given a circular array, find the next greater element for every element.

Approach

Sweep twice around the circle with a monotonic stack.

Time O(n)Space O(n)

How it works

  1. 1Walk the doubled array right to left in effect.
  2. 2The stack top is each position's next greater.

Sample input / output

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

Constraints

1 <= n <= 10^4; circular array.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 3Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]nextGreaterElements(int[]nums)DEFINE n = nums.lengthDEFINE [] res = new int[n]Arrays.fill(res, -1)Stack<Integer> stack = newStack<>()for (int i = 0; i < 2* n; i++)DEFINE num = nums[i % n]while(!stack.isEmpty() &&nums[stack.peek()] …res[stack.pop()] = numif (i < n)stack.push(i)RETURN resDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt()DEFINE [] nums = new int[n]for (int i = 0; i <nums.length; i++)nums[i] = sc.nextInt()System.out.println(Arrays.toString(nextGreaterElements(nums)))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