Array Algorithms (13 problems)

15 Problems with Guidance Only (NO Solutions)

Purpose: Master array manipulation - most common interview topic Difficulty: ⭐⭐ Easy → ⭐⭐⭐⭐ Hard Time per problem: 20-45 minutes


Problem 163: Two Sum ⭐⭐

[See previous example file - already completed]


Problem 164: Three Sum ⭐⭐⭐

Problem Statement:

Given an integer array nums, return all triplets [nums[i], nums[j], nums[k]] such that:

  • i != j, i != k, and j != k

  • nums[i] + nums[j] + nums[k] = 0

The solution set must not contain duplicate triplets.

Examples:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Input: nums = [0,1,1]
Output: []

Input: nums = [0,0,0]
Output: [[0,0,0]]

Constraints:

  • 3 ≤ nums.length ≤ 3000

  • -10⁵ ≤ nums[i] ≤ 10⁵


Approach: Sort + Two Pointers

Key Insight:

  • Fix one number, find two others that sum to its negative

  • This becomes Two Sum problem for each fixed number!

Concept:

  1. Sort the array

  2. For each number (as first number):

    • Use two pointers for remaining array

    • Find pairs that sum to -(first number)

  3. Skip duplicates to avoid duplicate triplets

Complexity:

  • Time: O(n²) - O(n log n) sort + O(n²) for nested loops

  • Space: O(1) excluding output

Hints:


Test Cases:

Common Mistakes:

  • Not sorting first

  • Not skipping duplicates (causes duplicate triplets)

  • Off-by-one errors with pointers

  • Forgetting edge cases (all zeros, all same numbers)

Interview Tips:

  • Explain it builds on Two Sum

  • Draw the pointer movement

  • Emphasize duplicate handling

  • Mention Four Sum as follow-up


Problem 165: Subarray with Given Sum ⭐⭐⭐

Problem Statement:

Given an array of positive integers and a target sum, find a continuous subarray that sums to the target. Return the start and end indices.

Examples:

Constraints:

  • Array contains only positive integers

  • 1 ≤ arr.length ≤ 10⁵


Approach: Sliding Window

Key Insight:

  • Since all numbers are positive, we can use sliding window

  • If sum too small → expand window (add right)

  • If sum too large → shrink window (remove left)

Concept:

  • Two pointers: left and right

  • Maintain current sum

  • Adjust window based on sum comparison

Complexity:

  • Time: O(n) - each element added and removed at most once

  • Space: O(1)

Hints:


What if array has negative numbers?

  • Sliding window doesn't work!

  • Need different approach: prefix sum + hash map

  • Time: O(n), Space: O(n)


Test Cases:

Interview Tips:

  • Clarify if array has negatives (changes approach!)

  • Explain sliding window technique

  • Mention it works for positive numbers only

  • Discuss prefix sum approach for negatives


Problem 166: Equilibrium Index ⭐⭐⭐

Problem Statement:

Find an index where the sum of elements on the left equals the sum of elements on the right.

Examples:


Approach: Prefix Sum

Key Insight:

  • leftSum + arr[i] + rightSum = totalSum

  • If leftSum = rightSum, then:

    • leftSum = (totalSum - arr[i]) / 2

Concept:

  1. Calculate total sum

  2. Iterate, maintaining left sum

  3. Right sum = total - left - current

  4. Check if left == right

Complexity:

  • Time: O(n)

  • Space: O(1)

Hints:


Test Cases:

Interview Tips:

  • Explain prefix sum concept

  • Mention two-pass vs one-pass

  • Discuss edge case: single element


Problem 167: Leaders in Array ⭐⭐

Problem Statement:

An element is a leader if it's greater than all elements to its right. Find all leaders.

Examples:


Approach: Right to Left Scan

Key Insight:

  • Rightmost element is always a leader

  • Scan from right to left, tracking max seen so far

  • Any element > max is a leader

Concept:

  • Start from right

  • Track maximum element seen

  • If current > max, it's a leader

Complexity:

  • Time: O(n)

  • Space: O(1) excluding output

Hints:


Test Cases:

Interview Tips:

  • Explain right-to-left approach

  • Mention why left-to-right is harder (O(n²))

  • Discuss whether order matters in output


Problem 168: Trapping Rainwater ⭐⭐⭐⭐

Problem Statement:

Given n non-negative integers representing elevation map where width of each bar is 1, compute how much water can be trapped after raining.

Examples:


Approach 1: Dynamic Programming

Key Insight:

  • Water trapped at index i = min(maxLeft[i], maxRight[i]) - height[i]

  • Precompute max heights to left and right of each position

Complexity:

  • Time: O(n)

  • Space: O(n) - two arrays

Hints:


Approach 2: Two Pointers (Optimal)

Key Insight:

  • Don't need full arrays if we use two pointers

  • Process from both ends moving toward center

Complexity:

  • Time: O(n)

  • Space: O(1)

Hints:


Test Cases:

Interview Tips:

  • Draw visual representation!

  • Start with DP approach (easier to explain)

  • Then optimize to two pointers

  • This is a hard problem - don't worry if stuck


Problem 169: Sort 0s, 1s, 2s (Dutch Flag) ⭐⭐⭐

Problem Statement:

Given an array containing only 0s, 1s, and 2s, sort it in-place without using sort function.

Examples:


Approach 1: Counting

Concept:

  • Count occurrences of 0, 1, 2

  • Overwrite array with counts

Complexity:

  • Time: O(n)

  • Space: O(1)

Hints:


Approach 2: Dutch National Flag (Single Pass)

Key Insight:

  • Three pointers: low (next position for 0), mid (current), high (next position for 2)

  • Partition array into three sections

Concept:

  • 0s go to low region

  • 2s go to high region

  • 1s stay in middle

