Top 5 Array Interview Problems in Java (With Real-World Solutions)

9.69K 0 0 0 0

Problem #1: Find the First Repeating Element in an Array

🧠 Problem Statement

Given:
An array of integers.

Task:
Find the first element that repeats. The second occurrence should be the earliest among all repeating elements.

Return:
The repeating element. If none exists, return -1.


🧾 Sample Input/Output

Input:
int[] arr = {10, 5, 3, 4, 3, 5, 6};
Output:
5
Explanation:
Both 5 and 3 repeat, but 5 repeats first in the array.


🔍 Naive Brute-Force Approach

Compare every element with every other element that comes after it.

public static int firstRepeatingNaive(int[] arr) {

    for (int i = 0; i < arr.length; i++) {

        for (int j = i + 1; j < arr.length; j++) {

            if (arr[i] == arr[j]) {

                return arr[i];

            }

        }

    }

    return -1;

}

Time Complexity: O(n²)
Space Complexity: O(1)

Works, but too slow for large arrays.


Optimized Approach Using HashSet

Track seen elements using a Set while traversing the array in reverse.

import java.util.*;

 

public class RepeatingElement {

    public static int firstRepeatingElement(int[] arr) {

        Set<Integer> seen = new HashSet<>();

        int result = -1;

 

        for (int i = arr.length - 1; i >= 0; i--) {

            if (seen.contains(arr[i])) {

                result = arr[i]; // This is the earliest repeated from right

            } else {

                seen.add(arr[i]);

            }

        }

 

        return result;

    }

 

    public static void main(String[] args) {

        int[] arr = {10, 5, 3, 4, 3, 5, 6};

        System.out.println(firstRepeatingElement(arr)); // Output: 5

    }

}


Why Reverse Loop?

Because it ensures we find the first repeating element (in original order) — the earliest second occurrence.


🧠 Edge Cases

Input

Output

Explanation

{1, 2, 3, 4, 5}

-1

No repeats

{2, 2, 3, 4, 5}

2

Immediate repeat at the start

{5, 1, 2, 3, 1, 2}

1

1 repeats before 2 again

{}

-1

Empty array


📈 Time & Space Complexity

Complexity

Value

Time

O(n)

Space

O(n) (for HashSet)


TuteeHub (1)

🧨 Interview Variants

  1. "Return the index of first repeating element"
    👉 Track both value and index using Map<Integer, Integer>
  2. "Return all repeating elements"
    👉 Use Map<Integer, Integer> to count frequency
  3. "In-place solution?"
    👉 Only if values are in known limited range (e.g. 1 ≤ arr[i] ≤ n)

Recap: Key Takeaways


  • Use Set to detect duplicates efficiently
  • Reverse traversal gives correct repeat order
  • Watch out for multiple correct-looking repeats
  • O(n²) brute-force may pass small test cases — not optimal for large data

Back

FAQs


1. Why are array problems so common in Java interviews?

Because they test core programming logic, data handling, loops, and algorithm efficiency.

2. What’s the difference between int[] and Integer[] in Java?

int[] is a primitive array; Integer[] is an array of objects (wrappers). The latter allows null values and works with collections.

3. Is it better to use Arrays or ArrayLists in interviews?

For fixed-size problems, use arrays. For dynamic data, ArrayList is better — but stick to arrays unless otherwise asked

4. What are common pitfalls in Java array questions?

Index out of bounds, mutating arrays while iterating, and forgetting that Java arrays have fixed size.

5. How do I remove duplicates from a Java array?

Use a Set for uniqueness or sort the array first and remove duplicates in-place using two pointers.

6. When should I use the two-pointer technique?

It’s great for sorted arrays, especially for problems involving pair sums, removing duplicates, and reversing data in-place.

7. How can I rotate an array in Java?

Use reversal techniques or cyclic replacements to do it in O(1) space.

8. What’s the time complexity of array search vs binary search?

Linear search = O(n); binary search = O(log n), but only on sorted arrays.

9. How do I handle negative numbers or large input arrays?

Always consider edge cases: empty arrays, one element, all duplicates, etc. Optimize with hashmaps or prefix sums where needed.

10. What libraries or classes help with arrays in Java?

Use Arrays.sort(), System.arraycopy(), Arrays.toString(), and Collections when applicable — but show the manual solution first in interviews.