Start learning free

LESSON 232 OF 671 · SETS

First Repeat in Java: Finding a Duplicate with a HashSet

Practice Read the full explanation

Given an array of integers nums, read it from left to right and return the first value that appears for the second time.

If no value appears twice, return -1.

 

Example 1:

Input: nums = [3, 1, 4, 1, 3]
Output: 1
Explanation: Reading from the left: 3, 1, 4, then 1 again. The second 1 (index 3) comes before the second 3 (index 4), so the answer is 1, although 3 showed up first.

Example 2:

Input: nums = [2, 7, 9]
Output: -1
Explanation: Every value appears once, so nothing repeats.

Example 3:

Input: nums = [6, 6, 6, 6]
Output: 6
Explanation: The second 6, at index 1, is already a repeat.

 

Constraints:

  • nums has at least one number.
  • Every number is between 0 and 109, so -1 always means that no value repeats.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · SETS

    First Repeat in Java, explained

    Problem overview

    The method firstRepeat receives an array of integers, nums. Read it from left to right and return the first value that appears for the second time, or -1 if no value repeats. Every number is between 0 and a billion, so -1 never clashes with a real answer.

    For [3, 1, 4, 1, 3] the answer is 1. Reading from the left you meet 3, 1, 4, and then 1 again. The second 1, at index 3, comes before the second 3, at index 4, so 1 is the answer even though 3 appeared first. [2, 7, 9] has no repeat and gives -1. [6, 6, 6, 6] gives 6: the second 6, at index 1, is already a repeat.

    Approach: remember what you have seen

    Walk through the array and keep a set of the values met so far. At each number, ask the set whether it already holds it. If yes, this is the second appearance, and because you read left to right, no earlier number could have repeated, or the method would have returned already. If not, remember the number and move on. If the loop ends, nothing repeated.

    The check must come before the add. A number that is added first is always found, so every element, including the first, would look like a repeat.

    Step by step

    1. Create the empty set. HashSet<Integer> seen = new HashSet<>(); holds the values read so far. Nothing has been read at the start.
    2. Loop left to right with for (int num : nums). The enhanced for loop goes through the array in index order.
    3. Check first. seen.contains(num) is true if num is in the set. Then return num ends the method on the spot.
    4. Then add. seen.add(num) records the number for the later elements.
    5. Return -1 after the loop. Reaching it means the loop never returned, so no value appeared twice.

    The solution in Java

    class Solution {
        public int firstRepeat(int[] nums) {
            HashSet<Integer> seen = new HashSet<>();
            for (int num : nums) {
                if (seen.contains(num)) {
                    return num;
                }
                seen.add(num);
            }
            return -1;
        }
    }
    

    This is how the set grows on [3, 1, 4, 1, 3] until the method returns:

    3 -> [3]
    1 -> [1, 3]
    4 -> [1, 3, 4]
    repeat 1
    

    The array has a second 3 at index 4, but the loop never reaches it: the method returns at index 3.

    Java details worth knowing:

    • return inside a loop. It leaves the whole method, not just the loop, so nothing after the repeat is read.
    • A shorter form. add returns false when the value was already in the set, so if (!seen.add(num)) return num; checks and adds in one call. It gives the same answers: 1 for [3, 1, 4, 1, 3], -1 for [2, 7, 9] and 6 for [6, 6, 6, 6]. The lesson's two statements make the order of check and add visible.
    • Autoboxing. contains(num) and add(num) take an Integer, so the int is boxed. The set compares by value, not by reference.
    • Why -1 works. Because the numbers are never negative, a real answer can't equal -1. If negative numbers were allowed, a flag or an exception would be needed to tell the two cases apart.

    Complexity

    Time: O(n) for n numbers, since contains and add cost a constant amount on average. Space: O(n) in the worst case, when there is no repeat and every value goes into the set.

    Edge cases and common mistakes

    • Adding before checking. The check always succeeds, so the method returns nums[0] every time.
    • Returning the first value that appears twice anywhere. That is a different question. Here the answer is the one whose second appearance comes first, which is why [3, 1, 4, 1, 3] gives 1 and not 3.
    • Returning after the loop inside the if. Putting return -1 in the else of the check would end the method at the first non-repeat.
    • Zero. It is a valid value: [0, 5, 0] returns 0, which is not "no repeat".
    • A single number. The loop adds it and ends, and the method returns -1.

    Testing

    • [3, 1, 4, 1, 3] gives 1.
    • [2, 7, 9] gives -1.
    • [6, 6, 6, 6] gives 6.
    • [0, 5, 0] gives 0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free