Skip to content

Commit 424633b

Browse files
committed
Adjusted comments & docstring.
1 parent 36b24e5 commit 424633b

1 file changed

Lines changed: 8 additions & 6 deletions

File tree

data_structures/stacks/kth_next_greater_element.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""
22
Implement the function to find kth Next Greatest Element (NGE) for all elements.
3-
Idea comes from my blog:
4-
https://starsexpress.github.io/SkyHorse/docs/stack/2454_hard/second_next_greater
53
"""
64

75
test_k = 10
@@ -21,7 +19,7 @@ def find_kth_next_greater_element(
2119
it means that this element has found its (j - 1)th NGE, now looking for jth NGE.
2220
2321
By processing stacks from higher to lower ordinals, we can always ensure that
24-
each stack secures decreasing monotonicity in terms of element value.
22+
each stack stays monotonically non-increasing in terms of element value.
2523
2624
Time complexity: O(kn) where n is the length of input array.
2725
However, if k >= n, all elements won't find their respective kth NGE.
@@ -33,7 +31,7 @@ def find_kth_next_greater_element(
3331
array (list[int | float]): A list for which the kth NGE is computed.
3432
A mix of integers and floats in list is allowed.
3533
36-
kth_ord (int): Ordinal of the NGE to find. k must be a positive integer.
34+
kth_ord (int): Ordinal of the NGE to find. kth_ord must be a positive integer.
3735
3836
Returns:
3937
A list containing each element's kth NGE. If an element can't find its kth NGE,
@@ -44,20 +42,24 @@ def find_kth_next_greater_element(
4442
True
4543
>>> find_kth_next_greater_element([2.5, 1.9, 4.3, 6.0], 1) == [4.3, 4.3, 6.0, None]
4644
True
45+
>>> find_kth_next_greater_element([1, 2, 3], 0)
46+
Traceback (most recent call last):
47+
...
48+
ValueError: kth_ord must be a positive integer.
4749
>>> find_kth_next_greater_element(list(range(1000)), 1000) == [None] * 1000
4850
True
4951
>>> find_kth_next_greater_element(test_array, test_k) == expected_answers
5052
True
5153
"""
5254
if not isinstance(kth_ord, int) or kth_ord < 1:
53-
raise ValueError("k must be a positive integer.")
55+
raise ValueError("kth_ord must be a positive integer.")
5456

5557
kth_next_greater_elements: list[int | float | None] = [None] * len(array)
5658
if kth_ord >= len(array): # Trivial cases: nobody can have kth NGE.
5759
return kth_next_greater_elements
5860

5961
# For 1 <= j <= k, the jth stack is at the jth idx of stacks list.
60-
# stacks[0]: a transporter that transfer entries between stacks.
62+
# stacks[0]: a transporter that transfers entries between stacks.
6163
# Each stack's entry is a tuple of (element, idx).
6264
stacks: list[list[tuple[int | float, int]]] = [[] for _ in range(kth_ord + 1)]
6365

0 commit comments

Comments
 (0)