First Unique Element in Java: Solution, Explanation & Practice

Find first element that appears once

Problem summary

Use collections to find the first element in a list that appears exactly once.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 1, 3, 2, 4, 3); // Test case 1
        
        // Find first unique element
        // Print: First unique: <element> OR No unique element
    }
}

Expected output and test cases

  • 4 appears once
    First unique: 4
  • First is unique
    First unique: 1
  • All repeat
    No unique element

Hints

  1. Count frequencies first with Map
  2. Then iterate original list
  3. Find first with count 1

Validated solution

Reveal Java solution
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    static Integer firstUnique(List<Integer> values) {
        Map<Integer, Integer> counts = new LinkedHashMap<>();
        for (int value : values) counts.put(value, counts.getOrDefault(value, 0) + 1);
        for (int value : values) if (counts.get(value) == 1) return value;
        return null;
    }
    public static void main(String[] args) {
        Integer answer = firstUnique(Arrays.asList(2, 3, 2, 3, 4, 5, 5));
        System.out.println(answer == null ? "No unique element" : "First unique: " + answer);
    }
}

How to approach the problem

Frequency alone cannot tell which unique value appeared first, so count first and then scan the original list. A LinkedHashMap is readable here, but the second list scan—not map order—defines the answer.

Approach

  1. Count each value.
  2. Scan the original order again.
  3. Return the first count equal to one.

Time and space complexity

Time: O(n) expected. Space: O(k).

Edge cases to test

  • An empty list has no unique element.
  • The order of values, not the smallest value, decides the answer.

Common mistakes

  • Returning the first map key with count one without preserving list order.
  • Mistaking a value occurring twice for a unique value.

Follow-up challenge

Maintain the first unique number as values arrive in a stream.

Related Collections exercises

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