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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: houses = [1,4,8,10,20], k = 3 Output: 5 Explanation: Allocate mailboxes in position 3, 9 and 20. Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
Example 2:
Input: houses = [2,3,5,12,18], k = 2 Output: 9 Explanation: Allocate mailboxes in position 3 and 14. Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
Constraints:
1 <= k <= houses.length <= 1001 <= houses[i] <= 104houses are unique.Problem summary: Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox. The test cases are generated so that the answer fits in a 32-bit integer.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Dynamic Programming
[1,4,8,10,20] 3
[2,3,5,12,18] 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1478: Allocate Mailboxes
class Solution {
public int minDistance(int[] houses, int k) {
Arrays.sort(houses);
int n = houses.length;
int[][] g = new int[n][n];
for (int i = n - 2; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
g[i][j] = g[i + 1][j - 1] + houses[j] - houses[i];
}
}
int[][] f = new int[n][k + 1];
final int inf = 1 << 30;
for (int[] e : f) {
Arrays.fill(e, inf);
}
for (int i = 0; i < n; ++i) {
f[i][1] = g[0][i];
for (int j = 2; j <= k && j <= i + 1; ++j) {
for (int p = 0; p < i; ++p) {
f[i][j] = Math.min(f[i][j], f[p][j - 1] + g[p + 1][i]);
}
}
}
return f[n - 1][k];
}
}
// Accepted solution for LeetCode #1478: Allocate Mailboxes
func minDistance(houses []int, k int) int {
sort.Ints(houses)
n := len(houses)
g := make([][]int, n)
f := make([][]int, n)
const inf = 1 << 30
for i := range g {
g[i] = make([]int, n)
f[i] = make([]int, k+1)
for j := range f[i] {
f[i][j] = inf
}
}
for i := n - 2; i >= 0; i-- {
for j := i + 1; j < n; j++ {
g[i][j] = g[i+1][j-1] + houses[j] - houses[i]
}
}
for i := 0; i < n; i++ {
f[i][1] = g[0][i]
for j := 2; j <= k && j <= i+1; j++ {
for p := 0; p < i; p++ {
f[i][j] = min(f[i][j], f[p][j-1]+g[p+1][i])
}
}
}
return f[n-1][k]
}
# Accepted solution for LeetCode #1478: Allocate Mailboxes
class Solution:
def minDistance(self, houses: List[int], k: int) -> int:
houses.sort()
n = len(houses)
g = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
g[i][j] = g[i + 1][j - 1] + houses[j] - houses[i]
f = [[inf] * (k + 1) for _ in range(n)]
for i in range(n):
f[i][1] = g[0][i]
for j in range(2, min(k + 1, i + 2)):
for p in range(i):
f[i][j] = min(f[i][j], f[p][j - 1] + g[p + 1][i])
return f[-1][k]
// Accepted solution for LeetCode #1478: Allocate Mailboxes
struct Solution;
use std::collections::HashMap;
impl Solution {
fn min_distance(mut houses: Vec<i32>, k: i32) -> i32 {
let n = houses.len();
let k = k as usize;
houses.sort_unstable();
let mut memo: HashMap<(usize, usize), i32> = HashMap::new();
Self::dp(0, k, &mut memo, &houses, n)
}
fn dp(
start: usize,
k: usize,
memo: &mut HashMap<(usize, usize), i32>,
houses: &[i32],
n: usize,
) -> i32 {
if let Some(&res) = memo.get(&(start, k)) {
return res;
}
let res = if k == 1 {
Self::distance(start, n, houses)
} else {
let mut min = std::i32::MAX;
for i in start..=n - k {
let end = i + 1;
let dist = Self::distance(start, end, houses);
min = min.min(dist + Self::dp(end, k - 1, memo, houses, n));
}
min
};
memo.insert((start, k), res);
res
}
fn distance(start: usize, end: usize, houses: &[i32]) -> i32 {
let mut sum = 0;
let median = (houses[(start + end - 1) / 2] + houses[(start + end) / 2]) / 2;
for i in start..end {
sum += (houses[i] - median).abs();
}
sum
}
}
#[test]
fn test() {
let houses = vec![1, 4, 8, 10, 20];
let k = 3;
let res = 5;
assert_eq!(Solution::min_distance(houses, k), res);
let houses = vec![2, 3, 5, 12, 18];
let k = 2;
let res = 9;
assert_eq!(Solution::min_distance(houses, k), res);
let houses = vec![7, 4, 6, 1];
let k = 1;
let res = 8;
assert_eq!(Solution::min_distance(houses, k), res);
let houses = vec![3, 6, 14, 10];
let k = 4;
let res = 0;
assert_eq!(Solution::min_distance(houses, k), res);
}
// Accepted solution for LeetCode #1478: Allocate Mailboxes
function minDistance(houses: number[], k: number): number {
houses.sort((a, b) => a - b);
const n = houses.length;
const g: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let i = n - 2; i >= 0; i--) {
for (let j = i + 1; j < n; j++) {
g[i][j] = g[i + 1][j - 1] + houses[j] - houses[i];
}
}
const inf = Number.POSITIVE_INFINITY;
const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(inf));
for (let i = 0; i < n; i++) {
f[i][1] = g[0][i];
}
for (let j = 2; j <= k; j++) {
for (let i = j - 1; i < n; i++) {
for (let p = i - 1; p >= 0; p--) {
f[i][j] = Math.min(f[i][j], f[p][j - 1] + g[p + 1][i]);
}
}
}
return f[n - 1][k];
}
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: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
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.