Ctrl K

Next Larger on the Right

Easy
You are given a list line of distinct non-negative integers and a list queries of distinct numbers, each of which appears in line. For each query, find where it sits in line and look to the right: the first number larger than the query is its answer. If no larger number follows, the answer is -1. Return the answers in the same order as the queries. The O(len(queries) · len(line)) approach is the obvious one; try for O(len(queries) + len(line)).
Example 1
queries=[7, 2, 9], line=[5, 7, 2, 4, 9, 1] → [9, 4, -1]

To the right of 7 come 2, 4, 9, and the first larger one is 9. For 2 the first larger value is 4. After 9 there is only 1, so the answer is -1.

Example 2
queries=[3], line=[8, 6, 3] → [-1]

3 is last in the line, so nothing is to its right.

Example 3
queries=[10, 0], line=[0, 10, 20] → [20, 10]
Constraints
  • 1 ≤ len(queries) ≤ len(line) ≤ 10⁵
  • 0 ≤ values ≤ 10⁵
  • All numbers in line are distinct, and so are all numbers in queries
  • Every query appears in line
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHard Shifts Take the Lead MediumDiscount From a Cheaper Neighbor EasyWater Between Walls HardBiggest Rectangle Under the Skyline HardBiggest Solid Panel Block Hard
loading Python…
Input
queries=[7, 2, 9], line=[5, 7, 2, 4, 9, 1]
Expected
[9, 4, -1]

Run checks the first 3 tests in your browser. Submit checks all 120 tests on the server, hidden ones included.