Zepruv › Coding problems

Next Greater Node In Linked List

Medium · Array, Linked List, Stack, Monotonic Stack

You are given the head of a linked list with n nodes.
For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.
Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.

Example 1

Input: head = [2,1,5]
Output: [5,5,0]

Example 2

Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]

Constraints

Starter code (python)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def nextLargerNodes(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: List[int]
        """
        

Related problems

Previous: Binary String With Substrings Representing 1 To N · Next: Number of Enclaves · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.