Leetcode #1066: Campus Bikes II
In this guide, we solve Leetcode #1066 Campus Bikes II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
On a campus represented as a 2D grid, there are n workers and m bikes, with n <= m. Each worker and bike is a 2D coordinate on this grid.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Bit Manipulation, Array, Dynamic Programming, Backtracking, Bitmask
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: 6
Explanation:
We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6.
Python Solution
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int:
n, m = len(workers), len(bikes)
f = [[inf] * (1 << m) for _ in range(n + 1)]
f[0][0] = 0
for i, (x1, y1) in enumerate(workers, 1):
for j in range(1 << m):
for k, (x2, y2) in enumerate(bikes):
if j >> k & 1:
f[i][j] = min(
f[i][j],
f[i - 1][j ^ (1 << k)] + abs(x1 - x2) + abs(y1 - y2),
)
return min(f[n])
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.