Advanced Java array programs for SDET

These are the "second wave" of array questions in SDET and automation interviews — the ones that follow once you've done sum, largest and duplicates: rotation, missing number, pair with a given sum, majority element, moving zeros, plus counting, merging, comparing and converting arrays.

Every program below comes from one Java class that was compiled and run; the outputs shown are real. Start with the basics in Array Basics & Calculations if you haven't yet.

Advertisement

1. Rotate an Array by k Positions ⭐

Simple approach (by one position):

Save the first element, shift everything left, and put the saved element at the end — O(n). Repeating that k times is O(n × k).

Better — the reversal algorithm:

Reverse the first k elements, reverse the rest, then reverse the whole array. This takes O(n) time and O(1) extra space for any k.

static void rotateLeft(int[] a, int k) {
    int n = a.length;
    k = k % n;                     // rotating by n is the same as not rotating
    reverse(a, 0, k - 1);
    reverse(a, k, n - 1);
    reverse(a, 0, n - 1);
}

static void rotateRight(int[] a, int k) {
    rotateLeft(a, a.length - (k % a.length));
}

static void reverse(int[] a, int i, int j) {
    while (i < j) {
        int t = a[i];
        a[i++] = a[j];
        a[j--] = t;
    }
}

// {10, 20, 30, 40, 50} → left by 2:  [30, 40, 50, 10, 20]
//                        → right by 2: [10, 20, 30, 40, 50]

Follow-up to expect:

"What if k is larger than the array length?"

That's what k % n handles.

2. Find the Missing Number ⭐

An array holds the numbers 1 to n with one missing. The expected sum is n(n + 1) / 2; subtract the actual sum.

static int missingNumber(int[] a, int n) {
    long expected = (long) n * (n + 1) / 2;   // long avoids overflow for large n
    long actual = 0;

    for (int x : a) {
        actual += x;
    }

    return (int) (expected - actual);
}

// XOR version — no overflow at all
static int missingNumberXor(int[] a, int n) {
    int x = 0;

    for (int i = 1; i <= n; i++) {
        x ^= i;
    }

    for (int v : a) {
        x ^= v;
    }

    return x;
}

// {1, 2, 3, 5}, n = 5 → 4 (both methods)

O(n) time, O(1) space.

Mentioning the overflow risk — and the XOR alternative — is what makes this answer stand out.

3. Pair With a Given Sum ⭐

For each number, the "complement" you need is target − number. Keep the numbers you've seen in a HashSet; if the complement is already there, you've found a pair.

static List<String> pairsWithSum(int[] a, int target) {
    Set<Integer> seen = new HashSet<>();
    List<String> pairs = new ArrayList<>();

    for (int x : a) {
        int need = target - x;

        if (seen.contains(need)) {
            pairs.add("(" + need + ", " + x + ")");
        }

        seen.add(x);
    }

    return pairs;
}

// {2, 4, 3, 5, 7, 8, 9}, target 7 → [(4, 3), (2, 5)]

O(n) time and space, versus O(n²) for nested loops.

If the array is sorted, a two-pointer approach — start and end, moving inward — does it in O(n) with O(1) space.

4. Majority Element — Moore's Voting Algorithm

Find the element that appears more than n/2 times.

Keep a candidate and a counter:

  • Same element → count up
  • Different element → count down
  • Count reaches zero → choose a new candidate

Then verify the result. If no majority exists, the candidate is simply the last survivor.

static Integer majority(int[] a) {
    int candidate = 0;
    int count = 0;

    for (int x : a) {
        if (count == 0) {
            candidate = x;
            count = 1;
        } else if (x == candidate) {
            count++;
        } else {
            count--;
        }
    }

    int occurrences = 0; // verification pass

    for (int x : a) {
        if (x == candidate) {
            occurrences++;
        }
    }

    return occurrences > a.length / 2 ? candidate : null;
}

// {2, 2, 1, 2, 3, 2, 2} → 2
// {1, 2, 3, 1, 2}       → null (no majority)

O(n) time, O(1) space.

Forgetting the verification pass is the most common mistake with this algorithm.

5. Move Zeros to the End

Keep a write index: copy every non-zero element forward, then fill the remaining positions with zeros. The order of the other elements is preserved.

static void moveZerosToEnd(int[] a) {
    int write = 0;

    for (int x : a) {
        if (x != 0) {
            a[write++] = x;
        }
    }

    while (write < a.length) {
        a[write++] = 0;
    }
}

// {0, 1, 0, 3, 12} → [1, 3, 12, 0, 0]

Variants:

  • Move zeros to the beginning by iterating from the end.
  • Move negative numbers to the front.

6. Common Elements of Two Arrays

static Set<Integer> common(int[] a, int[] b) {
    Set<Integer> first = new HashSet<>();

    for (int x : a) {
        first.add(x);
    }

    Set<Integer> result = new LinkedHashSet<>(); // unique, in b's order

    for (int x : b) {
        if (first.contains(x)) {
            result.add(x);
        }
    }

    return result;
}

// {1, 2, 3, 4} and {3, 4, 5, 3} → [3, 4]

7. Counting: Even/Odd and Positive/Negative/Zero

static String counts(int[] a) {
    int even = 0;
    int odd = 0;
    int pos = 0;
    int neg = 0;
    int zero = 0;

    for (int x : a) {
        if (x % 2 == 0) {
            even++;
        } else {
            odd++;
        }

        if (x > 0) {
            pos++;
        } else if (x < 0) {
            neg++;
        } else {
            zero++;
        }
    }

    return "even=" + even
        + " odd=" + odd
        + " positive=" + pos
        + " negative=" + neg
        + " zero=" + zero;
}

// {4, -3, 0, 7, -8} → even=3 odd=2 positive=2 negative=2 zero=1

