You're given an Array height
which represents the heights of steps in a staircase. Return an Array where each entry contains the number of steps you need to walk in order to get to a higher step. If there's no such step, return infinity.
Example:
Explanation: The first, 3rd, 4th, and 5th step don't have a higher step after them, so we give infinity for them. The 2nd step needs to walk 2 steps and the 3rd step needs to walk 1 step in order to get to a higher step.
You can solve this problem with brute-force, but this is slow and takes O(n2) time. Instead, you should look for a solution that takes just a single pass over the array.
To do a single pass, we need to remember the steps that we've visited so we can update them if we ever reach a higher stair. We'll store each step in an array called pending
, to indicate that the steps need to be updated.
When we take a new step, we should check whether the current step is taller than any of the pending
steps. If it is, then we can update those stairs accordingly.
Now we're ready to code this up. Amazingly, all the stairs in the pending
array are always sorted by decreasing height. This is because steps stop pending when the height increases. This lets us efficiently figure out which steps we should update - we can repeatedly pop the rightmost entry in the pending
array to get all the stairs that we should update (the lowest steps).
Here's how you code this up:
Time Complexity O(n). Each step gets added and removed from the pending
array.
Space Complexity O(n). The pending
array can grow to size n.
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()