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
A straightforward linear scan is enough here. Since we want the first matching index, scanning from left to right naturally gives the correct answer.
We check each element one by one:
The moment we find a match, we return that index immediately. Because the scan goes left to right, this is guaranteed to be the first occurrence.
If the loop ends without finding the target, then the value is not in the array, so we return:
This solution runs in O(n) time and uses O(1) extra space.
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.
