10 Most Common Array Interview Questions (With Solutions)

Array Interview Questions
10 Most Common Array Interview Questions (With Solutions)

Complete Guide with Solutions, Examples, and Visual Explanations

1. Two Sum Problem

Problem: Given an array of integers and a target sum, return the indices of two numbers that add up to the target.

Example:

Input: nums = [2, 7, 11, 15], target = 9

Output: [0, 1] (because nums[0] + nums[1] = 2 + 7 = 9)

Visual Representation:

2
7
11
15

Target: 9 | Solution: Index 0 + Index 1 = 2 + 7 = 9

function twoSum(nums, target) { const map = new Map(); 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); } return []; } // Example usage const nums = [2, 7, 11, 15]; const target = 9; console.log(twoSum(nums, target)); // [0, 1]
Time Complexity: O(n) – Single pass through array
Space Complexity: O(n) – Hash map storage

Step-by-Step Approach:

1. Create a hash map to store number-index pairs
2. For each element, calculate its complement (target – current element)
3. Check if complement exists in hash map
4. If found, return both indices; otherwise, add current element to map

2. Maximum Subarray (Kadane’s Algorithm)

Problem: Find the contiguous subarray with the largest sum and return its sum.

Example:

Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Output: 6 (subarray [4, -1, 2, 1] has sum 6)

Visual Representation:

-2
1
-3
4
-1
2
1
-5
4

Maximum subarray: [4, -1, 2, 1] = 6

