← All coding problems
Search Insert Position
easyBinary Search+10 XPTime limit 2s
The array is sorted and has distinct values. Print the index of target if it is present; otherwise print the index where it would be inserted to keep the array sorted.
Input:
- line 1:
n - line 2:
ndistinct integers in increasing order - line 3:
target
Output: one index (0-based, between 0 and n).
Constraints: 1 ≤ n ≤ 10⁵, −10⁴ ≤ a[i], target ≤ 10⁴. Aim for O(log n).
Think about it: this is "the first index whose value is ≥ target" — the lower bound. Write the loop so it ends with lo == hi at exactly that index.
Sample input 1
4 1 3 5 6 5
Sample output 1
2
Sample input 2
4 1 3 5 6 2
Sample output 2
1
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).