1478. Allocate Mailboxes - Detailed Explanation
Problem Statement
Description
Given an array houses where houses[i] is the position of the ith house on a number line, and an integer k, you want to build k mailboxes at integer locations. Return the minimum total distance between each house and its nearest mailbox.
Examples
Example 1
Input: houses = [1,4,8,10,20], k = 3
Output: 5
Explanation: Sort houses → [1,4,8,10,20].
Place mailboxes at 3, 9, 20.
Distances: |1-3|+|4-3| + |8-9|+|10-9| + |20-20| = 2+1 + 1+1 + 0 = 5
Example 2
Input: houses = [2,3,5,12,18], k = 2
Output: 9
Explanation: Sort → [2,3,5,12,18].
Split into [2,3,5] and [12,18].
Best mailbox positions are at medians 3 and 12.
Distances: (|2-3|+|3-3|+|5-3|)=1+0+2=3 plus (|12-12|+|18-12|)=0+6=6 → total 9
Example 3
Input: houses = [7,4,6,1], k = 1
Output: 8
Explanation: Sort → [1,4,6,7]. One mailbox at median index (1+4+6+7)/2→between 4 and 6, either 4 or 6 → pick 6.
Distances: |1-6|+|4-6|+|6-6|+|7-6| = 5+2+0+1 = 8
Constraints
- 1 ≤
houses.length≤ 100 - 1 ≤
houses[i]≤ 10⁴ - All
houses[i]are distinct - 1 ≤
k≤houses.length
Hints
- Why sort
housesbefore anything else? How does that help grouping? - For any contiguous group of houses, where’s the best mailbox location? How can you compute that cost quickly for every possible interval?
Brute‑Force Partitioning Approach
Idea
Try every way to split the sorted houses into k contiguous groups, place one mailbox per group at its median, and sum distances.
Steps
- Sort
houses. - Define a recursive function
dfs(start, rem)that returns the minimum cost to coverhouses[start:]withremmailboxes. - If
rem == 1, cost = distance‐sum when placing at median ofhouses[start:]. - Otherwise, for every
endfromstartton - rem, consider one mailbox coveringstart…end, then recurse onend+1withrem-1. - Take the minimum over all splits.
Why It’s Impractical
- There are O(nᵏ) ways to choose splits. With n up to 100, k up to n, this explodes exponentially.
Optimized DP with Precomputed Costs
Idea
- Precompute
cost[i][j]= minimal distance if one mailbox serves houses[i…j]. This is placing the mailbox at the median index m = (i+j)//2. - Use DP:
dp[g][i]= min total distance serving the firsti+1houses withgmailboxes. - Recurrence:
dp[1][i] = cost[0][i] dp[g][i] = min for all t < i of (dp[g-1][t] + cost[t+1][i])
Steps
- Sort
houses; letn = len(houses). - Build
costarray of sizen×n:- For each
i ≤ j, compute median indexm = (i+j)//2and sumabs(houses[x] - houses[m])for x in [i…j].
- For each
- Initialize a DP table
dp[k+1][n]with ∞. - Set
dp[1][i] = cost[0][i]for all i. - For
gfrom 2 to k, forifrom g-1 to n-1:- For
tfrom g-2 to i-1:dp[g][i] = min(dp[g][i], dp[g-1][t] + cost[t+1][i])
- For
- Answer =
dp[k][n-1].
Complexity Analysis
- Sorting: O(n log n)
- Cost Precompute: O(n²) intervals × O(n) summation → O(n³), but you can optimize each interval in O(1) amortized by two‐pointer median expansion; still O(n²) overall for n≤100.
- DP: O(k × n²)
- Total: O(k n² + n² + n log n) → dominated by O(k n²), feasible for n≤100, k≤100.
Code (Python)
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
Step‑by‑Step Walkthrough and Visual Example
For houses = [1,4,8,10,20], k = 3:
- Sort →
[1,4,8,10,20]. - Compute cost table:
cost[0][1]covers [1,4], median=1 or 4→choose 1 or 4; best sum=3.cost[0][2]covers [1,4,8], median=4→|1-4|+|4-4|+|8-4|=7, etc.
… fill allcost[i][j].
- DP layers:
dp[1][i] = cost[0][i]for i=0…4.dp[2][i] = min over split t of dp[1][t] + cost[t+1][i].dp[3][4]= final answer = 5.
Common Mistakes
- Forgetting to sort
housesfirst → wrong median segments. - Computing cost by choosing mean instead of median.
- Off‑by‑one errors in DP indices (
t+1vst). - Using an O(n³) cost precompute without optimizing, which can still pass for n≤100 but is easy to mis‐index.
Edge Cases
- k ≥ n: put a mailbox at each house → cost = 0.
- k = 1: one mailbox at overall median → sum of distances to that median.
- All houses identical: any mailbox at that position yields cost = 0.
Alternative Variations
- Weighted houses: each house has a weight (residents count); median becomes weighted median.
- 2D version: houses on a grid, mailboxes also placed on integer grid points (requires advanced geometry/DP).
- Continuous mailbox positions: allow mailbox anywhere on the line (still median‐based for each segment).
Related Problems
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
3026. Maximum Good Subarray Sum - Detailed Explanation
Learn to solve Leetcode 3026. Maximum Good Subarray Sum with multiple approaches.
652. Find Duplicate Subtrees - Detailed Explanation
Learn to solve Leetcode 652. Find Duplicate Subtrees with multiple approaches.
84. Largest Rectangle in Histogram - Detailed Explanation
Learn to solve Leetcode 84. Largest Rectangle in Histogram with multiple approaches.
532. K-diff Pairs in an Array - Detailed Explanation
Learn to solve Leetcode 532. K-diff Pairs in an Array with multiple approaches.
83. Remove Duplicates from Sorted List - Detailed Explanation
Learn to solve Leetcode 83. Remove Duplicates from Sorted List with multiple approaches.
3428. Maximum and Minimum Sums of at Most Size K Subsequences - Detailed Explanation
Learn to solve Leetcode 3428. Maximum and Minimum Sums of at Most Size K Subsequences with multiple approaches.
Related Courses

Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
$197

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
$78

Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
$78
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.