Watch the edge cases:

  • Zero is neither positive nor negative.
  • A check like x >= 0 would incorrectly count zero as positive.
  • -3 % 2 is -1 in Java, which is why the odd branch uses else rather than == 1.

The same single pass can also sum evens and odds or split them into separate lists.

8. Merge, Copy and Compare

static int[] merge(int[] a, int[] b) {
    int[] out = Arrays.copyOf(a, a.length + b.length);
    System.arraycopy(b, 0, out, a.length, b.length);
    return out;
}

// merge({1, 2}, {3, 4, 5}) → [1, 2, 3, 4, 5]

Arrays.equals(
    new int[]{1, 2},
    new int[]{1, 2}
); // true — same length and elements

int[] copy = Arrays.copyOf(
    original,
    original.length
); // independent copy

Remember that == on arrays compares references, not contents.

Use Arrays.equals() when you want to compare array contents.

9. Array ↔ ArrayList

List<Integer> list = new ArrayList<>();

for (int x : new int[]{10, 20, 30}) {
    list.add(x);
}

// ArrayList → Integer[]
Integer[] boxed = list.toArray(new Integer[0]);

// ArrayList → int[]
int[] primitives = list.stream()
    .mapToInt(Integer::intValue)
    .toArray();

Arrays.asList() works for object arrays such as String[], but gives a fixed-size list.

For an int[], it produces a list containing the array itself, which is a classic trap.

10. Separate Even and Odd Elements, and Sum Them

static int[][] splitEvenOdd(int[] a) {
    int evens = 0;
    for (int x : a) if (x % 2 == 0) evens++;
    int[] even = new int[evens], odd = new int[a.length - evens];
    int e = 0, o = 0;
    for (int x : a) { if (x % 2 == 0) even[e++] = x; else odd[o++] = x; }
    return new int[][]{even, odd};
}
static long[] sumEvenOdd(int[] a) {
    long even = 0, odd = 0;
    for (int x : a) { if (x % 2 == 0) even += x; else odd += x; }
    return new long[]{even, odd};
}
splitEvenOdd([4, 7, 10, -3, 0, 5]) → even [4, 10, 0], odd [7, -3, 5]
sumEvenOdd → even 14, odd 9

Test with x % 2 == 0, never x % 2 == 1: in Java -3 % 2 is -1, so the "== 1" version would drop −3 from the odd list. Counting first lets you size the two result arrays exactly; with a List you'd just add as you go. 0 is even.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

11. Search and Rearrange: Index of an Element, Negatives First, Zeros First

static int indexOf(int[] a, int target) {           // linear search
    for (int i = 0; i < a.length; i++) if (a[i] == target) return i;
    return -1;
}
static void moveNegativesToFront(int[] a) {         // keeps relative order
    int[] copy = a.clone(); int k = 0;
    for (int x : copy) if (x < 0) a[k++] = x;
    for (int x : copy) if (x >= 0) a[k++] = x;
}
static void moveZerosToFront(int[] a) {             // keeps order of non-zeros
    int write = a.length - 1;
    for (int i = a.length - 1; i >= 0; i--) if (a[i] != 0) a[write--] = a[i];
    while (write >= 0) a[write--] = 0;
}
indexOf([5, 8, 3, 8], 8) → 1, indexOf(.., 9) → -1
moveNegativesToFront([4, -1, 7, -3, 0, -8]) → [-1, -3, -8, 4, 7, 0]
moveZerosToFront([5, 0, 3, 0, 9]) → [0, 0, 5, 3, 9]
  • Linear search returns the first match and -1 when there's none — the same contract as String.indexOf. For a sorted array, Arrays.binarySearch is O(log n).
  • Negatives first: the version above keeps the original order (stable) at the cost of a copy; a two-pointer swap does it in place but can reorder elements. Ask which one the interviewer wants.
  • Zeros first: the mirror image of "zeros to the end" — walk from the back, writing non-zeros to the end.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

Complexity Summary

Program Best approach Time Extra space
Rotate by k Reversal algorithm O(n) O(1)
Missing number Sum formula or XOR O(n) O(1)
Pair with sum HashSet complement (two pointers if sorted) O(n) O(n) / O(1)
Majority element Moore's voting + verification O(n) O(1)
Move zeros Write index O(n) O(1)
Common elements HashSet lookup O(n + m) O(n)

Step through any of these in the Java Code Visualizer, then practice under time pressure in the Java Interview Simulator.

From the Interview Room

Java has been the language of every automation framework I've worked with — Selenium, TestNG, POM classes and Apache POI for Excel data. Interviews for automation roles regularly include basic programs like this one, often followed by a question on OOP concepts. Practice writing it by hand and explaining how you'd test it. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Explain the brute-force idea first, then the faster version — interviewers value the reasoning.

📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation

Frequently Asked Questions

How do you find a missing number in an array?

Subtract the actual sum from n(n + 1)/2 — using long to avoid overflow — or XOR all numbers from 1 to n with all array elements.

How do you find a pair with a given sum?

Store seen numbers in a HashSet. For each number, check whether target − number is already in the set. This provides an O(n) approach.

What is Moore's voting algorithm?

It is a single-pass, O(1)-space way to find the element appearing more than n/2 times, using a candidate and a counter — followed by a check that the candidate really is a majority.

How do you rotate an array by k positions efficiently?

Use the reversal algorithm: reverse the first k elements, reverse the rest, then reverse the whole array. This takes O(n) time and O(1) space.

How do you convert between an int[] and an ArrayList?

Add each element in a loop or use streams to build an ArrayList<Integer>. Convert back with toArray(new Integer[0]) for an Integer[], or stream().mapToInt(Integer::intValue).toArray() for an int[].