すべてのチャレンジ
中級 0件解決済み 正答率0%

Nearest Smaller Value to the Left

For each number, find the closest earlier position containing a strictly smaller number.

このチャレンジで学べること

  • Keep a stack of useful candidates
  • Pop values that can never be the answer
  • Solve the problem in linear time

問題

翻訳を表示

For each number, find the closest earlier position containing a strictly smaller number. Equal numbers do not qualify. Positions start at 1; use 0 when there is no smaller number to the left.

Implement nearest_smaller_value(numbers).

Input

numbers: Numbers in their original order.

Output

Return one earlier position (or 0) for every input value.

制約

0…200,000 integers, each between −1,000,000,000 and 1,000,000,000. Empty input returns an empty list.

例

例 1
入力:
numbers = [4, 2, 5, 3]

期待される出力:
expected = [0, 0, 2, 2]
入力:
std::vector<long long> numbers = {4, 2, 5, 3};

期待される出力:
std::vector<long long> expected = {0, 0, 2, 2};
入力:
long[] numbers = new long[] {4, 2, 5, 3};

期待される出力:
long[] expected = new long[] {0, 0, 2, 2};

解説

4 has no earlier value and 2 has no smaller earlier value. Both 5 and 3 find the value 2 at position 2.

例 2
入力:
numbers = [2, 2, 2]

期待される出力:
expected = [0, 0, 0]
入力:
std::vector<long long> numbers = {2, 2, 2};

期待される出力:
std::vector<long long> expected = {0, 0, 0};
入力:
long[] numbers = new long[] {2, 2, 2};

期待される出力:
long[] expected = new long[] {0, 0, 0};

解説

Earlier equal values are not strictly smaller. Every answer is 0.

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

For each position, you need the closest earlier value that is strictly smaller, not smaller-or-equal.

ヒント 2

Maintain a monotonic stack of candidate values with their positions while scanning left to right.

ヒント 3

Pop equal or larger values, since they can never be the nearest smaller answer for later elements.

目安の計算量

O(n) time, O(n) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。