Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4,3,2,3,5,2,1], k = 4 Output: true Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:
Input: nums = [1,2,3,4], k = 3 Output: false
Constraints:
1 <= k <= nums.length <= 161 <= nums[i] <= 104[1, 4].Problem summary: Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Backtracking · Bit Manipulation
[4,3,2,3,5,2,1] 4
[1,2,3,4] 3
partition-equal-subset-sum)fair-distribution-of-cookies)maximum-number-of-ways-to-partition-an-array)maximum-rows-covered-by-columns)maximum-product-of-two-integers-with-no-common-bits)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #698: Partition to K Equal Sum Subsets
class Solution {
private int[] nums;
private int[] cur;
private int s;
public boolean canPartitionKSubsets(int[] nums, int k) {
for (int v : nums) {
s += v;
}
if (s % k != 0) {
return false;
}
s /= k;
cur = new int[k];
Arrays.sort(nums);
this.nums = nums;
return dfs(nums.length - 1);
}
private boolean dfs(int i) {
if (i < 0) {
return true;
}
for (int j = 0; j < cur.length; ++j) {
if (j > 0 && cur[j] == cur[j - 1]) {
continue;
}
cur[j] += nums[i];
if (cur[j] <= s && dfs(i - 1)) {
return true;
}
cur[j] -= nums[i];
}
return false;
}
}
// Accepted solution for LeetCode #698: Partition to K Equal Sum Subsets
func canPartitionKSubsets(nums []int, k int) bool {
s := 0
for _, v := range nums {
s += v
}
if s%k != 0 {
return false
}
s /= k
cur := make([]int, k)
n := len(nums)
var dfs func(int) bool
dfs = func(i int) bool {
if i == n {
return true
}
for j := 0; j < k; j++ {
if j > 0 && cur[j] == cur[j-1] {
continue
}
cur[j] += nums[i]
if cur[j] <= s && dfs(i+1) {
return true
}
cur[j] -= nums[i]
}
return false
}
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
return dfs(0)
}
# Accepted solution for LeetCode #698: Partition to K Equal Sum Subsets
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
def dfs(i: int) -> bool:
if i == len(nums):
return True
for j in range(k):
if j and cur[j] == cur[j - 1]:
continue
cur[j] += nums[i]
if cur[j] <= s and dfs(i + 1):
return True
cur[j] -= nums[i]
return False
s, mod = divmod(sum(nums), k)
if mod:
return False
cur = [0] * k
nums.sort(reverse=True)
return dfs(0)
// Accepted solution for LeetCode #698: Partition to K Equal Sum Subsets
struct Solution;
impl Solution {
fn can_partition_k_subsets(nums: Vec<i32>, k: i32) -> bool {
let n = nums.len();
let sum: i32 = nums.iter().sum();
if sum % k != 0 {
return false;
}
let mut visited: Vec<bool> = vec![false; n];
Self::search(0, 0, k as usize, &mut visited, &nums, n, sum / k)
}
fn search(
start: usize,
sum: i32,
k: usize,
visited: &mut Vec<bool>,
nums: &[i32],
n: usize,
target: i32,
) -> bool {
if k == 0 {
return true;
}
for i in start..n {
if visited[i] {
continue;
}
visited[i] = true;
if sum + nums[i] < target
&& Self::search(i + 1, sum + nums[i], k, visited, nums, n, target)
{
return true;
}
if sum + nums[i] == target && Self::search(0, 0, k - 1, visited, nums, n, target) {
return true;
}
visited[i] = false;
}
false
}
}
#[test]
fn test() {
// let nums = vec![4, 3, 2, 3, 5, 2, 1];
// let k = 4;
// let res = true;
// assert_eq!(Solution::can_partition_k_subsets(nums, k), res);
let nums = vec![2, 2, 2, 2, 3, 4, 5];
let k = 4;
let res = false;
assert_eq!(Solution::can_partition_k_subsets(nums, k), res);
}
// Accepted solution for LeetCode #698: Partition to K Equal Sum Subsets
function canPartitionKSubsets(nums: number[], k: number): boolean {
const dfs = (i: number): boolean => {
if (i === nums.length) {
return true;
}
for (let j = 0; j < k; j++) {
if (j > 0 && cur[j] === cur[j - 1]) {
continue;
}
cur[j] += nums[i];
if (cur[j] <= s && dfs(i + 1)) {
return true;
}
cur[j] -= nums[i];
}
return false;
};
let s = nums.reduce((a, b) => a + b, 0);
const mod = s % k;
if (mod !== 0) {
return false;
}
s = Math.floor(s / k);
const cur = Array(k).fill(0);
nums.sort((a, b) => b - a);
return dfs(0);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.