Finding next greater node for each node in JavaScript

We are required to write a JavaScript function that takes in the head of a linked list as the first and only argument.

This linked list contains numerical data. Each node in the list may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0.

Our function should prepare and return an array in which the corresponding element is the next greater element for the element in the list.

Problem Example

For a linked list: 2 ? 7 ? 4 ? 3 ? 5

2 7 4 3 5 Result: [7, 0, 5, 5, 0]

The expected output should be:

[7, 0, 5, 5, 0]

Output Explanation

The next greater element of 2 is 7, for 7 there is no greater element (so 0), for 4 it's 5, for 3 it's 5, and for 5 there's no greater element (so 0).

Solution Using Stack Approach

We use a stack to efficiently track elements waiting for their next greater element. The algorithm processes each node once and maintains indices of elements that haven't found their next greater element yet.

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
        this.size = 0;
    }
    
    add(data) {
        const newNode = new Node(data);
        let curr;
        if (this.head === null) {
            this.head = newNode;
        } else {
            curr = this.head;
            while (curr.next) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        this.size++;
    }
}

const list = new LinkedList();
list.add(2);
list.add(7);
list.add(4);
list.add(3);
list.add(5);

const nextGreater = (head) => {
    const arr = [];  // Stack to store [index, value] pairs
    const res = [];  // Result array
    let curr = head;
    let currentIndex = 0;
    
    while (curr) {
        // While stack is not empty and current element is greater than stack top
        while (arr.length > 0 && curr.data > arr[arr.length - 1][1]) {
            const [index] = arr.pop();
            res[index] = curr.data;  // Found next greater element
        }
        
        // Push current element with its index
        arr.push([currentIndex, curr.data]);
        currentIndex += 1;
        curr = curr.next;
    }
    
    // Fill remaining positions with 0 (no next greater element)
    for (let i = 0; i < currentIndex; i++) {
        if (res[i] === undefined) {
            res[i] = 0;
        }
    }
    
    return res;
};

console.log(nextGreater(list.head));
[ 7, 0, 5, 5, 0 ]

How It Works

The algorithm uses a monotonic decreasing stack:

  1. Traverse the linked list from left to right
  2. For each element, pop from stack all elements smaller than current element
  3. For popped elements, current element is their next greater element
  4. Push current element to stack
  5. Elements remaining in stack have no next greater element (set to 0)

Time and Space Complexity

Complexity Value Explanation
Time O(n) Each element is pushed and popped at most once
Space O(n) Stack and result array space

Conclusion

The stack-based approach efficiently finds the next greater element for each node in a linked list with O(n) time complexity. Each element is processed exactly once, making it optimal for this problem.

Updated on: 2026-03-15T23:19:00+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements