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. You are also given an array bikes of length m where bikes[j] = [xj, yj] is the position of the jth bike.
Assign a bike to each worker using the following rules:
1. Among all available (worker, bike) pairs, choose the one with the shortest Manhattan distance 2. If there are ties, choose the pair with the smallest worker index 3. If there are still ties, choose the pair with the smallest bike index 4. Repeat until all workers have bikes
Return an array answer where answer[i] is the index of the bike assigned to the ith worker.
The Manhattan distance between two points p1 and p2 is: |p1.x - p2.x| + |p1.y - p2.y|
💡 Note:Worker 0 at (0,0): distances to bikes are [3,6,3]. Worker 1 at (2,1): distances are [2,3,0]. Closest pair is (worker 1, bike 2) with distance 0, so assign worker 1 → bike 2. Next closest available is (worker 0, bike 0) with distance 3, so worker 0 → bike 0.
💡 Note:Multiple pairs have distance 2. When tied, we choose smaller worker index first, then smaller bike index. Worker 0 gets bike 0 (distance 1), worker 1 gets bike 2 (distance 1), worker 2 gets bike 1 (distance 2).
The key insight is to use greedy assignment with proper tie-breaking rules. Generate all worker-bike distance pairs, sort by distance/worker/bike priority, then assign greedily. Best approach is brute force sorting for simplicity or priority queue for memory efficiency. Time: O(nm log(nm)), Space: O(nm).
Common Approaches
✓
Brute Force - All Combinations
⏱️ Time: O(nm log(nm))
Space: O(nm)
Generate all possible (worker, bike) pairs, calculate Manhattan distances, sort by distance/worker/bike priority, then assign bikes greedily following the sorted order.
Priority Queue Optimization
⏱️ Time: O(nm log(nm))
Space: O(nm)
Instead of generating all pairs upfront, use a priority queue to dynamically get the next best (worker, bike) pair. This reduces memory usage and can be faster when workers get assigned early.
Brute Force - All Combinations — Algorithm Steps
Calculate Manhattan distance for all worker-bike pairs
Sort pairs by distance, then worker index, then bike index
Assign bikes in sorted order, skipping already assigned bikes
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Generate Pairs
Calculate distance for all worker-bike combinations
2
Sort by Priority
Order by distance, worker index, bike index
3
Greedy Assignment
Assign first available bike for each worker
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int dist, worker, bike;
} Pair;
int compare(const void* a, const void* b) {
Pair* pa = (Pair*)a;
Pair* pb = (Pair*)b;
if (pa->dist != pb->dist) return pa->dist - pb->dist;
if (pa->worker != pb->worker) return pa->worker - pb->worker;
return pa->bike - pb->bike;
}
int* solution(int** workers, int workersSize, int** bikes, int bikesSize, int* returnSize) {
*returnSize = workersSize;
// Generate all pairs
Pair* pairs = malloc(workersSize * bikesSize * sizeof(Pair));
int pairCount = 0;
for (int i = 0; i < workersSize; i++) {
for (int j = 0; j < bikesSize; j++) {
int dist = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
pairs[pairCount++] = (Pair){dist, i, j};
}
}
// Sort pairs
qsort(pairs, pairCount, sizeof(Pair), compare);
// Assign bikes
int* result = malloc(workersSize * sizeof(int));
int* usedBikes = calloc(bikesSize, sizeof(int));
for (int i = 0; i < workersSize; i++) {
result[i] = -1;
}
for (int i = 0; i < pairCount; i++) {
int worker = pairs[i].worker;
int bike = pairs[i].bike;
if (result[worker] == -1 && !usedBikes[bike]) {
result[worker] = bike;
usedBikes[bike] = 1;
}
}
free(pairs);
free(usedBikes);
return result;
}
int parseArray(char* line, int*** arr, int* size) {
*size = 0;
if (strlen(line) <= 2) return 0; // Empty array []
// Count pairs by counting '[' after the first one
for (int i = 1; i < strlen(line); i++) {
if (line[i] == '[') (*size)++;
}
*arr = malloc(*size * sizeof(int*));
for (int i = 0; i < *size; i++) {
(*arr)[i] = malloc(2 * sizeof(int));
}
int idx = 0;
char* ptr = line + 1; // Skip first '['
while (idx < *size && *ptr) {
while (*ptr && *ptr != '[') ptr++; // Find next '['
if (!*ptr) break;
ptr++; // Skip '['
// Parse first number
(*arr)[idx][0] = strtol(ptr, &ptr, 10);
while (*ptr && *ptr != ',') ptr++; // Skip to ','
if (*ptr == ',') ptr++; // Skip ','
// Parse second number
(*arr)[idx][1] = strtol(ptr, &ptr, 10);
while (*ptr && *ptr != ']') ptr++; // Skip to ']'
if (*ptr == ']') ptr++; // Skip ']'
idx++;
}
return *size;
}
int main() {
char line[10000];
// Read workers
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0; // Remove newline
int** workers;
int workersSize;
parseArray(line, &workers, &workersSize);
// Read bikes
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0; // Remove newline
int** bikes;
int bikesSize;
parseArray(line, &bikes, &bikesSize);
int returnSize;
int* result = solution(workers, workersSize, bikes, bikesSize, &returnSize);
printf("[");
for (int i = 0; i < returnSize; i++) {
if (i > 0) printf(",");
printf("%d", result[i]);
}
printf("]\n");
// Free memory
for (int i = 0; i < workersSize; i++) {
free(workers[i]);
}
free(workers);
for (int i = 0; i < bikesSize; i++) {
free(bikes[i]);
}
free(bikes);
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(nm log(nm))
Generate nm pairs, then sort them
n
2n
⚡ Linearithmic
Space Complexity
O(nm)
Store all nm worker-bike distance pairs
n
2n
⚡ Linearithmic Space
78.6K Views
MediumFrequency
~25 minAvg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.