Campus Bikes II — LeetCode 1066 Python Solution

MediumLeetCode PremiumBit ManipulationArrayDynamic ProgrammingBacktrackingBitmask
Problem
#1066
Reading time
3 min

The problem

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.

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

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1066. Campus Bikes II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1066. Campus Bikes II?
LeetCode 1066. Campus Bikes II is rated Medium on LeetCode.
What topics does LeetCode 1066. Campus Bikes II cover?
LeetCode 1066. Campus Bikes II is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.
Is LeetCode 1066. Campus Bikes II a premium problem?
Yes. LeetCode 1066. Campus Bikes II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview