Home › Company-wise questions › Microsoft › Next Greater Element I ← Microsoft bank
Microsoft · Question 31 · Stacks
Next Greater Element I Stacks Java code ⏱ O(n+m) 💾 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 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 Sweep nums2 maintaining a decreasing stack. 2 Each popped value maps to its next greater. 3 Answer 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 Flowchart Pseudocode
Time O(n+m)Space O(n)Loops 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static int[] nextGreaterElement(int[] nums1, int[] nums2) Map<Integer, Integer> map = new HashMap<>() Stack<Integer> stack = new Stack<>() for (int num : nums2) while (!stack.isEmpty() && num > stack.peek()) map.put(stack.pop(), num) stack.push(num) DEFINE [] res = new int[nums1.length] for (int i = 0; i < nums1.length; i++) res[i] = map.getOrDefault(nums1[i], -1) RETURN res DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE n1 = sc.nextInt(); int n2 = sc.nextInt() DEFINE [] nums1 = new int[n1]; for (int i = 0; i < n1; i++) nums1[i] … DEFINE [] nums2 = new int[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← Q30 · Daily Temperatures Q32 · Next Greater Element II → 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 →