|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +We are given a linked list with head as the first node. Let's number the nodes |
| 4 | +in the list: node_1, node_2, node_3, ... etc. |
| 5 | +
|
| 6 | +Each node may have a next larger value: for node_i, next_larger(node_i) is the |
| 7 | +node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest |
| 8 | +possible choice. If such a j does not exist, the next larger value is 0. |
| 9 | +
|
| 10 | +Return an array of integers answer, where answer[i] = next_larger(node_{i+1}). |
| 11 | +
|
| 12 | +Note that in the example inputs (not outputs) below, arrays such as [2,1,5] |
| 13 | +represent the serialization of a linked list with a head node value of 2, second |
| 14 | +node value of 1, and third node value of 5. |
| 15 | +
|
| 16 | +Example 1: |
| 17 | +Input: [2,1,5] |
| 18 | +Output: [5,5,0] |
| 19 | +
|
| 20 | +Example 2: |
| 21 | +Input: [2,7,4,3,5] |
| 22 | +Output: [7,0,5,5,0] |
| 23 | +
|
| 24 | +Example 3: |
| 25 | +Input: [1,7,5,1,9,2,5,1] |
| 26 | +Output: [7,9,9,9,0,5,0,0] |
| 27 | +
|
| 28 | +Note: |
| 29 | +1 <= node.val <= 10^9 for each node in the linked list. |
| 30 | +The given list has length in the range [0, 10000]. |
| 31 | +""" |
| 32 | + |
| 33 | +# Definition for singly-linked list. |
| 34 | +class ListNode: |
| 35 | + def __init__(self, x): |
| 36 | + self.val = x |
| 37 | + self.next = None |
| 38 | + |
| 39 | + |
| 40 | +from typing import List |
| 41 | + |
| 42 | + |
| 43 | +class Solution: |
| 44 | + def nextLargerNodes(self, head: ListNode) -> List[int]: |
| 45 | + """ |
| 46 | + If input is an array, use stack from right to left. Maintain a decreasing stack |
| 47 | +
|
| 48 | + How to make it one-pass? Maintain a stack from left to right for the element |
| 49 | + waiting for the next larger node |
| 50 | + """ |
| 51 | + ret = [] |
| 52 | + stk = [] # [[index, value]] |
| 53 | + i = 0 |
| 54 | + cur = head |
| 55 | + while cur: |
| 56 | + while stk and stk[-1][1] < cur.val: |
| 57 | + idx, _ = stk.pop() |
| 58 | + ret[idx] = cur.val |
| 59 | + |
| 60 | + stk.append([i, cur.val]) |
| 61 | + ret.append(0) |
| 62 | + cur = cur.next |
| 63 | + i += 1 |
| 64 | + |
| 65 | + return ret |
0 commit comments