Binary search · Easy
A sorted numeric index needs an insertion point for a new key. If that key already exists, insertion must happen before all existing equal keys. The index is supplied already sorted; you are not asked to modify it.
Return the first index whose value is at least target, or nums.length if no such index exists.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "nums": number[], "target": number }.
Fields
- nums is sorted in non-decreasing order and may contain duplicates.
- target is the integer key to locate.
Output
Return value
- Return an integer from 0 through nums.length inclusive.
- All elements before that index must be smaller than target.
- At the returned index the element is at least target, unless the index equals the array length.
- An empty array returns 0.
Constraints
- 0 <= nums.length <= 100000.
- Values and target are integers in [-1000000000,1000000000].
- Do not sort the already sorted input or call a linear find/filter operation as the search.
Examples
Example 1
{
"nums": [
1,
2,
2,
5
],
"target": 2
}Returns
1Insert before the first 2.
Example 2
{
"nums": [
1,
2,
2,
5
],
"target": 6
}Returns
4Insert after the final value.
Required complexity
O(log(n + 1)) time and O(1) extra space