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]
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target – num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
# Example usage
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target)) # [0, 1]
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
Map 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[]{};
}
}
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
def max_subarray(nums):
max_so_far = nums[0]
max_ending_here = nums[0]
for i in range(1, len(nums)):
# Either extend existing subarray or start new one
max_ending_here = max(nums[i], max_ending_here + nums[i])
# Update global maximum
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
# Example usage
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(max_subarray(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;
}
# Approach 1: Using set
def contains_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
# Approach 2: One-liner
def contains_duplicate_oneliner(nums):
return len(set(nums)) != len(nums)
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]
def product_except_self(nums):
result = [1] * len(nums)
# Left pass: store product of elements to the left
for i in range(1, len(nums)):
result[i] = result[i – 1] * nums[i – 1]
# Right pass: multiply by product of elements to the right
right_product = 1
for i in range(len(nums) – 1, -1, -1):
result[i] *= right_product
right_product *= nums[i]
return result
# Example usage
nums = [1, 2, 3, 4]
print(product_except_self(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
def max_profit(prices):
min_price = prices[0]
max_profit = 0
for i in range(1, len(prices)):
# Update minimum price seen so far
min_price = min(min_price, prices[i])
# Calculate profit if selling today
current_profit = prices[i] – min_price
# Update maximum profit
max_profit = max(max_profit, current_profit)
return max_profit
# Example usage
prices = [7, 1, 5, 3, 6, 4]
print(max_profit(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;
}
# Approach 1: Mathematical Sum
def missing_number(nums):
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum – actual_sum
# Approach 2: XOR (Bit Manipulation)
def missing_number_xor(nums):
result = len(nums)
for i, num in enumerate(nums):
result ^= i ^ num
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;
}
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) – 2):
# Skip duplicates for first element
if i > 0 and nums[i] == nums[i – 1]:
continue
left, right = i + 1, len(nums) – 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum == 0:
result.append([nums[i], nums[left], nums[right]])
# Skip duplicates
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif current_sum < 0:
left += 1
else:
right -= 1
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);
}
# Approach 1: Using Extra Array
def rotate(nums, k):
n = len(nums)
k = k % n # Handle k > n
result = [0] * n
for i in range(n):
result[(i + k) % n] = nums[i]
# Copy back to original array
nums[:] = result
# Approach 2: Reverse Method (In-place)
def rotate_reverse(nums, k):
n = len(nums)
k = k % n
def reverse(start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
# 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++;
}
}
}
def move_zeroes(nums):
write_index = 0
# Move all non-zero elements to the front
for read_index in range(len(nums)):
if nums[read_index] != 0:
nums[write_index] = nums[read_index]
write_index += 1
# Fill remaining positions with zeros
while write_index < len(nums):
nums[write_index] = 0
write_index += 1
# Alternative: Swap approach
def move_zeroes_swap(nums):
left = 0
for right in range(len(nums)):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
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]
def merge(nums1, m, nums2, n):
i = m – 1 # Last element in nums1
j = n – 1 # Last element in nums2
k = m + n – 1 # Last position in merged array
# Merge from right to left
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
# Copy remaining elements from nums2
while j >= 0:
nums1[k] = nums2[j]
j -= 1
k -= 1
# nums1 elements are already in place, no need to copy
# Example usage
nums1 = [1,2,3,0,0,0]
nums2 = [2,5,6]
merge(nums1, 3, nums2, 3)
print(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