Skip to contentKEEP THE CRAFTTHE SANCTUARY

Previous Smaller Element

For each value, find the nearest earlier value that is strictly smaller.

The problem

Implement previous_smaller_indices(values). For each index i, find the nearest index j < i with values[j] < values[i] (strictly smaller) and use j as the answer for i; use -1 when no earlier value is smaller. Return the list of answers, one per index. For example, [3, 1, 4, 2, 5] gives [-1, -1, 1, 1, 3], and [2, 2, 3] gives [-1, -1, 1]. values may be empty.

Starter code

def previous_smaller_indices(values):
    pass

Public examples

  1. values = [3, 1, 4, 2, 5]gives[-1, -1, 1, 1, 3]
  2. values = [2, 2, 3]gives[-1, -1, 1]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.