In this problem, you are given an array and a target value. Your job is to return the index where that target first appears.
If the target does not exist in the array, the answer should be -1. If the target appears more than once, you do not return all matching positions. You return only the first one.
For example, in [10,20,30] with target 20, the answer is 1. With the same array and target 40, the answer is -1 because 40 is missing. In [5,5,5], the target 5 gives 0 because the first match is at index 0.
So the task is to scan from left to right and return the earliest index whose value equals the target, or -1 if no such index exists.
Example Input & Output
Example 1: Target 20 is at index 1
Example 2: Target 40 is not found
Example 3: Target 5 first appears at index 0
Algorithm Flow
Solution Approach
Given a sorted array and a target value, find the index of the target using binary search. Maintain left and right pointers. Compute mid. If nums[mid] equals target, return mid. If target is smaller, search left half; if larger, search right half. Return -1 if not found.
Binary search halves the search range each iteration, making it exponentially faster than linear search for large sorted arrays.
Time complexity is O(log n), space complexity is O(1).
Best Answers
class Solution {
public int find_index(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) return i;
}
return -1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
