878955. Find index

Easy

Find Index

Slug: find-index-1614919939--145853

Difficulty: Easy

Id: 878955

Topic Tags: python

Summary

Find the index of a given element in an array. The problem is about searching for an element in a list and returning its position or index.

Detailed Explanation

The problem can be solved using a linear search algorithm, which iterates through the array until it finds the target element.

Here's a step-by-step breakdown:

  1. Initialize two pointers, start and end, to the beginning and end of the array.
  2. Calculate the midpoint between start and end.
  3. Compare the midpoint element with the target element. If they match, return the midpoint index.
  4. If the midpoint element is not the target, update start or end based on whether the target is in the left or right half of the array.
  5. Repeat steps 2-4 until the target is found.

Time complexity: O(n), where n is the length of the array. Space complexity: O(1).

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; // not found
}

DevExCode

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

© 2026 DevExCode. All rights reserved.