Arrays are where every coding round starts, because they test the basics without any library to lean on: a loop, an index, an if, and whether you think about the edge cases.
These seven problems are small. That’s the point. Each one teaches one move, and the moves come back again and again in harder problems later. Try each one yourself before you read the solution.
1. Find the maximum and minimum
Problem: given [4, 2, 9, 1, 7], print max = 9 and min = 1.
Plan in plain English: assume the first element is both the biggest and the smallest. Walk through the rest. If something is bigger than the current max, it’s the new max. Same for min.
static int[] findMaxMin(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int max = arr[0];
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
return new int[] { max, min };
}
max = 9
min = 1
Why start from arr[0] and not 0? If every number is negative, like [-5, -2, -9], a max that starts at 0 would wrongly return 0. Starting from the first element is always safe. (You could also start from Integer.MIN_VALUE and Integer.MAX_VALUE.)
You can write the two ifs with Math: max = Math.max(max, arr[i]);. Same result, and some interviewers like seeing you know it.
Cost: O(n) time, O(1) space.
The one-liner (only after you can write the loop):
int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();
2. Reverse an array
Problem: [1, 2, 3, 4, 5] becomes [5, 4, 3, 2, 1], in place (no second array).
Plan: put one finger on the first element and one on the last. Swap them. Move both fingers one step towards the middle. Stop when they meet. These fingers are called two pointers.
static void reverse(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
[5, 4, 3, 2, 1]
Notice the swap: three lines with a temp variable. You will write it many times in this series, so make it automatic.
Why left < right and not left <= right? When they’re equal, both point at the middle element, and swapping it with itself does nothing. Either works, but < shows you thought about it.
Cost: O(n) time (n/2 swaps), O(1) space.
3. Find the second largest element
Problem: in [10, 5, 20, 8, 20], the second largest is 10, not 20. The largest value appears twice, but it’s still the largest.
The easy answer that’s wrong-ish: sort the array and take the second-last element. For this input you’d get 20, because of the duplicate. And sorting costs O(n log n) when one pass is enough.
Plan: keep two variables, largest and second. For each number:
- If it’s bigger than
largest, the old largest becomessecond, and this number becomeslargest. - Otherwise, if it’s bigger than
secondand not equal tolargest, it becomessecond.
static int secondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int n : arr) {
if (n > largest) {
second = largest;
largest = n;
} else if (n > second && n != largest) {
second = n;
}
}
if (second == Integer.MIN_VALUE) {
throw new IllegalArgumentException("no second largest element");
}
return second;
}
Walk through [10, 5, 20, 8, 20]:
| n | largest | second | why |
|---|---|---|---|
| 10 | 10 | MIN | bigger than largest |
| 5 | 10 | 5 | bigger than second |
| 20 | 20 | 10 | bigger than largest, old 10 moves down |
| 8 | 20 | 10 | not bigger than second |
| 20 | 20 | 10 | equal to largest, skipped |
Edge cases to mention: an array like [7, 7] has no second largest, so we throw. And Integer.MIN_VALUE is used as “nothing yet”; if the array can contain Integer.MIN_VALUE itself, use Integer with null, or a long, as the marker. Saying this out loud earns points.
Cost: O(n) time, O(1) space.
4. Remove duplicates from a sorted array
Problem: [1, 1, 2, 2, 3, 4, 4] becomes [1, 2, 3, 4]. Do it in place and return the new length.
The key word is sorted. In a sorted array, duplicates sit next to each other. So you only need to compare each element with the last unique one you kept.
Plan: a slow pointer marks the last unique element. A fast pointer reads ahead. When fast finds a new value, move slow forward one place and copy the value there.
static int removeDuplicates(int[] arr) {
if (arr.length == 0) return 0;
int slow = 0;
for (int fast = 1; fast < arr.length; fast++) {
if (arr[fast] != arr[slow]) {
slow++;
arr[slow] = arr[fast];
}
}
return slow + 1; // number of unique elements
}
int[] arr = {1, 1, 2, 2, 3, 4, 4};
int k = removeDuplicates(arr);
System.out.println(Arrays.toString(Arrays.copyOf(arr, k))); // [1, 2, 3, 4]
Anything after position k is leftover junk. The problem only cares about the first k elements. This is exactly LeetCode 26.
Cost: O(n) time, O(1) space. (If the array were not sorted, you’d need a HashSet, which is problem 12.)
5. Move all zeros to the end
Problem: [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0]. Keep the non-zero numbers in their original order.
Plan: insertAt points at the place where the next non-zero number should go. Walk through the array with i. Every time arr[i] is not zero, swap it into insertAt and move insertAt forward. The zeros get pushed back naturally.
static void moveZeros(int[] arr) {
int insertAt = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
int temp = arr[insertAt];
arr[insertAt] = arr[i];
arr[i] = temp;
insertAt++;
}
}
}
[1, 3, 12, 0, 0]
The picture at the top of this article shows each swap. It’s the same two-pointer idea as problem 4: one pointer reads, one pointer writes.
Another way that interviewers also accept: copy every non-zero forward first, then fill the rest with zeros.
int insertAt = 0;
for (int n : arr) {
if (n != 0) arr[insertAt++] = n;
}
while (insertAt < arr.length) arr[insertAt++] = 0;
Cost: O(n) time, O(1) space.
6. Rotate an array by K positions
Problem: rotate [1, 2, 3, 4, 5] to the right by k = 2. The last two elements wrap round to the front: [4, 5, 1, 2, 3].
First, fix k. Rotating a 5-element array by 5 gives the same array back. So rotating by 7 is the same as rotating by 2. Always start with k = k % n. Forgetting this is the most common bug.
Simple way, with an extra array: element i moves to position (i + k) % n.
static int[] rotateCopy(int[] arr, int k) {
int n = arr.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[(i + k) % n] = arr[i];
}
return result;
}
That’s O(n) space. The interviewer will usually ask: “Can you do it in place?”
The reverse trick: reverse the whole array, then reverse the first k elements, then reverse the rest.
static void rotateRight(int[] arr, int k) {
int n = arr.length;
if (n == 0) return;
k = k % n;
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
static void reverse(int[] arr, int left, int right) {
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
Notice that reverse here is just problem 2, with a start and an end. That’s the order of this series paying off.
Rotate left instead? Rotating left by k is the same as rotating right by n - k.
Cost: O(n) time, O(1) space.
7. Find the missing number
Problem: an array holds n distinct numbers from the range 0 to n. One is missing. In [3, 0, 1], n is 3, the range is 0 to 3, and 2 is missing.
Plan A, the sum trick: the sum of 0 to n is n * (n + 1) / 2. Subtract the actual sum of the array, and what’s left is the missing number.
static int missingBySum(int[] arr) {
int n = arr.length;
int expected = n * (n + 1) / 2;
int actual = 0;
for (int x : arr) actual += x;
return expected - actual;
}
For [3, 0, 1]: expected is 3 × 4 / 2 = 6, actual is 4, missing is 2.
Plan B, the XOR trick: XOR (^) has two handy rules: a ^ a = 0 and a ^ 0 = a. If you XOR every number from 0 to n and every number in the array, each number that appears in both cancels itself out. Only the missing one survives.
static int missingByXor(int[] arr) {
int xor = 0;
for (int i = 0; i < arr.length; i++) {
xor ^= i + 1; // the numbers 1..n (0 changes nothing)
xor ^= arr[i]; // the numbers we actually have
}
return xor;
}
Which is better? Both are O(n) time and O(1) space. The sum can overflow an int when n is very large (above about 46,000, n * (n + 1) goes past the int limit of about 2.1 billion). XOR never overflows. Mentioning that is a nice touch. Using a long for the sum also fixes it.
What you practised
| Move | Problems |
|---|---|
| One loop, track a best-so-far | 1, 3 |
| Two pointers from both ends | 2, 6 |
| Two pointers, one reads and one writes | 4, 5 |
| Swap with a temp variable | 2, 5, 6 |
% n to wrap around |
6 |
| A maths shortcut (sum, XOR) | 7 |
Every one of these comes back later. Two pointers alone solves dozens of LeetCode problems: palindromes, pair sums in a sorted array, merging sorted arrays, container with most water.
Next: Phase 2, string interview programs, where you swap the array of numbers for an array of characters and start counting things.
Comments