Find the Index of a Target in a Sorted Array of Distinct Integers
VisaSoftware Engineer · OnsiteLast updated
Practice locating a target value in a strictly increasing array of distinct integers, returning its zero-based index or -1 when it is absent. The task checks logarithmic-time search over sorted data, precise loop boundaries, and correct handling of single-element arrays and values that fall between or outside the stored elements.
Given an array nums of distinct integers sorted in strictly increasing order and an integer target, return the position of target in nums. If target is not present, return -1.
Function Signature
def find_target_index(nums: list[int], target: int) -> int:
Rules
- Positions are 0-based: the first element of
numsis at index 0. - Because the values in
numsare distinct,targetappears at most once, so the returned index is unique. - Return
-1if and only iftargetdoes not occur innums. - Do not modify
nums. - The algorithm must run in $O(\log n)$ time, where $n$ is the length of
nums.
Constraints
1 <= len(nums) <= 10^4-10^4 < nums[i] < 10^4for every indexi-10^4 < target < 10^4nums[i] < nums[i + 1]for every0 <= i < len(nums) - 1(strictly increasing, so there are no duplicates)- All values are well within the 32-bit signed integer range.
Examples
Example 1
Input: nums = [-7, -2, 0, 4, 11, 15], target = 4
Output: 3
nums[3] is 4.
Example 2
Input: nums = [-7, -2, 0, 4, 11, 15], target = 5
Output: -1
5 would fall between 4 and 11, but it is not in the array.
Example 3
Input: nums = [8], target = 8
Output: 0
The only element is the target.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.