Code Logo

Find Index

Published at10 Jan 2026
1D Array Easy 15 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

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.

function search(nums, target) {
  var left = 0, right = nums.length - 1;
  while (left <= right) {
    var mid = Math.floor((left + right) / 2);
    if (nums[mid] === target) return mid;
    if (nums[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}

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

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