easyBinary SearchPure DSA~13 min
Leaderboard Insert Rank
A leaderboard keeps scores sorted ascending. When a new score arrives, the UI needs the index where it would slot in so it can animate the row into place — without re-sorting the whole board.
Problem
Given a sorted array scores and a target value, return the index at which target should be inserted to keep the array sorted. If target already exists, return the index of its first occurrence.
Input
A sorted array scores of length n (0 ≤ n ≤ 10^5) and integer target.
Output
A single integer — the insertion index in [0, n].
Constraints
- scores is sorted in non-decreasing order
- 0 ≤ n ≤ 100,000
- Values in [-10^9, 10^9]
Examples
Example 1
Input
scores = [1, 3, 5, 6], target = 5
Output
2
5 is already present at index 2.
Example 2
Input
scores = [1, 3, 5, 6], target = 2
Output
1
2 belongs between 1 and 3, at index 1.