Code Logo

Find Index

Published at10 Jan 2026
Easy 5 views
Like22

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
Input
nums = [10, 20, 30], target = 20
Output
1
Explanation

Example 1: Target 20 is at index 1

Example 2
Input
nums = [10, 20, 30], target = 40
Output
-1
Explanation

Example 2: Target 40 is not found

Example 3
Input
nums = [5, 5, 5], target = 5
Output
0
Explanation

Example 3: Target 5 first appears at index 0

Algorithm Flow

Recommendation Algorithm Flow for Find Index
Recommendation Algorithm Flow for Find Index

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:

for (let i = 0; i < nums.length; i++) {
  if (nums[i] === target) {
    return i;
  }
}

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:

return -1;

This solution runs in O(n) time and uses O(1) extra space.

Best Answers

java
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;
    }
}