oneby7

Linked Lists Reversing and rewiring

308. Next Greater Node In Linked List

Medium

You are given head, the first node of a singly linked list. For each node, look at the nodes after it, from the head side towards the tail.

The next greater node of a node is the first node after it whose value is larger. An equal value is not larger. If no node after it is larger, the node has no next greater node.

Return an array answer with one entry per node, in list order. answer[i] is the value of the next greater node of the node at position i, counting from 0 at the head, or 0 if it has none.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6.

Example 1

5249438

Input: head = [5, 2, 4, 9, 4, 3, 8]

Output: [9,4,9,0,8,8,0]

Explanation: After 2, the first larger value is 4. The first 4 is followed straight away by 9, and 5 also gets 9, because 2 and 4 are smaller than 5. Nothing after 9 is larger, so it gets 0. The second 4 and the 3 both get 8. The 8 is the last node, so it gets 0.

Example 2

8838

Input: head = [8, 8, 3, 8]

Output: [0,0,8,0]

Explanation: An equal value is not larger, so every 8 gets 0. The first node after 3 is an 8, which is larger.

Example 3

12941

Input: head = [12, 9, 4, 1]

Output: [0,0,0,0]

Explanation: The values only fall, so no node has a larger one after it.

Check your understanding

Work out the answer for this input before you write any code.

head = [2, 4, 7, 3, 5]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • 1 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.