Linear Search in Java: Solution, Explanation & Practice

Find an element in an array

Problem summary

Search for element 30 in array [10, 20, 30, 40, 50] and print its index.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        int target = 30;
        
        // Find index of target
        // Print: Found at index: <index> OR Not found
    }
}

Expected output and test cases

  • Find 30 in array
    Found at index: 2

Hints

  1. Loop through each element
  2. Compare with target value
  3. Return index when found

Validated solution

Reveal Java solution
public class Main {
    static int indexOf(int[] values, int target) {
        for (int index = 0; index < values.length; index++) {
            if (values[index] == target) return index;
        }
        return -1;
    }

    public static void main(String[] args) {
        int index = indexOf(new int[] {10, 20, 30, 40, 50}, 30);
        System.out.println("Found at index: " + index);
    }
}

How to approach the problem

Linear search has no ordering requirement. Inspect positions from left to right and return immediately on the first match; -1 is a clear sentinel because it is never a valid index.

Approach

  1. Start at index zero.
  2. Compare each value to target.
  3. Return -1 only after the entire array has been checked.

Time and space complexity

Time: O(n). Space: O(1).

Edge cases to test

  • An empty array immediately returns -1.
  • For duplicate targets, this version deliberately returns the first index.

Common mistakes

  • Looping with index <= values.length.
  • Returning zero when a target is not found, which collides with a valid index.

Follow-up challenge

Return every matching index and compare the added memory cost with a callback-based design.

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler