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:
- Initialize two pointers,
startandend, to the beginning and end of the array. - Calculate the midpoint between
startandend. - Compare the midpoint element with the target element. If they match, return the midpoint index.
- If the midpoint element is not the target, update
startorendbased on whether the target is in the left or right half of the array. - 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
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
}