Master Reference: Advanced Array & Matrix Algorithms
Yeh tamam 15 advanced array, prefix sum, matrix, aur two-pointer problems ki complete, professional guide hai. Har problem ka exact mathematical mechanism, C++, aur Python ka production-ready optimal code ($O(1)$ ya optimal space complexity ke sath) shamil hai.
1. Subarray Sum Equals K (With Negative Numbers)
Jab array mein negative numbers ya zeroes hon, to sliding window technique fail ho jati hai kyunke array size barhane se sum kam bhi ho sakta hai. Is problem ko solve karne ke liye hum running prefix sum aur frequency hash map ka istemal karte hain.
Core Mathematical Proof
Let $\text{prefix}[i]$ be the sum of elements from index 0 to i. The sum of a contiguous subarray from index $j + 1$ to $i$ is defined as:
$$\text{Subarray Sum}(j+1, i) = \text{prefix}[i] - \text{prefix}[j]$$
We want this subarray sum to equal $k$:
$$\text{prefix}[i] - \text{prefix}[j] = k \implies \text{prefix}[j] = \text{prefix}[i] - k$$
While iterating at index $i$, if the value $(\text{prefix}[i] - k)$ exists in our frequency map, the count associated with that key represents the exact number of valid subarrays ending at index $i$.
Code Implementation
C++ Solution
#include <vector>
#include <unordered_map>
int subarraySum(const std::vector<int>& nums, int k) {
std::unordered_map<int, int> prefix_counts;
prefix_counts[0] = 1; // Base case: prefix sum of 0 occurs once initially
int current_sum = 0;
int total_subarrays = 0;
for (int num : nums) {
current_sum += num;
int target = current_sum - k;
if (prefix_counts.find(target) != prefix_counts.end()) {
total_subarrays += prefix_counts[target];
}
prefix_counts[current_sum]++;
}
return total_subarrays;
}
Python Solution
def subarray_sum(nums: list[int], k: int) -> int:
prefix_counts = {0: 1} # Base case for subarrays starting at index 0
current_sum = 0
total_subarrays = 0
for num in nums:
current_sum += num
target = current_sum - k
if target in prefix_counts:
total_subarrays += prefix_counts[target]
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
return total_subarrays
Complexity
- Time Complexity: $O(n)$ average time using hash map lookups.
- Auxiliary Space: $O(n)$ to store prefix frequencies.
2. Boyer-Moore Majority Vote (> n/3 Threshold)
Size $n$ ke kisi bhi array mein zyada se zyada 2 elements aise ho sakte hain jin ki frequency strictly $\lfloor n/3 \rfloor$ se zyada ho. Boyer-Moore algorithm 2 candidates aur 2 counters track kar ke cancelation logic run karta hai.
Algorithmic Execution Rules
- Pass 1 (Candidate Selection): Maintain
cand1,cand2,count1, andcount2.- If
num == cand1, incrementcount1. - Else if
num == cand2, incrementcount2. - Else if
count1 == 0, assigncand1 = num, count1 = 1. - Else if
count2 == 0, assigncand2 = num, count2 = 1. - Else, decrement both
count1andcount2(canceling 3 distinct elements).
- If
- Pass 2 (Verification): Iterate through the array again to verify if the selected candidates actually exceed the $n/3$ threshold.
Code Implementation
C++ Solution
#include <vector>
std::vector<int> majorityElement(const std::vector<int>& nums) {
int cand1 = 0, cand2 = 0;
int count1 = 0, count2 = 0;
for (int num : nums) {
if (num == cand1) {
count1++;
} else if (num == cand2) {
count2++;
} else if (count1 == 0) {
cand1 = num;
count1 = 1;
} else if (count2 == 0) {
cand2 = num;
count2 = 1;
} else {
count1--;
count2--;
}
}
// Verification Pass
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == cand1) count1++;
else if (num == cand2) count2++;
}
std::vector<int> result;
int threshold = static_cast<int>(nums.size()) / 3;
if (count1 > threshold) result.push_back(cand1);
if (count2 > threshold && cand1 != cand2) result.push_back(cand2);
return result;
}
Python Solution
def majority_element_n_over_3(nums: list[int]) -> list[int]:
cand1, cand2 = None, None
count1, count2 = 0, 0
for num in nums:
if num == cand1:
count1 += 1
elif num == cand2:
count2 += 1
elif count1 == 0:
cand1, count1 = num, 1
elif count2 == 0:
cand2, count2 = num, 1
else:
count1 -= 1
count2 -= 1
# Verification Pass
threshold = len(nums) // 3
result = []
for cand in (cand1, cand2):
if cand is not None and nums.count(cand) > threshold:
if cand not in result:
result.append(cand)
return result
Complexity
- Time Complexity: $O(n)$ with two linear passes.
- Auxiliary Space: $O(1)$ space using scalar variables.
3. First Missing Positive (Cyclic Index Placement)
Length $n$ ke array mein pehla missing positive integer hamesha range $[1, n + 1]$ ke andar hota hai. Hum array ko Cyclic Sort ki tarah modify karte hain taake har number $x \in [1, n]$ apne correct index $x - 1$ par chala jaye.
Cyclic Placement Rule
While $\text{nums}[i] \in [1, n]$ and $\text{nums}[\text{nums}[i] - 1] \neq \text{nums}[i]$, swap $\text{nums}[i]$ with $\text{nums}[\text{nums}[i] - 1]$.
Code Implementation
C++ Solution
#include <vector>
#include <algorithm>
int firstMissingPositive(std::vector<int>& nums) {
int n = static_cast<int>(nums.size());
for (int i = 0; i < n; ++i) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
std::swap(nums[i], nums[nums[i] - 1]);
}
}
for (int i = 0; i < n; ++i) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}
Python Solution
def first_missing_positive(nums: list[int]) -> int:
n = len(nums)
for i in range(n):
while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
target_idx = nums[i] - 1
nums[i], nums[target_idx] = nums[target_idx], nums[i]
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
Complexity
- Time Complexity: $O(n)$ amortized time. Every element is swapped at most once into its correct position.
- Auxiliary Space: $O(1)$ space.
4. Product of Array Except Self (Division-Free & Overflow-Safe)
To construct an output array where $\text{result}[i] = \prod_{j \neq i} \text{nums}[j]$ without division: $$\text{result}[i] = (\text{Prefix Product of elements } 0 \dots i-1) \times (\text{Suffix Product of elements } i+1 \dots n-1)$$
Overflow Protection
In languages like C++, large product accumulations can overflow 32-bit signed integers. We use long long / int64_t data types for intermediate state storage.
Code Implementation
C++ Solution
#include <vector>
#include <cstdint>
std::vector<int64_t> productExceptSelf(const std::vector<int>& nums) {
int n = static_cast<int>(nums.size());
std::vector<int64_t> result(n, 1);
// Pass 1: Compute left prefix products
int64_t prefix = 1;
for (int i = 0; i < n; ++i) {
result[i] = prefix;
prefix *= nums[i];
}
// Pass 2: Multiply right suffix products in-place
int64_t suffix = 1;
for (int i = n - 1; i >= 0; --i) {
result[i] *= suffix;
suffix *= nums[i];
}
return result;
}
Python Solution
def product_except_self(nums: list[int]) -> list[int]:
n = len(nums)
result = [1] * n
prefix = 1
for i in range(n):
result[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return result
Complexity
- Time Complexity: $O(n)$ time using two linear passes.
- Auxiliary Space: $O(1)$ space (excluding memory for the returned array).
5. Group Anagrams via Frequency Key Maps
Strings of length $k$ can be grouped as anagrams without sorting ($O(k \log k)$) by encoding each string’s character count into a fixed 26-element array.
Custom Hash Strategy
- Python: Convert the 26-element integer frequency list into an immutable
tupleto serve directly as a hash map key. - C++: Use
std::array<int, 26>with a custom bit-mixing hash functor (FreqHash) forstd::unordered_map.
Code Implementation
C++ Solution
#include <vector>
#include <string>
#include <array>
#include <unordered_map>
struct FreqHash {
std::size_t operator()(const std::array<int, 26>& arr) const {
std::size_t hash_val = 0;
for (int count : arr) {
// Bit-mixing hash combination formula
hash_val ^= std::hash<int>()(count) + 0x9e3779b9 + (hash_val << 6) + (hash_val >> 2);
}
return hash_val;
}
};
std::vector<std::vector<std::string>> groupAnagrams(const std::vector<std::string>& strs) {
std::unordered_map<std::array<int, 26>, std::vector<std::string>, FreqHash> groups;
for (const auto& s : strs) {
std::array<int, 26> freq = {0};
for (char ch : s) {
freq[ch - 'a']++;
}
groups[freq].push_back(s);
}
std::vector<std::vector<std::string>> result;
for (auto& [key, group] : groups) {
result.push_back(std::move(group));
}
return result;
}
Python Solution
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for s in strs:
freq = [0] * 26
for ch in s:
freq[ord(ch) - ord('a')] += 1
groups[tuple(freq)].append(s)
return list(groups.values())
Complexity
- Time Complexity: $O(n \cdot k)$ where $n$ is total strings and $k$ is max string length.
- Space Complexity: $O(n \cdot k)$ space for map storage.
6. Longest Consecutive Sequence ($O(n)$ Hash Set Logic)
Nested while loops inside a for loop running in $O(n)$ time can seem counter-intuitive. The sequence head check eliminates duplicate iterations.
Sequence Head Condition
We only initiate sequence expansion if:
$$(x - 1) \notin \text{hash_set}$$
If x - 1 exists, x is part of an ongoing sequence and will be visited when the root of that sequence is processed. Across all sequence heads, each element is processed inside the inner while loop at most once.
$$\text{Total Work} = \underbrace{n \text{ outer checks}}{\text{Outer loop}} + \underbrace{\sum L_i}{\text{Inner loop across heads}} \le n + n = 2n \implies O(n)$$
Code Implementation
C++ Solution
#include <vector>
#include <unordered_set>
#include <algorithm>
int longestConsecutive(const std::vector<int>& nums) {
std::unordered_set<int> num_set(nums.begin(), nums.end());
int max_streak = 0;
for (int num : num_set) {
// Only start sequence from the head
if (num_set.find(num - 1) == num_set.end()) {
int current_num = num;
int current_streak = 1;
while (num_set.find(current_num + 1) != num_set.end()) {
current_num += 1;
current_streak += 1;
}
max_streak = std::max(max_streak, current_streak);
}
}
return max_streak;
}
Python Solution
def longest_consecutive(nums: list[int]) -> int:
num_set = set(nums)
max_streak = 0
for num in num_set:
if (num - 1) not in num_set:
current_num = num
current_streak = 1
while (current_num + 1) in num_set:
current_num += 1
current_streak += 1
max_streak = max(max_streak, current_streak)
return max_streak
Complexity
- Time Complexity: $O(n)$ average execution.
- Auxiliary Space: $O(n)$ to store unique array values in a set.
7. 2D Prefix Sum Matrix ($O(1)$ Submatrix Range Queries)
Precomputing a 1-indexed 2D Prefix Sum Matrix P allows submatrix sum extraction in constant $O(1)$ time.
Mathematical Precomputation & Querying
- Precomputation: $$P[i][j] = \text{matrix}[i-1][j-1] + P[i-1][j] + P[i][j-1] - P[i-1][j-1]$$
- Inclusion-Exclusion Query $(r_1, c_1) \dots (r_2, c_2)$: $$\text{Sum} = P[r_2 + 1][c_2 + 1] - P[r_1][c_2 + 1] - P[r_2 + 1][c_1] + P[r_1][c_1]$$
Code Implementation
C++ Solution
#include <vector>
class NumMatrix {
private:
std::vector<std::vector<long long>> prefix;
public:
NumMatrix(const std::vector<std::vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return;
int m = matrix.size();
int n = matrix[0].size();
prefix.assign(m + 1, std::vector<long long>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
prefix[i][j] = matrix[i - 1][j - 1]
+ prefix[i - 1][j]
+ prefix[i][j - 1]
- prefix[i - 1][j - 1];
}
}
}
long long sumRegion(int r1, int c1, int r2, int c2) const {
return prefix[r2 + 1][c2 + 1]
- prefix[r1][c2 + 1]
- prefix[r2 + 1][c1]
+ prefix[r1][c1];
}
};
Python Solution
class NumMatrix:
def __init__(self, matrix: list[list[int]]):
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
self.prefix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
self.prefix[i][j] = (
matrix[i - 1][j - 1]
+ self.prefix[i - 1][j]
+ self.prefix[i][j - 1]
- self.prefix[i - 1][j - 1]
)
def sum_region(self, r1: int, c1: int, r2: int, c2: int) -> int:
return (
self.prefix[r2 + 1][c2 + 1]
- self.prefix[r1][c2 + 1]
- self.prefix[r2 + 1][c1]
+ self.prefix[r1][c1]
)
Complexity
- Precomputation Time: $O(M \cdot N)$
- Query Time: $O(1)$ constant time
- Auxiliary Space: $O(M \cdot N)$
8. Difference Array Technique for $O(1)$ Range Updates
To perform $Q$ range increment operations $\text{add}(L, R, V)$ across an array of length $N$:
- Difference Update ($O(1)$): $$D[L] \mathrel{+}= V, \quad D[R + 1] \mathrel{-}= V$$
- Reconstruction Pass ($O(N)$): $$A[i] = \sum_{k=0}^{i} D[k]$$
This reduces overall complexity from $O(Q \cdot N)$ to $O(N + Q)$.
Code Implementation
C++ Solution
#include <vector>
class DifferenceArray {
private:
std::vector<long long> diff;
int n;
public:
DifferenceArray(const std::vector<int>& arr) {
n = arr.size();
diff.assign(n + 1, 0);
diff[0] = arr[0];
for (int i = 1; i < n; ++i) {
diff[i] = arr[i] - arr[i - 1];
}
}
void update(int l, int r, long long val) {
diff[l] += val;
diff[r + 1] -= val;
}
std::vector<long long> getResult() const {
std::vector<long long> result(n);
result[0] = diff[0];
for (int i = 1; i < n; ++i) {
result[i] = result[i - 1] + diff[i];
}
return result;
}
};
Python Solution
class DifferenceArray:
def __init__(self, arr: list[int]):
self.n = len(arr)
self.diff = [0] * (self.n + 1)
self.diff[0] = arr[0]
for i in range(1, self.n):
self.diff[i] = arr[i] - arr[i - 1]
def update(self, l: int, r: int, val: int) -> None:
self.diff[l] += val
self.diff[r + 1] -= val
def get_result(self) -> list[int]:
result = [0] * self.n
result[0] = self.diff[0]
for i in range(1, self.n):
result[i] = result[i - 1] + self.diff[i]
return result
Complexity
- Update Time: $O(1)$ per query
- Reconstruction Time: $O(N)$
- Auxiliary Space: $O(N)$
9. In-Place $90^\circ$ Clockwise Matrix Rotation
Rotating an $n \times n$ matrix $90^\circ$ clockwise in-place ($O(1)$ auxiliary memory) is achieved by combining matrix transposition with row reversal.
$$\text{Rotate } 90^\circ \text{ Clockwise} = \text{Transpose Matrix} \longrightarrow \text{Reverse Every Row}$$
- Transpose: Swap element $(i, j)$ with $(j, i)$ for $j > i$.
- Reverse: Reverse each row horizontally using two pointers.
Code Implementation
C++ Solution
#include <vector>
#include <algorithm>
void rotate(std::vector<std::vector<int>>& matrix) {
int n = matrix.size();
// Step 1: Transpose
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
std::swap(matrix[i][j], matrix[j][i]);
}
}
// Step 2: Reverse each row
for (int i = 0; i < n; ++i) {
std::reverse(matrix[i].begin(), matrix[i].end());
}
}
Python Solution
def rotate(matrix: list[list[int]]) -> None:
n = len(matrix)
# Step 1: Transpose matrix in-place
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Step 2: Reverse each row
for row in matrix:
row.reverse()
Complexity
- Time Complexity: $O(n^2)$
- Auxiliary Space: $O(1)$ in-place execution
10. Set Matrix Zeroes ($O(1)$ Space Flag Markers)
Instead of allocating $O(m + n)$ marker arrays, we use the matrix’s first row and first column as flag markers. Cell matrix[0][0] creates an overlap conflict between Row 0 and Col 0, which we resolve using a separate scalar variable first_col_zero.
Execution Order
- Check if column 0 originally contains any zeroes (
first_col_zero). - Scan inner matrix (
1..m-1,1..n-1) and set flags in row 0 and column 0. - Zero out inner matrix cells based on row/column flags.
- Zero out row 0 if
matrix[0][0] == 0. - Zero out column 0 if
first_col_zero == true.
Code Implementation
C++ Solution
#include <vector>
void setZeroes(std::vector<std::vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
bool first_col_zero = false;
for (int r = 0; r < m; ++r) {
if (matrix[r][0] == 0) first_col_zero = true;
for (int c = 1; c < n; ++c) {
if (matrix[r][c] == 0) {
matrix[r][0] = 0;
matrix[0][c] = 0;
}
}
}
for (int r = 1; r < m; ++r) {
for (int c = 1; c < n; ++c) {
if (matrix[r][0] == 0 || matrix[0][c] == 0) {
matrix[r][c] = 0;
}
}
}
if (matrix[0][0] == 0) {
for (int c = 0; c < n; ++c) matrix[0][c] = 0;
}
if (first_col_zero) {
for (int r = 0; r < m; ++r) matrix[r][0] = 0;
}
}
Python Solution
def set_zeroes(matrix: list[list[int]]) -> None:
m, n = len(matrix), len(matrix[0])
first_col_zero = False
for r in range(m):
if matrix[r][0] == 0:
first_col_zero = True
for c in range(1, n):
if matrix[r][c] == 0:
matrix[r][0] = 0
matrix[0][c] = 0
for r in range(1, m):
for c in range(1, n):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if matrix[0][0] == 0:
for c in range(n):
matrix[0][c] = 0
if first_col_zero:
for r in range(m):
matrix[r][0] = 0
Complexity
- Time Complexity: $O(m \cdot n)$
- Auxiliary Space: $O(1)$ space
11. Next Lexicographical Permutation
This algorithm rearranges an array into its lexicographically next greater permutation in $O(n)$ time and $O(1)$ space.
Three-Step Mechanism
- Find Pivot Index $i$: Scan right to left for the first index $i$ where $\text{nums}[i] < \text{nums}[i + 1]$.
- Find Swap Target $j$: If $i \ge 0$, scan right to left for the first index $j$ where $\text{nums}[j] > \text{nums}[i]$. Swap $\text{nums}[i]$ and $\text{nums}[j]$.
- Reverse Suffix: Reverse elements from $i + 1$ to the end of the array to minimize the suffix value.
Code Implementation
C++ Solution
#include <vector>
#include <algorithm>
void nextPermutation(std::vector<int>& nums) {
int n = nums.size();
int i = n - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
std::swap(nums[i], nums[j]);
}
std::reverse(nums.begin() + i + 1, nums.end());
}
Python Solution
def next_permutation(nums: list[int]) -> None:
n = len(nums)
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
j = n - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
left, right = i + 1, n - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
Complexity
- Time Complexity: $O(n)$
- Auxiliary Space: $O(1)$ space
12. Reverse Three-Pointer Merge for Sorted Arrays
Merging two sorted arrays nums1 (size $m + n$) and nums2 (size $n$) in-place without overwriting active elements requires merging from right to left starting at write index $p = m + n - 1$.
Overwrite Invariant Proof
At any step, write pointer $p = p_1 + (p_2 + 1)$. Because $p_2 \ge 0$, $p > p_1$ always holds. The write head $p$ strictly leads read head $p_1$, preventing unexamined element overwrites.
Code Implementation
C++ Solution
#include <vector>
void merge(std::vector<int>& nums1, int m, const std::vector<int>& nums2, int n) {
int p1 = m - 1;
int p2 = n - 1;
int p = m + n - 1;
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] > nums2[p2]) {
nums1[p--] = nums1[p1--];
} else {
nums1[p--] = nums2[p2--];
}
}
while (p2 >= 0) {
nums1[p--] = nums2[p2--];
}
}
Python Solution
def merge(nums1: list[int], m: int, nums2: list[int], n: int) -> None:
p1 = m - 1
p2 = n - 1
p = m + n - 1
while p1 >= 0 and p2 >= 0:
if nums1[p1] > nums2[p2]:
nums1[p] = nums1[p1]
p1 -= 1
else:
nums1[p] = nums2[p2]
p2 -= 1
p -= 1
while p2 >= 0:
nums1[p] = nums2[p2]
p2 -= 1
p -= 1
Complexity
- Time Complexity: $O(m + n)$
- Auxiliary Space: $O(1)$ space
13. Dutch National Flag Problem (3-Way Partitioning)
Dijkstra’s Dutch National Flag algorithm partitions an array of 0s, 1s, and 2s in a single pass ($O(n)$ time) using three pointers: low, mid, and high.
Pointer Movement Rules
nums[mid] == 0:swap(nums[low], nums[mid]),low++,mid++.nums[mid] == 1:mid++.nums[mid] == 2:swap(nums[mid], nums[high]),high--(do not advancemidbecause the swapped element is unexamined).
Code Implementation
C++ Solution
#include <vector>
#include <algorithm>
void sortColors(std::vector<int>& nums) {
int low = 0, mid = 0;
int high = static_cast<int>(nums.size()) - 1;
while (mid <= high) {
if (nums[mid] == 0) {
std::swap(nums[low++], nums[mid++]);
} else if (nums[mid] == 1) {
mid++;
} else {
std::swap(nums[mid], nums[high--]);
}
}
}
Python Solution
def sort_colors(nums: list[int]) -> None:
low, mid = 0, 0
high = len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
Complexity
- Time Complexity: $O(n)$ single-pass
- Auxiliary Space: $O(1)$ space
14. 3Sum (Unique Zero-Sum Triplets Without Extra Set Memory)
To find all unique triplets summing to 0 in $O(n^2)$ time and $O(1)$ extra space, sort the array and use a fixed anchor i combined with a two-pointer sweep (left, right).
Deduplication Rules
- Skip anchor duplicates:
if (i > 0 && nums[i] == nums[i-1]) continue;. - Skip left/right duplicates after recording a match:
while (left < right && nums[left] == nums[left - 1]) left++;while (left < right && nums[right] == nums[right + 1]) right--;
Code Implementation
C++ Solution
#include <vector>
#include <algorithm>
std::vector<std::vector<int>> threeSum(std::vector<int>& nums) {
std::vector<std::vector<int>> result;
int n = nums.size();
if (n < 3) return result;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; ++i) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = n - 1;
while (left < right) {
long long sum = static_cast<long long>(nums[i]) + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) left++;
while (left < right && nums[right] == nums[right + 1]) right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
Python Solution
def three_sum(nums: list[int]) -> list[list[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result
Complexity
- Time Complexity: $O(n^2)$
- Auxiliary Space: $O(1)$ space (excluding output array)
15. Contiguous Subarray with Equal 0s and 1s
By mapping every 0 to -1 and leaving 1 as +1, finding a contiguous subarray with an equal number of 0s and 1s becomes equivalent to finding a subarray whose mapped elements sum to 0.
Algorithm Variants
- Longest Subarray: Use a hash map storing
{prefix_sum: earliest_index}. Initialize map with{0: -1}. Update max length when a sum re-occurs. - Count All Subarrays: Use a hash map storing
{prefix_sum: frequency}. Initialize map with{0: 1}. Addmap[prefix_sum]to total count before incrementing frequency.
Code Implementation
C++ Solution (Longest & Count Variants)
#include <vector>
#include <unordered_map>
#include <algorithm>
// Variant 1: Maximum Length Subarray
int findMaxLength(const std::vector<int>& nums) {
std::unordered_map<int, int> earliest_seen;
earliest_seen[0] = -1;
int prefix_sum = 0;
int max_len = 0;
for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
prefix_sum += (nums[i] == 0) ? -1 : 1;
if (earliest_seen.find(prefix_sum) != earliest_seen.end()) {
max_len = std::max(max_len, i - earliest_seen[prefix_sum]);
} else {
earliest_seen[prefix_sum] = i;
}
}
return max_len;
}
// Variant 2: Count Total Balanced Subarrays
int countBalancedSubarrays(const std::vector<int>& nums) {
std::unordered_map<int, int> freq;
freq[0] = 1;
int prefix_sum = 0;
int total_count = 0;
for (int val : nums) {
prefix_sum += (val == 0) ? -1 : 1;
if (freq.find(prefix_sum) != freq.end()) {
total_count += freq[prefix_sum];
}
freq[prefix_sum]++;
}
return total_count;
}
Python Solution (Longest & Count Variants)
# Variant 1: Maximum Length Subarray
def find_max_length(nums: list[int]) -> int:
earliest_seen = {0: -1}
prefix_sum = 0
max_len = 0
for i, num in enumerate(nums):
prefix_sum += -1 if num == 0 else 1
if prefix_sum in earliest_seen:
max_len = max(max_len, i - earliest_seen[prefix_sum])
else:
earliest_seen[prefix_sum] = i
return max_len
# Variant 2: Count Total Balanced Subarrays
def count_balanced_subarrays(nums: list[int]) -> int:
freq = {0: 1}
prefix_sum = 0
total_count = 0
for num in nums:
prefix_sum += -1 if num == 0 else 1
if prefix_sum in freq:
total_count += freq[prefix_sum]
freq[prefix_sum] = freq.get(prefix_sum, 0) + 1
return total_count
Complexity
- Time Complexity: $O(n)$ single-pass lookup
- Space Complexity: $O(n)$ space for hash map storage