Leetcode #1057: Campus Bikes
In this guide, we solve Leetcode #1057 Campus Bikes 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 on the X-Y plane, there are n workers and m bikes, with n <= m. You are given an array workers of length n where workers[i] = [xi, yi] is the position of the ith worker.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Sorting, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: [1,0]
Explanation: Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0].
Python Solution
class Solution:
def assignBikes(
self, workers: List[List[int]], bikes: List[List[int]]
) -> List[int]:
n, m = len(workers), len(bikes)
arr = []
for i, j in product(range(n), range(m)):
dist = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1])
arr.append((dist, i, j))
arr.sort()
vis1 = [False] * n
vis2 = [False] * m
ans = [0] * n
for _, i, j in arr:
if not vis1[i] and not vis2[j]:
vis1[i] = vis2[j] = True
ans[i] = j
return ans
Complexity
The time complexity is O(n log n). The space complexity is O(n).
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.