AlgoInsight

DSA problem

Next Greater Node In Linked List

MediumMonotonic StackPattern: Monotonic Stacktop600AmazonGoogleMicrosoftBloombergApple

You are given the head of a singly linked list with n nodes. For each node, find the value of the next node in the list that has a strictly greater value. Return an integer array answer of length n where answer[i] is the value of the next greater node after the i-th node (0-indexed), or 0 if there is no such node.

The naive approach walks the entire list once to collect values into an array, then for each index walks forward looking for the next greater value, costing O(n²) total. While simple, it is too slow for n up to 10⁴ in adversarial cases.

This is the classic "next greater element" problem with a linked-list input. The cleanest implementation converts the list to an array in a single linear pass, then runs the standard monotonic-decreasing-stack-of-indices algorithm:

  1. Initialise answer with zeros (the default for "no next greater").
  2. Walk the array i = 0..n-1 maintaining a stack of indices waiting for their answer.
  3. While the stack is non-empty and values[i] > values[stack.top], pop the top j and set answer[j] = values[i].
  4. Push i. Indices left on the stack at the end keep their default 0.

The total time is O(n) and the space is O(n) for the converted array, the stack, and the answer.

Examples

Example 1
Input: head = [2,1,5]
Output: [5,5,0]
Explanation: For node 0 (value 2) the next greater is 5. For node 1 (value 1) the next greater is 5. For node 2 (value 5) there is none.
Example 2
Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]
Explanation: For node 0 (value 2) the next greater is 7. For node 1 (value 7) there is no greater value later. For nodes 2 and 3 the next greater is 5. The tail has no successor.
Example 3
Input: head = [1,7,5,1,9,2,5,1]
Output: [7,9,9,9,0,5,0,0]
Explanation: Track the next greater value for each node; the maximum 9 stops giving answers after index 4.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

monotonic-stackstacklinked-listarray

Browse all DSA problems