Advertisement
Home Data Structure Arrays Check if an Array Contains Repeated Pairs

Check if an Array Contains Repeated Pairs

0
Advertisement

Title: Check if an Array Contains Repeated Pairs

In this guide, you’ll learn how to check whether a Java array contains repeated pairs of equal elements. It’s a common warm-up question in coding interviews because it rewards frequency-based thinking over brute-force nested loops.

We’ll pin down exactly what a repeated pair means, walk through an efficient HashMap-based solution, trace it step by step on a sample input, and cover the mistakes and edge cases an interviewer expects you to raise on your own.

Understanding the Problem

A pair is two elements sitting at different indices that hold the same value. Given an array of integers, the question is whether we can form at least two such pairs without reusing any index.

In {4, 8, 4, 8} the value 4 forms one pair and the value 8 forms another, so this array contains repeated pairs. In {6, 6, 1, 2, 3} only the two 6s form a pair, and there is no second pair anywhere else, so this array does not qualify.

A single value that appears four times, like {2, 2, 2, 2}, still only contributes two pairs, not four, because each pair consumes two of the four occurrences.

Approach

  1. Guard against a null array or an array with fewer than four elements, since four elements are the minimum needed to form two disjoint pairs.
  2. Create a HashMap named frequency to track how many times each value has been seen so far.
  3. Initialize a counter pairCount to 0.
  4. Traverse the array once. For each value, increment its entry in frequency.
  5. Each time an updated frequency becomes even, increment pairCount, because an even count means the value has just completed a new pair.
  6. If pairCount reaches 2 at any point, return true immediately.
  7. If the loop finishes without pairCount reaching 2, return false.

Java Program

Java
import java.util.HashMap;
import java.util.Map;

public class RepeatedPairsChecker {

    public static boolean hasRepeatedPairs(int[] arr) {
        if (arr == null || arr.length < 4) {
            return false;
        }

        Map<Integer, Integer> frequency = new HashMap<>();
        int pairCount = 0;

        for (int value : arr) {
            int updatedCount = frequency.getOrDefault(value, 0) + 1;
            frequency.put(value, updatedCount);

            if (updatedCount % 2 == 0) {
                pairCount++;
            }

            if (pairCount >= 2) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] arr1 = {7, 7, 7, 7, 2, 9};
        System.out.println(hasRepeatedPairs(arr1));

        int[] arr2 = {1, 2, 3, 4, 5, 6};
        System.out.println(hasRepeatedPairs(arr2));
    }
}

Explanation of the Program

The hasRepeatedPairs method does all of its work in a single pass over the array.

  • frequency.getOrDefault(value, 0) + 1 computes the new count for value without a separate lookup and insert.
  • The check updatedCount % 2 == 0 fires exactly once per completed pair, so a value seen four times contributes two pairs instead of one.
  • Returning as soon as pairCount reaches 2 avoids scanning the rest of the array once the answer is already known.
  • main demonstrates both outcomes: an array that reaches two pairs quickly, and one with no repeated values at all.

Step-by-Step Trace

Let’s trace hasRepeatedPairs on {3, 5, 3, 5, 3, 8}, which should return true.

Iterationarr[i]frequency after updatepairCount (before)pairCount (after)
13{3=1}00
25{3=1, 5=1}00
33{3=2, 5=1}01
45{3=2, 5=2}12

The loop exits immediately after iteration 4, once pairCount reaches 2, without inspecting the remaining 3 and 8.

At the end of each iteration, pairCount holds the number of values whose occurrences so far have completed a full pair.

Examples

Example 1: Two Different Repeated Values

Two distinct values each appear twice, so the method finds two pairs and returns early.

Java
int[] arr = {4, 8, 4, 8, 15, 16, 15, 16};
boolean result = hasRepeatedPairs(arr);
System.out.println(result);
// Output: true

Example 2: One Value Repeated Four Times

A single value occurring four times still produces two pairs, since every even occurrence count closes out a new pair.

Java
int[] arr = {9, 9, 9, 9};
boolean result = hasRepeatedPairs(arr);
System.out.println(result);
// Output: true

Example 3: Only One Pair Present

Only one value repeats, so the method never reaches a pairCount of 2 and correctly returns false.

Java
int[] arr = {6, 6, 1, 2, 3};
boolean result = hasRepeatedPairs(arr);
System.out.println(result);
// Output: false

Common Mistakes to Avoid

These are the mistakes learners most often make when solving this exact problem.

  • Treating one repeat as the whole answer – returns true as soon as any value is seen twice, so {6, 6, 1, 2, 3} incorrectly reports true. Require pairCount to reach 2, not 1, before returning true.
  • Incrementing pairCount on every count of 2 or more – treats a value seen three times as two pairs instead of one, overcounting on inputs like {5, 5, 5}. Only increment when the updated count is exactly even.
  • Skipping the null and length guard – throws a NullPointerException on arr.length when the array is null, or wastes a full scan on arrays with fewer than four elements that can never hold two disjoint pairs. Check arr == null || arr.length < 4 before building the frequency map.
  • Resetting the frequency map partway through - clearing or rebuilding frequency mid-loop loses counts already collected and undercounts later pairs. Build the map once across the full array in a single pass.
  • Comparing every index pair with nested loops - works but costs quadratic O(n*n) time, which is unnecessary when a single HashMap pass solves it in O(n).

Edge Cases to Test

Mention these cases out loud during an interview, even before being asked.

  • Empty array
  • Array with fewer than four elements
  • All elements identical
  • Exactly one repeated pair present
  • Multiple values each repeated
  • Negative numbers and zero
  • Integer.MIN_VALUE / Integer.MAX_VALUE present
  • Null array reference

Additional Considerations

The HashMap approach runs in O(n) time, since it visits each element once, and uses O(n) additional space in the worst case, when every value in the array is distinct.

If the array can be sorted first, an alternative is to sort it in O(n log n) time and then scan for adjacent equal elements, counting a pair whenever two matching elements line up next to each other. This drops extra space to O(1) but costs more time overall and only works if mutating or copying the input before sorting is acceptable.

Values like Integer.MIN_VALUE and Integer.MAX_VALUE are worth testing because autoboxing into the HashMap must behave the same at the extremes of the int range as it does for small values. Nothing in this algorithm adds or subtracts array values, so there's no overflow risk, but it's still good practice to confirm boundary values are counted correctly. A null array reference deserves its own test too, since skipping the guard turns a normal input check into a crash.

Interview Follow-up Questions

Once you've nailed the base solution, expect an interviewer to push further with questions like these.

  • What if the array is already sorted? - scan once and count a pair whenever two adjacent elements match, which needs only O(1) extra space instead of a HashMap.
  • What if you need the exact number of repeated pairs, not just whether two exist? - remove the early return and sum count / 2 for every value's final frequency instead of stopping at two.
  • What if the array is read-only and you cannot allocate extra space? - sorting is off the table since it mutates the array, so you'd need an in-place technique such as marking visited indices, trading simplicity for the space constraint.
  • What if the values arrive as an unbounded stream instead of a fixed array? - keep the same frequency map and pairCount logic, update it per incoming value, and report true the moment pairCount reaches two, with no need to know the stream's length in advance.

Conclusion

Checking for repeated pairs is a great example of trading a brute-force nested loop for a single pass backed by a HashMap. The key insight, that a pair is only complete when a value's count turns even, is what keeps the solution both correct and fast.

Try adapting hasRepeatedPairs to count pairs instead of just detecting them, or to work directly on a sorted array. You can learn more about array-based interview problems in our Arrays category.