Skip to content
RED SAGSkills

Find Position in Sorted Array

Given an array nums of distinct integers sorted in ascending order and a value x, return the index of x in nums. If x is not present, return the index where it would be inserted to keep the array sorted.

Your solution should run in O(log n) time.

Example 1

Input: nums = [2, 5, 8, 13], x = 8
Output: 2

Example 2

Input: nums = [2, 5, 8, 13], x = 6
Output: 2
Explanation: 6 would go between 5 and 8.

Constraints

  • 0 <= nums.length <= 10^5
  • nums is sorted ascending with distinct values.
Hint 1

Search a half-open range [lo, hi).

Hint 2

When the loop ends, lo is the first index whose value is not less than x.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Game Developer, Automation Test Engineer, Database Administrator

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.