Array interview questions with worked solutions
Last updated 2026-11-19
Arrays are the first topic in almost every coding round, because they test whether you can handle indexes, in-place updates and off-by-one errors without a library doing the work for you. Most array problems reduce to a handful of moves: a write pointer that compacts the array, a reversal trick, a single pass that carries a running value, or a pass from each end.
The ten problems below are ordered from easy to hard and each one introduces a different move. If you are building a study plan, pair this page with the two pointers questions and the DSA coding round guide.
| Problems | 10, easy to hard |
|---|---|
| Languages | Python and Java |
| Core moves | Write pointer, reversal, running value, fill from back |
How to spot an array problem that wants in-place work
Look for phrases such as "in place", "O(1) extra space" or "modify the input array". These tell you the interviewer wants you to reuse the array itself, usually with a read index running ahead of a write index.
When the statement gives no space limit, a hash map or a second array is usually acceptable, but say so and then mention the in-place alternative. That conversation is often worth more than the code.
- Write pointer plus read pointer: Move Zeroes, Remove Duplicates.
- Reverse in parts: Rotate Array, Next Permutation.
- Carry a running value: Stock profit, Boyer-Moore majority.
- Fill from the back to avoid overwriting: Merge Sorted Array.
Common array mistakes
Most failed array solutions fail on size 0, size 1 or all-equal input. Before you submit, run those three by hand, and check that every loop bound is inclusive or exclusive on purpose.
- Forgetting k % n when rotating.
- Overflow when multiplying or summing in Java: use long if values can reach 10^9.
- Modifying an array while iterating over it with a for-each loop.
Array interview questions with worked solutions: questions with worked answers
1 Move all zeroes to the end while keeping the order of the other elements.
easyKeep a write index w. Scan once; whenever an element is non-zero, copy it to a[w] and advance w. After the scan, fill the rest of the array with zeroes. This keeps relative order and uses no extra array. Time O(n), space O(1).. Edge cases: empty array, all zeroes, no zeroes.
pythondef move_zeroes(a): w = 0 for x in a: if x != 0: a[w] = x w += 1 for i in range(w, len(a)): a[i] = 0javaimport java.util.*; class Solution { static void moveZeroes(int[] a) { int w = 0; for (int x : a) if (x != 0) a[w++] = x; while (w < a.length) a[w++] = 0; } }2 Remove duplicates from a sorted array in place and return the new length.
easyBecause duplicates are adjacent, the first element is always kept. Compare each new element with the last kept one, a[w-1]; if different, write it at w. The answer is w. Time O(n), space O(1).. Edge cases: empty array, one element, all equal.
pythondef remove_duplicates(a): if not a: return 0 w = 1 for i in range(1, len(a)): if a[i] != a[w - 1]: a[w] = a[i] w += 1 return wjavaimport java.util.*; class Solution { static int removeDuplicates(int[] a) { if (a.length == 0) return 0; int w = 1; for (int i = 1; i < a.length; i++) if (a[i] != a[w - 1]) a[w++] = a[i]; return w; } }3 Best time to buy and sell a stock once: find the maximum profit.
easyTrack the lowest price seen so far. At each day the best profit if you sell today is price minus that minimum. Keep the maximum of those. You never need the buy day itself, only the minimum. Time O(n), space O(1).. Edge cases: prices only fall (answer 0, never negative), one day.
pythondef max_profit(prices): low, best = float('inf'), 0 for p in prices: low = min(low, p) best = max(best, p - low) return bestjavaimport java.util.*; class Solution { static int maxProfit(int[] prices) { int low = Integer.MAX_VALUE, best = 0; for (int p : prices) { low = Math.min(low, p); best = Math.max(best, p - low); } return best; } }4 Rotate an array to the right by k steps in place.
mediumReduce k to k % n. Reverse the whole array, then reverse the first k elements and the last n-k elements. For [1,2,3,4,5,6,7] and k=3: whole reverse gives 7,6,5,4,3,2,1; reversing the first three gives 5,6,7 and the rest gives 1,2,3,4. Result 5,6,7,1,2,3,4. Time O(n), space O(1).. Edge cases: k larger than n, k = 0, empty array (avoid modulo by zero).
pythondef rotate(a, k): n = len(a) if n == 0: return k %= n def rev(l, r): while l < r: a[l], a[r] = a[r], a[l] l += 1 r -= 1 rev(0, n - 1) rev(0, k - 1) rev(k, n - 1)javaimport java.util.*; class Solution { static void rotate(int[] a, int k) { int n = a.length; if (n == 0) return; k %= n; rev(a, 0, n - 1); rev(a, 0, k - 1); rev(a, k, n - 1); } static void rev(int[] a, int l, int r) { while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; } } }5 Find the majority element (appears more than n/2 times).
mediumBoyer-Moore voting: keep a candidate and a count. If count is zero, take the current element as candidate. Equal elements add one, different ones subtract one. A true majority cannot be cancelled out, so it survives. If the problem does not guarantee a majority, make a second pass to verify. Time O(n), space O(1).. Edge cases: no majority when not guaranteed (verify), single element.
pythondef majority(a): cand, cnt = None, 0 for x in a: if cnt == 0: cand = x cnt += 1 if x == cand else -1 return candjavaimport java.util.*; class Solution { static int majority(int[] a) { int cand = 0, cnt = 0; for (int x : a) { if (cnt == 0) cand = x; cnt += (x == cand) ? 1 : -1; } return cand; } }6 Product of array except self, without division.
mediumMake the output hold prefix products: out[i] is the product of everything left of i. Then sweep from the right with a running suffix product and multiply it into out[i]. Division fails when zeroes are present, which is why the two-pass form is preferred. Time O(n), space O(1) beyond the output.. Edge cases: zeroes in the input, negative numbers, length 2.
pythondef product_except_self(a): n = len(a) out = [1] * n for i in range(1, n): out[i] = out[i - 1] * a[i - 1] suf = 1 for i in range(n - 1, -1, -1): out[i] *= suf suf *= a[i] return outjavaimport java.util.*; class Solution { static int[] productExceptSelf(int[] a) { int n = a.length; int[] out = new int[n]; out[0] = 1; for (int i = 1; i < n; i++) out[i] = out[i - 1] * a[i - 1]; int suf = 1; for (int i = n - 1; i >= 0; i--) { out[i] *= suf; suf *= a[i]; } return out; } }7 Merge two sorted arrays into the first one, which has room at the end.
mediumFill from the back so you never overwrite an unread element. Use i at the end of the first real part, j at the end of the second and k at the last slot. Place the larger of a[i] and b[j] at k and step back. Only the second array needs draining at the end; leftovers of the first are already in place. Time O(m+n), space O(1).. Edge cases: m = 0, n = 0, all of b smaller than a.
pythondef merge(a, m, b, n): i, j, k = m - 1, n - 1, m + n - 1 while j >= 0: if i >= 0 and a[i] > b[j]: a[k] = a[i] i -= 1 else: a[k] = b[j] j -= 1 k -= 1javaimport java.util.*; class Solution { static void merge(int[] a, int m, int[] b, int n) { int i = m - 1, j = n - 1, k = m + n - 1; while (j >= 0) { if (i >= 0 && a[i] > b[j]) a[k--] = a[i--]; else a[k--] = b[j--]; } } }8 Find the next lexicographic permutation in place.
mediumScan from the right for the first index i with a[i] < a[i+1]. If none exists, the array is the last permutation, so reverse it. Otherwise find the rightmost j with a[j] > a[i], swap, then reverse the suffix after i to make it the smallest ordering. For 1,3,2: i=0, j=2, swap gives 2,3,1, reverse suffix gives 2,1,3. Time O(n), space O(1).. Edge cases: descending input wraps to ascending, duplicates (use > not >=), length 1.
pythondef next_permutation(a): i = len(a) - 2 while i >= 0 and a[i] >= a[i + 1]: i -= 1 if i >= 0: j = len(a) - 1 while a[j] <= a[i]: j -= 1 a[i], a[j] = a[j], a[i] l, r = i + 1, len(a) - 1 while l < r: a[l], a[r] = a[r], a[l] l += 1 r -= 1javaimport java.util.*; class Solution { static void nextPermutation(int[] a) { int i = a.length - 2; while (i >= 0 && a[i] >= a[i + 1]) i--; if (i >= 0) { int j = a.length - 1; while (a[j] <= a[i]) j--; int t = a[i]; a[i] = a[j]; a[j] = t; } for (int l = i + 1, r = a.length - 1; l < r; l++, r--) { int t = a[l]; a[l] = a[r]; a[r] = t; } } }9 Trapping rain water: how much water do the bars hold?
hardWater above a bar is min(maxLeft, maxRight) minus its height. Use two pointers from the ends and track the max on each side. Move the side with the smaller max, because that side is the bottleneck and its water level is already decided. For [0,1,0,2,1,0,1,3,2,1,2,1] the answer is 6. Time O(n), space O(1).. Edge cases: fewer than 3 bars gives 0, strictly increasing or decreasing bars give 0.
pythondef trap(h): l, r = 0, len(h) - 1 lm = rm = water = 0 while l < r: if h[l] < h[r]: lm = max(lm, h[l]) water += lm - h[l] l += 1 else: rm = max(rm, h[r]) water += rm - h[r] r -= 1 return waterjavaimport java.util.*; class Solution { static int trap(int[] h) { int l = 0, r = h.length - 1, lm = 0, rm = 0, water = 0; while (l < r) { if (h[l] < h[r]) { lm = Math.max(lm, h[l]); water += lm - h[l++]; } else { rm = Math.max(rm, h[r]); water += rm - h[r--]; } } return water; } }10 Find the first missing positive integer in O(n) time and O(1) space.
hardPlace each value v in 1..n at index v-1 by swapping, repeating until the current slot holds a value that is out of range or already in place. Then the first index i where a[i] != i+1 gives the answer i+1; if all match, the answer is n+1. The while loop is still linear since each swap fixes one value for good. Time O(n), space O(1).. Edge cases: duplicates (the already-in-place check prevents infinite loops), negatives, zeros, [1,2,3] gives 4.
pythondef first_missing_positive(a): n = len(a) for i in range(n): while 1 <= a[i] <= n and a[a[i] - 1] != a[i]: j = a[i] - 1 a[i], a[j] = a[j], a[i] for i in range(n): if a[i] != i + 1: return i + 1 return n + 1javaimport java.util.*; class Solution { static int firstMissingPositive(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { while (a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i]) { int j = a[i] - 1; int t = a[i]; a[i] = a[j]; a[j] = t; } } for (int i = 0; i < n; i++) if (a[i] != i + 1) return i + 1; return n + 1; } }11 Sort an array of 0s, 1s and 2s in one pass (Dutch national flag).
hardKeep three regions with pointers lo, mid and hi. If a[mid] is 0, swap with lo and move both forward; if 1, move mid; if 2, swap with hi and move hi back without advancing mid, because the swapped-in value is unchecked. Time O(n), space O(1).. Edge cases: array with only one value, already sorted, reverse sorted.
pythondef sort_colors(a): lo, mid, hi = 0, 0, len(a) - 1 while mid <= hi: if a[mid] == 0: a[lo], a[mid] = a[mid], a[lo] lo += 1 mid += 1 elif a[mid] == 1: mid += 1 else: a[mid], a[hi] = a[hi], a[mid] hi -= 1javaimport java.util.*; class Solution { static void sortColors(int[] a) { int lo = 0, mid = 0, hi = a.length - 1; while (mid <= hi) { if (a[mid] == 0) { int t = a[lo]; a[lo++] = a[mid]; a[mid++] = t; } else if (a[mid] == 1) mid++; else { int t = a[mid]; a[mid] = a[hi]; a[hi--] = t; } } } }
Frequently asked questions
Which array problems should I practise first?
Start with the in-place compaction problems (move zeroes, remove duplicates), then stock profit and rotation. They teach the index discipline that harder topics such as sliding window and two pointers rely on.
Is it fine to use extra space in an interview?
Yes, if the statement allows it. State the simple solution first, then offer the O(1) space version. Do not silently pick the harder one if you cannot finish it.
Should I use Python or Java for array questions?
Use the language you can write without looking things up. Python is shorter, but Java shows you handle typed arrays, overflow and index bounds explicitly. Both appear in the code above.
How do I test an array solution quickly?
Run three inputs by hand: empty or length one, all elements equal, and a case that needs the longest path through the logic. Most bugs show up in one of those.
Where do prefix sums and sliding windows fit in?
Both are array techniques with their own pages. See prefix sum questions and sliding window questions.
Related guides
- Two pointers interview questions with worked solutions
- Sliding window interview questions with worked solutions
- Prefix sum interview questions with worked solutions
- Cyclic sort pattern interview questions with worked solutions
- Sorting algorithm interview questions with worked solutions
- Kadane algorithm interview questions with worked solutions
More in DSA Interview Questions
- Backtracking interview questions with worked solutions
- BFS (Breadth-First Search) Interview Questions
- Binary search interview questions with worked solutions
- Binary Search Tree Interview Questions and Answers
- Binary Tree Interview Questions and Answers
- Bit manipulation interview questions with worked solutions
- Bitmask DP Interview Questions
- Cyclic sort pattern interview questions with worked solutions
- DFS (Depth-First Search) Interview Questions
- Dijkstra and Shortest Path Interview Questions
- Divide and Conquer Interview Questions
- Dynamic Programming Interview Questions