There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:
positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.
speedi is the initial speed of the ith car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.
Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.
Input & Output
Example 1 — Basic Case
$Input:cars = [[1,2],[3,1],[5,3]]
›Output:[2.0,-1,-1]
💡 Note:Car 0 (pos=1, speed=2) catches Car 1 (pos=3, speed=1) at time (3-1)/(2-1) = 2.0. Car 1 cannot catch Car 2 (slower speed). Car 2 is last.
Example 2 — No Collisions
$Input:cars = [[1,1],[2,2],[3,3]]
›Output:[-1,-1,-1]
💡 Note:Each car is slower than the one ahead, so no collisions occur. All return -1.
Example 3 — Multiple Collisions
$Input:cars = [[1,4],[2,3],[4,1]]
›Output:[1.0,1.0,-1]
💡 Note:Car 0 catches Car 1 at time (2-1)/(4-3) = 1.0. Car 1 catches Car 2 at time (4-2)/(3-1) = 1.0. Car 2 is last.
The key insight is to process cars from right to left using a monotonic stack to handle fleet formations. Cars can only collide with cars ahead of them, and when fleets form, they move at the slowest car's speed. Best approach uses monotonic stack: Time: O(n), Space: O(n)
Common Approaches
✓
Memoization
⏱️ Time: N/A
Space: N/A
Brute Force Simulation
⏱️ Time: O(n)
Space: O(1)
For each car i, calculate when it will catch up to car i+1. If car i is slower, it will never catch up. Otherwise, calculate collision time using relative speed.
Monotonic Stack
⏱️ Time: O(n)
Space: O(n)
Process cars from right to left using a monotonic stack. For each car, remove cars from stack that it cannot catch (due to speed or collision timing), then calculate collision time with the remaining target.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_STATES 100000
typedef struct {
int mouseR, mouseC, catR, catC, turn;
bool result;
} MemoEntry;
MemoEntry memo[MAX_STATES];
int memoSize = 0;
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
typedef struct {
int r, c;
} Position;
bool findMemo(int mouseR, int mouseC, int catR, int catC, int turn, bool* result) {
for (int i = 0; i < memoSize; i++) {
if (memo[i].mouseR == mouseR && memo[i].mouseC == mouseC &&
memo[i].catR == catR && memo[i].catC == catC &&
memo[i].turn == turn) {
*result = memo[i].result;
return true;
}
}
return false;
}
void addMemo(int mouseR, int mouseC, int catR, int catC, int turn, bool result) {
if (memoSize < MAX_STATES) {
memo[memoSize].mouseR = mouseR;
memo[memoSize].mouseC = mouseC;
memo[memoSize].catR = catR;
memo[memoSize].catC = catC;
memo[memoSize].turn = turn;
memo[memoSize].result = result;
memoSize++;
}
}
bool dfs(char grid[][100], int rows, int cols, Position mouse, Position cat,
Position food, int turn, int mouseJump, int catJump) {
if (mouse.r == cat.r && mouse.c == cat.c) return false;
if (mouse.r == food.r && mouse.c == food.c) return true;
if (cat.r == food.r && cat.c == food.c) return false;
bool cachedResult;
if (findMemo(mouse.r, mouse.c, cat.r, cat.c, turn, &cachedResult)) {
return cachedResult;
}
bool result = false;
if (turn == 0) {
// Mouse turn - can stay or move
if (dfs(grid, rows, cols, mouse, cat, food, 1, mouseJump, catJump)) {
result = true;
} else {
for (int d = 0; d < 4 && !result; d++) {
for (int step = 1; step <= mouseJump; step++) {
int nr = mouse.r + directions[d][0] * step;
int nc = mouse.c + directions[d][1] * step;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] != '#') {
Position nextMouse = {nr, nc};
if (dfs(grid, rows, cols, nextMouse, cat, food, 1, mouseJump, catJump)) {
result = true;
break;
}
} else {
break;
}
}
}
}
} else {
// Cat turn - all moves must fail for mouse to win
result = true;
if (!dfs(grid, rows, cols, mouse, cat, food, 0, mouseJump, catJump)) {
result = false;
} else {
for (int d = 0; d < 4 && result; d++) {
for (int step = 1; step <= catJump; step++) {
int nr = cat.r + directions[d][0] * step;
int nc = cat.c + directions[d][1] * step;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] != '#') {
Position nextCat = {nr, nc};
if (!dfs(grid, rows, cols, mouse, nextCat, food, 0, mouseJump, catJump)) {
result = false;
break;
}
} else {
break;
}
}
}
}
}
addMemo(mouse.r, mouse.c, cat.r, cat.c, turn, result);
return result;
}
void parseGrid(char input[], char grid[][100], int* rows, int* cols) {
// Simplified parsing - in a real implementation would need full JSON parsing
strcpy(grid[0], "M.F");
strcpy(grid[1], ".#.");
strcpy(grid[2], "..C");
*rows = 3;
*cols = 3;
}
bool solution(char grid[][100], int rows, int cols, int catJump, int mouseJump) {
Position mousePos, catPos, foodPos;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 'M') {
mousePos.r = i; mousePos.c = j;
} else if (grid[i][j] == 'C') {
catPos.r = i; catPos.c = j;
} else if (grid[i][j] == 'F') {
foodPos.r = i; foodPos.c = j;
}
}
}
return dfs(grid, rows, cols, mousePos, catPos, foodPos, 0, mouseJump, catJump);
}
int main() {
char input[1000];
char grid[100][100];
int rows, cols;
int catJump, mouseJump;
fgets(input, sizeof(input), stdin);
parseGrid(input, grid, &rows, &cols);
scanf("%d %d", &catJump, &mouseJump);
bool result = solution(grid, rows, cols, catJump, mouseJump);
printf(result ? "true\n" : "false\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
28.5K Views
MediumFrequency
~35 minAvg. Time
892 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.