#1019

Next Greater Node In Linked List

Medium
ArrayLinked ListStackMonotonic StackStackMonotonic Stack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a stack allows us to efficiently keep track of nodes for which we haven't yet found the next greater value. This way, we can find the next greater node in a single pass through the list.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty stack and an array to hold results, initialized to 0.
  2. 2Step 2: Traverse the linked list while pushing indices of nodes onto the stack.
  3. 3Step 3: For each node, while the stack is not empty and the current node's value is greater than the value at the index stored at the top of the stack, pop from the stack and set the result for that index.
solution.py17 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def nextLargerNodes(head):
8    result = []
9    stack = []
10    current = head
11    while current:
12        result.append(0)
13        while stack and current.val > result[stack[-1]]:
14            result[stack.pop()] = current.val
15        stack.append(len(result) - 1)
16        current = current.next
17    return result

Complexity note: This complexity is due to a single pass through the list and using a stack to store indices, which takes linear space.

  • 1Using a stack helps efficiently track the next greater elements.
  • 2The problem can be solved in a single pass with a stack, reducing time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.