0% found this document useful (0 votes)
9 views11 pages

Top 15 Array Problems for Interviews

This document provides a cheat sheet of the top 15 array problems commonly encountered in technical interviews, including problems like Two Sum, Maximum Subarray, and Move Zeros. Each problem includes a brief description, key approaches, and sample Python code to solve it. The document serves as a quick reference for understanding various array manipulation techniques and algorithms.

Uploaded by

adinath9070
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

Top 15 Array Problems for Interviews

This document provides a cheat sheet of the top 15 array problems commonly encountered in technical interviews, including problems like Two Sum, Maximum Subarray, and Move Zeros. Each problem includes a brief description, key approaches, and sample Python code to solve it. The document serves as a quick reference for understanding various array manipulation techniques and algorithms.

Uploaded by

adinath9070
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Perfect!

Here's a Top 15 Array Problems Cheat Sheet for technical interviews with
problem, key approach, and patterns to remember:

Two Sum / Pair Sum

 Problem: Find indices of two numbers adding to a target.

✅ Code to Show All Possible Pairs


numbers = [2, 7, 11, 15, -2, 4, 5]
target = int(input("Enter target: "))

found = False

for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
print("Pair found →", numbers[i], "+", numbers[j], "=", target)
print("Indices:", i, j)
print("-------------------")
found = True

if not found:
print("No pairs found for target:", target)

Example Run

List:

[2, 7, 11, 15, -2, 4, 5]

Input:

Enter target: 9

Output:

Pair found → 2 + 7 = 9
Indices: 0 1
-------------------
Pair found → 11 + -2 = 9
Indices: 2 4
-------------------
Pair found → 4 + 5 = 9
Indices: 5 6
-------------------
Maximum Subarray (Kadane’s Algorithm)

 Problem: Max sum of contiguous subarray.

👉 First: What is a subarray?

A subarray means:

 Continuous part of the array


 No skipping allowed

Example:

[4, -1, 2, 1] ✔ valid subarray


[4, 2, 1] ❌ NOT valid (because -1 was skipped)

👉 Goal of this problem

From this list:

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

Find a continuous chunk (subarray) whose sum is the highest possible.

Answer is:

[4, -1, 2, 1] → sum = 6

✅ Simple Code with NumPy (Beginner-Friendly)


import numpy as np

arr = [Link]([-2, 1, -3, 4, -1, 2, 1, -5, 4])

current_sum = 0
max_sum = arr[0]
subarray = []
best = []

for num in arr:


# If continuing is good, keep going
if current_sum + num >= num:
current_sum += num
[Link](num)
else:
# restart new subarray
current_sum = num
subarray = [num]

# update best if needed


if current_sum > max_sum:
max_sum = current_sum
best = [Link]()

print("Maximum Sum:", max_sum)


print("Subarray with max sum:", best)

Output:
Maximum Sum: 6
Subarray with max sum: [4, -1, 2, 1]

3 ⃣ Move Zeros / Segregate Array

 Problem: Move all zeros to the end.

Problem

Given an array, move all zeros to the end while keeping the order of non-zero elements
same.

Example:

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


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

✅ Simple Python Code (Two-pointer approach)


arr = [0, 1, 0, 3, 12]

# pointer for next position of non-zero element


pos = 0

# move non-zero elements forward


for num in arr:
if num != 0:
arr[pos] = num
pos += 1

# fill remaining positions with zeros


while pos < len(arr):
arr[pos] = 0
pos += 1

print("Array after moving zeros:", arr)

Output
Array after moving zeros: [1, 3, 12, 0, 0]

4 ⃣ Reverse / Rotate Array

 Problem: Reverse array or rotate by k.


Problem

1. Reverse an array → flip it completely.


Example:
2. [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1]
3. Rotate array by k → move elements to the right by k positions (wrap around).
Example:
4. arr = [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3]

✅ 1. Reverse Array (Simple Python)


arr = [1, 2, 3, 4, 5]

# Reverse array
arr = arr[::-1]

print("Reversed Array:", arr)

Output:

Reversed Array: [5, 4, 3, 2, 1]

 [::-1] → slice trick to reverse the array easily.

