Home › Company-wise questions › Microsoft › Next Greater Element II ← Microsoft bank
Microsoft · Question 32 · Stacks
Next Greater Element II Stacks Java code ⏱ O(n) 💾 O(n)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Walk the doubled array right to left in effect. 2 The 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 Flowchart Pseudocode
Time O(n)Space O(n)Loops 3Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static int[] nextGreaterElements(int[] nums) DEFINE n = nums.length DEFINE [] res = new int[n] Arrays.fill(res, -1) Stack<Integer> stack = new Stack<>() for (int i = 0; i < 2 * n; i++) DEFINE num = nums[i % n] while (!stack.isEmpty() && nums[stack.peek()] … res[stack.pop()] = num if (i < n) stack.push(i) RETURN res DEFINE static void main(String[] args) java.util.Scanner sc = new java.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← Q31 · Next Greater Element I Q33 · Baseball Game → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →