702694. Find Index

Easy

Find Index

Slug: find-index4752

Difficulty: Easy

Id: 702694

Topic Tags: Arrays, Data Structures

Company Tags: None

Summary

Given an array of integers and a target integer value, write a function to find the index of the target value in the array. The array may contain duplicate values.

This problem involves searching for an element in an array and returning its index. We will use a simple linear search algorithm to solve this problem.

Detailed Explanation

The problem can be solved by iterating through the array and comparing each element with the target value. When we find a match, we return the current index. If the target value is not found in the array, we return -1 or any other appropriate value to indicate that the target is not present in the array.

Here's a step-by-step breakdown of the solution:

  1. Initialize two variables: index and target. Set index to 0 (assuming the array is 0-indexed) and set target to the given target value.
  2. Iterate through the array using a for loop or while loop. For each element in the array:
    • Compare the current element with the target value.
    • If the elements match, return the current index.
  3. If the loop completes without finding a match, return -1 (or any other appropriate value to indicate that the target is not present in the array).

The time complexity of this solution is O(n), where n is the size of the input array. The space complexity is O(1) as we are only using a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public int findIndex(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.