✅ 2. Rotate Array by k (Simple Python)


arr = [1, 2, 3, 4, 5]
k=2

n = len(arr)
k = k % n # in case k > length of array

# Rotate: take last k elements and put them in front


rotated_arr = arr[-k:] + arr[:-k]

print(f"Array after rotating by {k}:", rotated_arr)

Output:

Array after rotating by 2: [4, 5, 1, 2, 3]

5 ⃣ Remove Duplicates from Sorted Array

 Problem: Remove duplicates in-place.

Simple For Loop with not in Check


arr = [1, 1, 2, 2, 3]
arr_no_duplicates = []

for num in arr:


# Add number only if it's not already in the new list
if num not in arr_no_duplicates:
arr_no_duplicates.append(num)

print("Array after removing duplicates:", arr_no_duplicates)


print("New length:", len(arr_no_duplicates))

Output:

Array after removing duplicates: [1, 2, 3]


New length: 3

 ✅ Easy to understand
 ✅ Maintains order
 ❌ Slightly slower for very large arrays

Using Set (Built-in Functionality)


arr = [1, 1, 2, 2, 3]

# Remove duplicates using set, then sort


arr_no_duplicates = sorted(set(arr))

print("Array after removing duplicates:", arr_no_duplicates)


print("New length:", len(arr_no_duplicates))

Output:

Array after removing duplicates: [1, 2, 3]


New length: 3

 ✅ Very short and simple


 ✅ Removes duplicates automatically
 ✅ Maintains sorted order (use sorted)
 ❌ Not in-place

💡 Tip:

 Use for loop with not in if you want to understand the logic.
 Use set if you want a quick and short solution.

6 ⃣ Find Duplicate / Missing Number

 Problem: Numbers 1..n, find missing or duplicate.

✅ Approach: Sum and Sum of Squares


Idea:

Let:

 D = duplicate
 M = missing
 sum_arr = sum of array
 sum_sq_arr = sum of squares of array
 sum_n = sum of 1..n = n*(n+1)//2
 sum_sq_n = sum of squares 1..n = n*(n+1)*(2n+1)//6

Then:

1. D - M = sum_arr - sum_n
2. D^2 - M^2 = sum_sq_arr - sum_sq_n → (D - M)*(D + M)

Solve for D + M → then find D and M.

✅ Python Code (Math Way)


arr = [1, 2, 2, 4]
n = len(arr)

sum_n = n*(n+1)//2
sum_sq_n = n*(n+1)*(2*n+1)//6

sum_arr = sum(arr)
sum_sq_arr = sum(x*x for x in arr)

diff = sum_arr - sum_n # D - M


sq_diff = sum_sq_arr - sum_sq_n # D^2 - M^2

D_plus_M = sq_diff // diff # D + M

duplicate = (diff + D_plus_M) // 2


missing = D_plus_M - duplicate

print("Duplicate:", duplicate)
print("Missing:", missing)

Output
Duplicate: 2
Missing: 3

✅ Simple Python Code


arr = [1, 2, 2, 4]
n = len(arr)

# Step 1: Find duplicate


duplicate = None
for i in arr:
if [Link](i) > 1:
duplicate = i
break

# Step 2: Find missing


missing = None
for i in range(1, n+1):
if i not in arr:
missing = i
break

print("Duplicate:", duplicate)
print("Missing:", missing)

Output
Duplicate: 2
Missing: 3

7 ⃣ Merge Intervals / Sorted Arrays

 Problem: Merge sorted arrays or intervals.

✅ Merge Two Sorted NumPy Arrays (Two-Pointer Method)


import numpy as np

arr1 = [Link]([1, 3, 5])


arr2 = [Link]([2, 4, 6])

i=j=0
merged = []

# Two-pointer merge
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
[Link](arr1[i])
i += 1
else:
[Link](arr2[j])
j += 1

# Add remaining elements


[Link](arr1[i:])
[Link](arr2[j:])

# Convert to NumPy array


merged = [Link](merged)
print("Merged sorted array:", merged)

Output
Merged sorted array: [1 2 3 4 5 6]

✅ Merge Sorted NumPy Arrays Using Built-in Functions


import numpy as np

arr1 = [Link]([1, 3, 5])


arr2 = [Link]([2, 4, 6])

# Merge arrays
merged = [Link]((arr1, arr2))

# Sort the merged array


[Link]() # in-place sorting

print("Merged sorted array:", merged)

Output
Merged sorted array: [1 2 3 4 5 6]

8 ⃣ Product of Array Except Self

 Problem: Return array where each element is product of others.

Problem:

Given an array, return a new array where each element is the product of all other elements.

Example:

nums = [1, 2, 3, 4]

Output:

[24, 12, 8, 6]

✅ Simple Python Code (Easy to Understand)


nums = [1, 2, 3, 4]
n = len(nums)
output = []
for i in range(n):
product = 1
for j in range(n):
if i != j:
product *= nums[j]
[Link](product)

print("Product array except self:", output)

Output
Product array except self: [24, 12, 8, 6]

🔍 How it Works

1. Loop through each element i.


2. For each i, multiply all elements except itself.
3. Append the result to output.

Step by step for [1, 2, 3, 4]:

 For index 0: 234 = 24


 For index 1: 134 = 12
 For index 2: 124 = 8
 For index 3: 123 = 6

9 ⃣ Subarray Sum / Sliding Window

 Problem: Max sum of size k, or subarray with sum = target.


 Pattern: Sliding window or prefix sum.
 Key Tip: Works for contiguous subarrays only.

Sure! We can update the sliding window code to also show the subarray that has the
maximum sum, not just the sum itself.

✅ Python Code (Sliding Window with Subarray)


arr = [2, 1, 5, 1, 3, 2]
k=3

# Initial window sum and max sum


window_sum = sum(arr[:k])
max_sum = window_sum
max_start = 0 # start index of max sum subarray

for i in range(k, len(arr)):


# Slide window
window_sum += arr[i] - arr[i-k]
# Update max sum and starting index if needed
if window_sum > max_sum:
max_sum = window_sum
max_start = i - k + 1 # new start index of max subarray

# Extract the subarray


max_subarray = arr[max_start:max_start + k]

print("Maximum sum of subarray of size", k, "is:", max_sum)


print("Subarray with maximum sum:", max_subarray)

Output
Maximum sum of subarray of size 3 is: 9
Subarray with maximum sum: [5, 1, 3]

1 ⃣4 ⃣ Maximum Product Subarray

 Problem: Max product of contiguous subarray.

✅ Simple Version (Brute-force, easy to understand)


arr = [2, 3, -2, 4]

max_product = arr[0]

# Check all possible contiguous subarrays


for i in range(len(arr)):
product = 1
for j in range(i, len(arr)):
product *= arr[j]
if product > max_product:
max_product = product

print("Maximum product subarray:", max_product)

Output
Maximum product subarray: 6

1 ⃣5 ⃣ Count Subarrays with Sum / Prefix Sum

 Problem: Count subarrays with sum = k.


 Pattern: Use hashmap for prefix sums.
 Key Tip: Count occurrences of (current_sum - k).

Sure! Let’s update the simple nested loop code to also print all subarrays whose sum
equals k.

✅ Python Code (Show Subarrays)


arr = [1, 2, 3, 0, 3]
k=3

count = 0
subarrays = []

# Loop over all possible subarrays


for i in range(len(arr)):
current_sum = 0
for j in range(i, len(arr)):
current_sum += arr[j] # sum of subarray arr[i:j+1]
if current_sum == k:
count += 1
[Link](arr[i:j+1]) # store the subarray

print("Number of subarrays with sum", k, "is:", count)


print("Subarrays with sum", k, "are:", subarrays)

Output
Number of subarrays with sum 3 is: 4
Subarrays with sum 3 are: [[1, 2], [3], [3], [0, 3]]

🔍 How it Works

1. Outer loop i → starting index of subarray


2. Inner loop j → ending index of subarray
3. current_sum → sum of elements from i to j
4. If current_sum == k, append the subarray to subarrays

You might also like