Complexity:

  • Time: O(n) - single pass

  • Space: O(1)

Hints:


Test Cases:

Interview Tips:

  • Show both approaches

  • Dutch flag is more elegant (single pass)

  • Explain why we don't increment mid when swapping with high

  • Mention this generalizes to k colors


Problem 170: Find Majority Element ⭐⭐⭐

Problem Statement:

Given an array, find the element that appears more than ⌊n/2⌋ times. You may assume such element always exists.

Examples:


Approach 1: Hash Map

Concept:

  • Count frequencies

  • Find element with count > n/2

Complexity:

  • Time: O(n)

  • Space: O(n)


Approach 2: Boyer-Moore Voting Algorithm (Optimal)

Key Insight:

  • Majority element appears more than all others combined

  • Cancel out different elements

  • Remaining is majority

Concept:

  • Candidate and count

  • If same as candidate, count++

  • If different, count--

  • If count = 0, new candidate

Complexity:

  • Time: O(n)

  • Space: O(1)

Hints:


Why this works:

  • Majority element survives cancellation

  • Even if all others team up, majority wins!


Test Cases:

Interview Tips:

  • Explain both approaches

  • Boyer-Moore is brilliant but non-obvious

  • Walk through example showing cancellation

  • This is a classic algorithm!


Problem 171: Kth Largest Element ⭐⭐⭐

Problem Statement:

Find the kth largest element in an unsorted array. Note that it is the kth largest element in sorted order, not the kth distinct element.

Examples:


Approach 1: Sort

Concept:

  • Sort array

  • Return element at index (length - k)

Complexity:

  • Time: O(n log n)

  • Space: O(1)


Approach 2: Min Heap of Size K

Concept:

  • Maintain heap of k largest elements

  • Top of heap is kth largest

Complexity:

  • Time: O(n log k)

  • Space: O(k)

Hints:


Approach 3: QuickSelect (Optimal)

Concept:

  • Like QuickSort but only recurse on one side

  • Partition array, check if pivot is kth largest

Complexity:

  • Time: O(n) average, O(n²) worst

  • Space: O(1)

This is advanced - mention but implementation is tricky


Test Cases:

Interview Tips:

  • Start with sort approach (simple)

  • Then min heap (better for small k)

  • Mention QuickSelect (optimal but complex)

  • Ask: "Do you want me to implement QuickSelect?"


Problem 172: Next Permutation ⭐⭐⭐⭐

Problem Statement:

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation.

If not possible (highest permutation), rearrange to lowest (sorted ascending).

Must be in-place with O(1) extra space.

Examples:


Approach: Single Pass Algorithm

Key Insight:

  1. Find rightmost pair where nums[i] < nums[i+1]

  2. Swap nums[i] with smallest element to its right that's larger

  3. Reverse everything after i

Concept:

Complexity:

  • Time: O(n)

  • Space: O(1)

Hints:


Test Cases:

Interview Tips:

  • This is a hard problem

  • Draw out the steps

  • Explain lexicographic order

  • The algorithm is non-obvious - OK to struggle


Problem 173: Merge Intervals ⭐⭐⭐

Problem Statement:

Given a collection of intervals, merge all overlapping intervals.

Examples:


Approach: Sort + Merge

Key Insight:

  • Sort intervals by start time

  • Merge consecutive overlapping intervals

Concept:

  1. Sort by start time

  2. Iterate, checking if current overlaps with previous

  3. If overlaps, merge (extend end)

  4. If not, add previous and start new interval

Complexity:

  • Time: O(n log n) - sorting

  • Space: O(n) - output

Hints:


Test Cases:

Interview Tips:

  • Always sort first!

  • Draw timeline visualization

  • Handle edge case: one interval inside another

  • Mention insert interval as follow-up


Problem 174: Longest Increasing Subsequence ⭐⭐⭐⭐

Problem Statement:

Given an integer array nums, return the length of the longest strictly increasing subsequence.

Note: Subsequence != subarray (elements don't need to be contiguous)

Examples:


Approach 1: Dynamic Programming

Concept:

  • dp[i] = length of LIS ending at index i

  • For each i, check all previous elements

  • If nums[j] < nums[i], can extend LIS at j

Complexity:

  • Time: O(n²)

  • Space: O(n)

Hints:


Approach 2: Binary Search (Optimal)

Concept:

  • Maintain array of smallest tail values for each length

  • Use binary search to find position

Complexity:

  • Time: O(n log n)

  • Space: O(n)

This is advanced - mention but don't worry if can't implement


Test Cases:

Interview Tips:

  • DP approach is expected

  • Draw the dp array

  • Binary search optimization is bonus

  • This is a classic hard problem


Problem 175: Stock Buy/Sell (One Transaction) ⭐⭐

Problem Statement:

You are given an array prices where prices[i] is the price of a stock on day i.

Find maximum profit from one buy and one sell. If no profit possible, return 0.

Examples:


Approach: Single Pass

Key Insight:

  • Track minimum price seen so far

  • Calculate profit if sold today

  • Update maximum profit

Concept:

  • Keep track of lowest price

  • For each day, calculate: price today - lowest price

  • Update max profit

Complexity:

  • Time: O(n)

  • Space: O(1)

Hints:


Test Cases:

Follow-up Questions:

  • Multiple transactions? (Different problem - DP)

  • At most k transactions? (Hard DP problem)

  • With transaction fee? (Modified DP)

Interview Tips:

  • This is easier than it looks

  • One pass is sufficient

  • Explain why greedy works here

  • Mention follow-ups to show broader knowledge


✅ Track B Complete!

You've covered 15 essential array algorithm problems. These are the MOST common in interviews!

Next: Track C - Searching & Sorting (10 problems)

Last updated