BudiBadu Logo

Find Index

Array Easy 3 views
Like22

Ever found yourself looking for a specific item in a crowded box? That’s exactly what Find Index is all about! You’re given an array of integers and a target value. Your mission is to find the position (the index) where that target first appears in the list. If it’s not there at all, return -1.

The "secret sauce" here is a Linear Search. You start at the very beginning (index 0) and check each item one by one. Think of it like a basic "Is this it?" question. As soon as you find a match, you return that index and stop searching. If you reach the very end without finding it, you provide the standard "not found" signal of -1. It’s a simple, fundamental process that forms the basis of all search-related algorithms.

This challenge is a great way to master basic array indexing and loops. It’s a simple but effective exercise that builds the foundation for more complex data retrieval tasks!

Examples

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 - Budibadu
Recommendation Algorithm Flow for Find Index - Budibadu

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