function maxSubArray(nums) { let maxSoFar = nums[0]; let maxEndingHere = nums[0]; for (let i = 1; i < nums.length; i++) { // Either extend existing subarray or start new one maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]); // Update global maximum maxSoFar = Math.max(maxSoFar, maxEndingHere); } return maxSoFar; } // Example usage const nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; console.log(maxSubArray(nums)); // 6
Time Complexity: O(n) – Single pass
Space Complexity: O(1) – Constant space

3. Contains Duplicate

Problem: Given an integer array, return true if any value appears at least twice in the array.

Example:

Input: [1, 2, 3, 1]

Output: true (1 appears twice)

// Approach 1: Using Set function containsDuplicate(nums) { const seen = new Set(); for (const num of nums) { if (seen.has(num)) { return true; } seen.add(num); } return false; } // Approach 2: One-liner using Set function containsDuplicateOneliner(nums) { return new Set(nums).size !== nums.length; }
Time Complexity: O(n) – Single pass
Space Complexity: O(n) – Set storage

4. Product of Array Except Self

Problem: Given an array, return an array where each element is the product of all elements except itself. Cannot use division.

Example:

Input: [1, 2, 3, 4]

Output: [24, 12, 8, 6]

Two-Pass Approach Visualization:

Left Pass: Products of elements to the left

1
1
2
6

Right Pass: Multiply by products from the right

24
12
8
6
function productExceptSelf(nums) { const result = new Array(nums.length); // Left pass: store product of elements to the left result[0] = 1; for (let i = 1; i < nums.length; i++) { result[i] = result[i - 1] * nums[i - 1]; } // Right pass: multiply by product of elements to the right let rightProduct = 1; for (let i = nums.length - 1; i >= 0; i–) { result[i] *= rightProduct; rightProduct *= nums[i]; } return result; } // Example usage const nums = [1, 2, 3, 4]; console.log(productExceptSelf(nums)); // [24, 12, 8, 6]
Time Complexity: O(n) – Two passes
Space Complexity: O(1) – No extra space (excluding output array)

5. Best Time to Buy and Sell Stock

Problem: Find the maximum profit from buying and selling a stock once, given daily prices.

Example:

Input: [7, 1, 5, 3, 6, 4]

Output: 5 (buy at 1, sell at 6)

Price Chart:

7
1
5
3
6
4

Buy at price 1, sell at price 6 → Profit = 5

function maxProfit(prices) { let minPrice = prices[0]; let maxProfit = 0; for (let i = 1; i < prices.length; i++) { // Update minimum price seen so far minPrice = Math.min(minPrice, prices[i]); // Calculate profit if selling today const currentProfit = prices[i] - minPrice; // Update maximum profit maxProfit = Math.max(maxProfit, currentProfit); } return maxProfit; } // Example usage const prices = [7, 1, 5, 3, 6, 4]; console.log(maxProfit(prices)); // 5
Time Complexity: O(n) – Single pass
Space Complexity: O(1) – Constant space

6. Find Missing Number

Problem: Given an array containing n distinct numbers from 0 to n, find the missing number.

Example:

Input: [3, 0, 1]

Output: 2 (missing from range 0-3)

// Approach 1: Mathematical Sum function missingNumber(nums) { const n = nums.length; const expectedSum = (n * (n + 1)) / 2; const actualSum = nums.reduce((sum, num) => sum + num, 0); return expectedSum – actualSum; } // Approach 2: XOR (Bit Manipulation) function missingNumberXOR(nums) { let result = nums.length; for (let i = 0; i < nums.length; i++) { result ^= i ^ nums[i]; } return result; }
Time Complexity: O(n) – Single pass
Space Complexity: O(1) – Constant space

7. 3Sum Problem

Problem: Find all unique triplets in the array that sum to zero.

Example:

Input: [-1, 0, 1, 2, -1, -4]

Output: [[-1, -1, 2], [-1, 0, 1]]

function threeSum(nums) { nums.sort((a, b) => a – b); const result = []; for (let i = 0; i < nums.length - 2; i++) { // Skip duplicates for first element if (i > 0 && nums[i] === nums[i – 1]) continue; let left = i + 1; let right = nums.length – 1; while (left < right) { const sum = nums[i] + nums[left] + nums[right]; if (sum === 0) { result.push([nums[i], nums[left], nums[right]]); // Skip duplicates while (left < right && nums[left] === nums[left + 1]) left++; while (left < right && nums[right] === nums[right - 1]) right--; left++; right--; } else if (sum < 0) { left++; } else { right--; } } } return result; }
Time Complexity: O(n²) – Nested loops with two pointers
Space Complexity: O(1) – No extra space (excluding output)

8. Rotate Array

Problem: Rotate an array to the right by k steps.

Example:

Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

Rotation Visualization:

Original:

1
2
3
4
5
6
7

After rotating right by 3:

5
6
7
1
2
3
4
// Approach 1: Using Extra Array function rotate(nums, k) { const n = nums.length; k = k % n; // Handle k > n const result = new Array(n); for (let i = 0; i < n; i++) { result[(i + k) % n] = nums[i]; } // Copy back to original array for (let i = 0; i < n; i++) { nums[i] = result[i]; } } // Approach 2: Reverse Method (In-place) function rotateReverse(nums, k) { const n = nums.length; k = k % n; // Helper function to reverse array portion function reverse(start, end) { while (start < end) { [nums[start], nums[end]] = [nums[end], nums[start]]; start++; end--; } } // 1. Reverse entire array reverse(0, n - 1); // 2. Reverse first k elements reverse(0, k - 1); // 3. Reverse remaining elements reverse(k, n - 1); }
Time Complexity: O(n) – Single pass
Space Complexity: O(1) for reverse method, O(n) for extra array

Reverse Method Steps:

1. Reverse the entire array: [7,6,5,4,3,2,1]
2. Reverse first k elements: [5,6,7,4,3,2,1]
3. Reverse remaining elements: [5,6,7,1,2,3,4]

9. Move Zeroes

Problem: Move all zeros to the end of array while maintaining relative order of non-zero elements.

Example:

Input: [0,1,0,3,12]

Output: [1,3,12,0,0]

Two-Pointer Approach:

Original:

0
1
0
3
12

After moving zeros:

1
3
12
0
0
function moveZeroes(nums) { let writeIndex = 0; // Move all non-zero elements to the front for (let readIndex = 0; readIndex < nums.length; readIndex++) { if (nums[readIndex] !== 0) { nums[writeIndex] = nums[readIndex]; writeIndex++; } } // Fill remaining positions with zeros while (writeIndex < nums.length) { nums[writeIndex] = 0; writeIndex++; } } // Alternative: Swap approach function moveZeroesSwap(nums) { let left = 0; for (let right = 0; right < nums.length; right++) { if (nums[right] !== 0) { [nums[left], nums[right]] = [nums[right], nums[left]]; left++; } } }
Time Complexity: O(n) – Single pass
Space Complexity: O(1) – In-place modification

10. Merge Sorted Array

Problem: Merge two sorted arrays nums1 and nums2 into nums1 in-place. nums1 has enough space to hold both arrays.

Example:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

Merge Process (Right to Left):

Initial State:

1
2
3
0
0
0

nums2:

2
5
6

Final Result:

1
2
2
3
5
6
function merge(nums1, m, nums2, n) { let i = m – 1; // Last element in nums1 let j = n – 1; // Last element in nums2 let k = m + n – 1; // Last position in merged array // Merge from right to left while (i >= 0 && j >= 0) { if (nums1[i] > nums2[j]) { nums1[k] = nums1[i]; i–; } else { nums1[k] = nums2[j]; j–; } k–; } // Copy remaining elements from nums2 while (j >= 0) { nums1[k] = nums2[j]; j–; k–; } // nums1 elements are already in place, no need to copy } // Example usage let nums1 = [1,2,3,0,0,0]; let nums2 = [2,5,6]; merge(nums1, 3, nums2, 3); console.log(nums1); // [1,2,2,3,5,6]
Time Complexity: O(m + n) – Single pass through both arrays
Space Complexity: O(1) – In-place merge

Why Merge Right to Left?

1. Prevents overwriting elements in nums1 that haven’t been processed yet
2. Takes advantage of the extra space at the end of nums1
3. Allows for true in-place merging without extra space

🎯 Key Takeaways for Array Interview Success

Master these fundamental patterns and you’ll be ready for most array-based coding interviews!

🔍 Two Pointers

Essential for problems involving pairs, triplets, or moving elements. Used in Two Sum, 3Sum, Move Zeroes, and Merge Sorted Array.

📊 Hash Maps

Perfect for O(1) lookups and tracking seen elements. Key to solving Two Sum and Contains Duplicate efficiently.

🔄 Sliding Window

Great for subarray problems. Kadane’s Algorithm (Maximum Subarray) is a classic example of this technique.

💡 Mathematical Insights

Sometimes math can simplify complex problems. See Missing Number and Product of Array Except Self for examples.

🎨 In-Place Algorithms

Minimize space complexity by modifying arrays in-place. Critical for Rotate Array and Move Zeroes solutions.

⚡ Edge Cases

Always consider: empty arrays, single elements, duplicates, negative numbers, and overflow scenarios.

🚀 Practice Strategy:

1. Understand the problem thoroughly
2. Think about time/space complexity
3. Start with brute force, then optimize
4. Test with edge cases
5. Explain your approach clearly

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *