Next Greater Node In Linked List

medium linked list array monotonic stack

Problem

Return an array answer where answer[i] is the value of the next node with strictly greater value (0 if none).

Inputhead = [2,1,5]
Output[5,5,0]
Standard "next greater" monotonic stack on the flattened array.

def nextLargerNodes(head):
    a = []
    cur = head
    while cur: a.append(cur.val); cur = cur.next
    res = [0] * len(a)
    st = []
    for i, x in enumerate(a):
        while st and a[st[-1]] < x:
            res[st.pop()] = x
        st.append(i)
    return res
function nextLargerNodes(head) {
  const a = [];
  for (let cur = head; cur; cur = cur.next) a.push(cur.val);
  const res = new Array(a.length).fill(0);
  const st = [];
  for (let i = 0; i < a.length; i++) {
    while (st.length && a[st[st.length - 1]] < a[i]) res[st.pop()] = a[i];
    st.push(i);
  }
  return res;
}
class Solution {
    public int[] nextLargerNodes(ListNode head) {
        List<Integer> a = new ArrayList<>();
        for (ListNode c = head; c != null; c = c.next) a.add(c.val);
        int[] res = new int[a.size()];
        Deque<Integer> st = new ArrayDeque<>();
        for (int i = 0; i < a.size(); i++) {
            while (!st.isEmpty() && a.get(st.peek()) < a.get(i)) res[st.pop()] = a.get(i);
            st.push(i);
        }
        return res;
    }
}
vector<int> nextLargerNodes(ListNode* head) {
    vector<int> a;
    for (auto c = head; c; c = c->next) a.push_back(c->val);
    vector<int> res(a.size(), 0);
    stack<int> st;
    for (int i = 0; i < (int)a.size(); i++) {
        while (!st.empty() && a[st.top()] < a[i]) { res[st.top()] = a[i]; st.pop(); }
        st.push(i);
    }
    return res;
}
Time: O(n) Space: O(n)