Beginner Array Problems Java

Linear Search in Java: Program and Logic

Return the first index of a target in an array, or -1 if it is missing.

  • TimeO(n)
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

Linear search in Java checks array elements one by one from index 0. If an element equals the target, return its index at once. If the loop ends with no match, return -1. It works on sorted and unsorted arrays, takes O(n) time in the worst case and uses O(1) extra space.

Linear searchArray traversalEarly return
1

Problem statement

Write a program for linear search in Java. Given an int array and a target, return the index of the first match, or -1 if the target is not present.

The array can be in any order. That is the main advantage over binary search, which needs sorted data.

Input

An integer array arr of length n and an integer target.

Output

The first index of target, or -1.

Examples

Example 1
Inputarr = [12, 45, 7, 30, 9], target = 30
Output3

30 is at index 3.

Example 2
Inputarr = [12, 45, 7, 30, 9], target = 8
Output-1

All five elements are checked and none equals 8.

Constraints

  • 0 <= n <= 10^6
  • Elements may repeat and may be in any order
2

Think before you code

Reveal the questions to ask yourself first
  • How do you visit every element with its index?
  • Can you stop early?
  • At what point are you sure the target is missing?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Use a for loop with an index, since you must return a position.
2 Hint 2
Return as soon as you see a match.
3 Hint 3
Put return -1 after the loop, not in an else inside it.
4

Approach

Reveal the step-by-step approach
  1. Start at index 0.
  2. Compare arr[i] with the target.
  3. If they are equal, return i.
  4. If not, move to the next index.
  5. After the loop, return -1.
Case When Checks
Best Target is first 1, so O(1)
Worst Target is last or missing n, so O(n)
Average Target equally likely at each index About n / 2, so O(n)
5

Dry run

Walk through the example step by step

Target 30 in [12, 45, 7, 30, 9]:

i | arr[i] | equal to 30? | action
--+--------+--------------+---------
0 | 12     | no           | continue
1 | 45     | no           | continue
2 | 7      | no           | continue
3 | 30     | yes          | return 3

Index 4 is never checked.

6

Solution

Reveal the full Java solution
Solution.java
public class LinearSearch {
    static int search(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {12, 45, 7, 30, 9};
        System.out.println(search(arr, 30));
        System.out.println(search(arr, 8));
    }
}

Output of this linear search in Java code:

3
-1

Linear search in Java using Scanner

The user types the size, the elements, and then the value to find.

import java.util.Scanner;

public class LinearSearchInput {
    // Sample input: 5 12 45 7 30 9 7
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        int target = sc.nextInt();
        int pos = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] == target) {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            System.out.println(target + " not found");
        } else {
            System.out.println(target + " found at index " + pos);
        }
    }
}

Output for the sample input:

7 found at index 2

For a linear search in Java with user input, you can also print a message before each nextInt() so that the user knows what to type.

Find every match, and search strings

import java.util.ArrayList;
import java.util.List;

public class LinearSearchMore {
    static List<Integer> allIndexes(int[] arr, int target) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                result.add(i);
            }
        }
        return result;
    }

    static int searchName(String[] names, String target) {
        for (int i = 0; i < names.length; i++) {
            if (target.equals(names[i])) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(allIndexes(new int[]{4, 2, 4, 9, 4}, 4));
        String[] names = {"Ravi", "Anu", "Kiran"};
        System.out.println(searchName(names, "Anu"));
    }
}
[0, 2, 4]
1

Use equals for text. == on strings checks if both names point to the same object. Read strings in Java for the reason.

Point Linear search Binary search
Needs sorted data No Yes
Worst time O(n) O(log n)
Good for Small or unsorted data Large sorted data, many searches

Linear search in Java: practice tasks

  1. Return the last index of the target.
  2. Count how many times the target appears.
  3. Search a 2D array and print the row and column.
  4. Find the largest element with one loop, which is the same walk with a different test.

More tasks are in the core Java practice problems. For guided learning, see the Java full stack course.

TimeO(n)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Returning -1 in an else inside the loop, so that only the first element is checked.
  • Looping to i <= arr.length, which throws ArrayIndexOutOfBoundsException when there is no match.
  • Comparing strings with == instead of equals.
  • Forgetting break when storing the position, which returns the last match.

Edge cases to test

  • Empty array returns -1.
  • Target at the first or last index.
  • Repeated target: return the first index.
  • Null array: decide whether to throw an error or return -1.

Interview follow-ups

  • How do you search for the last match?
  • When is linear search a better choice than binary search?
  • How would you search a list of objects by one field?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us