Array Coding Interview Problems — Two Sum, Kadane, Sliding Window & More
If there is one topic that shows up in almost every technical coding interview — whether you are applying to a startup, a product company, or a FAANG-level organisation — it is arrays. They are the most fundamental data structure in computer science, and interviewers use array problems to test your understanding of time complexity, space complexity, pattern recognition, and your ability to write clean, efficient code under pressure.
In this guide we will cover the most commonly asked array interview problems with detailed explanations, multiple approaches, and working code examples in JavaScript and Java. For each problem we will walk through the brute force approach first, then the optimal solution — because that is exactly how you should think through problems in a real interview.
What Interviewers Are Actually Testing
Before diving into the problems, understand what the interviewer is looking for. It is rarely about memorizing solutions. They want to see:
- Can you break down a problem before writing any code?
- Do you understand time and space complexity trade-offs?
- Can you recognize patterns — two pointers, sliding window, hashing?
- Do you handle edge cases — empty arrays, single elements, duplicates?
- Can you communicate your thinking clearly while coding?
With that in mind, let us get into the problems.
Problem 1 — Two Sum
Problem: Given an array of integers and a target number, return the indices of the two numbers that add up to the target. Assume exactly one solution exists.
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] // nums[0] + nums[1] = 2 + 7 = 9
Brute Force — O(n²) time, O(1) space
// JavaScript
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
}
twoSum([2, 7, 11, 15], 9); // [0, 1]
Optimal Solution — O(n) time, O(n) space
Use a HashMap to store each number and its index as you iterate. For each element, check if its complement (target - current) already exists in the map. If yes — you found your pair.
// JavaScript — HashMap approach
function twoSum(nums, target) {
const map = new Map(); // stores {number: index}
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
}
twoSum([2, 7, 11, 15], 9); // [0, 1]
// Java — same approach
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[] {}; // no solution
}
Interview tip: Always ask the interviewer — "Can the array contain duplicates?" and "Is the array sorted?" If sorted, a two-pointer approach works in O(n) with O(1) space — no HashMap needed. Asking these questions earns you points even before you write a line.
Problem 2 — Find the Maximum Subarray Sum (Kadane's Algorithm)
Problem: Given an integer array, find the contiguous subarray with the largest sum and return that sum.
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6 // subarray [4, -1, 2, 1] has the maximum sum
Brute Force — O(n²) time
function maxSubarrayBrute(nums) {
let maxSum = -Infinity;
for (let i = 0; i < nums.length; i++) {
let currentSum = 0;
for (let j = i; j < nums.length; j++) {
currentSum += nums[j];
maxSum = Math.max(maxSum, currentSum);
}
}
return maxSum;
}
Optimal — Kadane's Algorithm O(n) time, O(1) space
The insight: if the running sum becomes negative, it can only drag down future sums — so reset it to zero and start fresh from the next element.
// JavaScript — Kadane's Algorithm
function maxSubarray(nums) {
let maxSum = nums[0]; // track global maximum
let currentSum = nums[0]; // track running sum
for (let i = 1; i < nums.length; i++) {
// Either extend the existing subarray or start fresh
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
maxSubarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]); // 6
// Java
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
Problem 3 — Best Time to Buy and Sell Stock
Problem: Given an array of stock prices where
prices[i] is the price on day i, find the
maximum profit from one buy and one sell. You must buy before you sell.
Input: [7, 1, 5, 3, 6, 4]
Output: 5 // buy at 1 (day 2), sell at 6 (day 5)
// JavaScript — O(n) time, O(1) space
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) {
minPrice = price; // found a cheaper buying price
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice; // found a better profit
}
}
return maxProfit;
}
maxProfit([7, 1, 5, 3, 6, 4]); // 5
// Java
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
Problem 4 — Move All Zeros to the End
Problem: Given an array, move all zeros to the end while maintaining the relative order of non-zero elements. Do it in place.
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Use the two-pointer technique: one pointer tracks the position to place the next non-zero element, the other iterates through the array.
// JavaScript — O(n) time, O(1) space
function moveZeroes(nums) {
let insertPos = 0; // position to place next non-zero
// First pass — move all non-zeros to the front
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[insertPos] = nums[i];
insertPos++;
}
}
// Second pass — fill remaining positions with 0
for (let i = insertPos; i < nums.length; i++) {
nums[i] = 0;
}
return nums;
}
moveZeroes([0, 1, 0, 3, 12]); // [1, 3, 12, 0, 0]
// Java
public void moveZeroes(int[] nums) {
int insertPos = 0;
for (int num : nums) {
if (num != 0) {
nums[insertPos++] = num;
}
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}
Watch the video below for a clear step-by-step walkthrough with code:
Problem 5 — Find Duplicate in Array
Problem: Given an array of n+1 integers where each integer is between 1 and n inclusive, find the duplicate number. Do not modify the array and use only O(1) extra space.
Input: [1, 3, 4, 2, 2]
Output: 2
HashMap Approach — O(n) time, O(n) space
function findDuplicate(nums) {
const seen = new Set();
for (let num of nums) {
if (seen.has(num)) return num;
seen.add(num);
}
}
Floyd's Cycle Detection — O(n) time, O(1) space (optimal)
Treat the array as a linked list where the value at each index points to the next index. A duplicate creates a cycle. Use Floyd's tortoise and hare algorithm to find the entry point of the cycle.
// JavaScript — Floyd's Cycle Detection
function findDuplicate(nums) {
// Phase 1 — find intersection point inside cycle
let slow = nums[0];
let fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow !== fast);
// Phase 2 — find cycle entry (the duplicate)
slow = nums[0];
while (slow !== fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
findDuplicate([1, 3, 4, 2, 2]); // 2
Problem 6 — Maximum Product Subarray
Problem: Find the contiguous subarray with the largest product.
Input: [2, 3, -2, 4]
Output: 6 // subarray [2, 3]
The trick here is that a negative number multiplied by another negative gives a positive — so you must track both the maximum and minimum product at each step.
// JavaScript — O(n) time, O(1) space
function maxProduct(nums) {
let maxProd = nums[0];
let minProd = nums[0];
let result = nums[0];
for (let i = 1; i < nums.length; i++) {
// When multiplied by a negative, max and min swap
if (nums[i] < 0) {
[maxProd, minProd] = [minProd, maxProd];
}
maxProd = Math.max(nums[i], maxProd * nums[i]);
minProd = Math.min(nums[i], minProd * nums[i]);
result = Math.max(result, maxProd);
}
return result;
}
maxProduct([2, 3, -2, 4]); // 6
Problem 7 — Rotate Array
Problem: Given an array, rotate it to the right by k steps in place.
Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
The elegant three-reverse approach: reverse the entire array, then reverse the first k elements, then reverse the rest.
// JavaScript — O(n) time, O(1) space
function rotate(nums, k) {
k = k % nums.length; // handle k > array length
reverse(nums, 0, nums.length - 1); // reverse entire array
reverse(nums, 0, k - 1); // reverse first k elements
reverse(nums, k, nums.length - 1); // reverse the rest
return nums;
}
function reverse(nums, start, end) {
while (start < end) {
[nums[start], nums[end]] = [nums[end], nums[start]];
start++;
end--;
}
}
rotate([1, 2, 3, 4, 5, 6, 7], 3); // [5, 6, 7, 1, 2, 3, 4]
Problem 8 — Sliding Window Maximum
Problem: Given an array and a window size k, return the maximum of each sliding window as it moves from left to right.
Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output: [3, 3, 5, 5, 6, 7]
Use a deque (double-ended queue) to maintain a decreasing sequence of indices. The front of the deque always holds the index of the maximum element in the current window.
// JavaScript — O(n) time using Deque
function maxSlidingWindow(nums, k) {
const result = [];
const deque = []; // stores indices
for (let i = 0; i < nums.length; i++) {
// Remove indices outside the current window
while (deque.length && deque[0] < i - k + 1) {
deque.shift();
}
// Remove smaller elements from the back (they can never be max)
while (deque.length && nums[deque[deque.length - 1]] < nums[i]) {
deque.pop();
}
deque.push(i);
// Start adding results once we have a full window
if (i >= k - 1) {
result.push(nums[deque[0]]);
}
}
return result;
}
maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3);
// [3, 3, 5, 5, 6, 7]
Key Patterns to Master for Array Interviews
| Pattern | When to Use | Problems |
|---|---|---|
| Two Pointers | Sorted array, pairs, palindrome | Two Sum (sorted), Move Zeros, 3Sum |
| Sliding Window | Contiguous subarray/substring | Max subarray, Window maximum, Longest substring |
| HashMap / HashSet | O(1) lookup, count frequency | Two Sum, Find Duplicate, Anagram |
| Prefix Sum | Range sum queries | Subarray sum equals K, Range queries |
| Kadane's Algorithm | Maximum subarray sum/product | Max subarray sum, Max product subarray |
| Binary Search | Sorted array, find target | Search in rotated array, First/last position |
| Cycle Detection | Duplicate in array as linked list | Find Duplicate, Happy Number |
Time and Space Complexity Quick Reference
// Array operations — always know these
Access by index: O(1) — random access, direct
Search (unsorted): O(n) — linear scan
Search (sorted): O(log n) — binary search
Insert at end: O(1) — amortized for dynamic arrays
Insert at beginning: O(n) — all elements must shift
Delete at end: O(1)
Delete at beginning: O(n) — all elements must shift
Sort: O(n log n) — comparison-based sorting lower bound
Common Mistakes in Array Interviews
- Not handling edge cases first — always ask yourself: what if the array is empty? What if it has only one element? What if all elements are the same? State these out loud before coding.
-
Off-by-one errors — the most common bug in array
problems. Use
<vs<=carefully, especially in two-pointer and sliding window problems. - Modifying the array while iterating — can cause skipped elements or infinite loops. Make a copy or use a separate pointer if you need to modify in place.
- Using O(n) space when O(1) is possible — creating a new array when the problem says "in place" costs you points. Always ask if in-place modification is required.
- Jumping to code without a plan — interviewers value seeing your thought process. Spend 2–3 minutes talking through your approach before writing any code.
Interview Tips — What to Say While Solving
Most candidates freeze or work silently. Strong candidates narrate their thinking. Here is a framework:
- Clarify: "Can I assume the array is non-empty? Can there be duplicates? Is it sorted?"
- Brute force first: "The naive approach would be O(n²) by checking every pair. Let me think if we can do better."
- Optimize: "If I use a HashMap, I can get O(n) time at the cost of O(n) space. Is that acceptable?"
- Code and explain: Walk through your code line by line as you write it — do not code silently.
- Test your code: After writing, trace through your example input manually. Then test an edge case.
Final Thought
Arrays are the foundation of almost every other data structure and algorithm problem you will encounter in interviews. Mastering the patterns covered here — two pointers, sliding window, hashing, Kadane's algorithm, cycle detection — gives you tools that apply far beyond just array problems. You will find yourself reaching for these same patterns in string, linked list, and graph problems too.
Do not memorize solutions. Understand the pattern behind each solution — why it works, what insight it relies on, and when to reach for it. That understanding is what transfers to new problems you have never seen before, which is exactly what a technical interview is designed to test.
Preparing for an upcoming interview and stuck on a specific problem? Drop us a message on our contact page — we will help you work through it.
Finding duplicate elements in an array is one of the most frequently asked Java interview questions. Watch the video below for a clear step-by-step walkthrough with code:
📚 You Might Also Like
- → How to Start Freelancing as a Web Developer in 2026 (Complete Beginner's Guide) miscellaneous
- → JavaScript Promises vs Async/Await — Complete Guide with Examples javascript
- → Laravel 12 Features You Should Know (2026 Update) Laravel
- → Interview Prep: Common Developer Interview Questions & Answers (2026 Guide) Laravel
- → How to Add a WhatsApp Share Button in a Website — 5 Methods with Examples html