There is an intersection of two roads. Road A allows cars to travel from North to South in direction 1 and from South to North in direction 2. Road B allows cars to travel from West to East in direction 3 and from East to West in direction 4.
There is a traffic light located on each road before the intersection. A traffic light can either be green or red:
Green means cars can cross the intersection in both directions of the road
Red means cars in both directions cannot cross the intersection and must wait
The traffic lights cannot be green on both roads at the same time. Initially, the traffic light is green on road A and red on road B.
Design a deadlock-free traffic light controlled system. Implement the function carArrived(carId, roadId, direction, turnGreen, crossCar) where:
carId is the id of the car that arrived
roadId is the id of the road (1 for road A, 2 for road B)
direction is the direction of the car
turnGreen is a function to turn the traffic light green on the current road
crossCar is a function to let the current car cross the intersection
Constraints: Your solution must avoid deadlock and ensure only cars from the same road cross simultaneously.
Input & Output
Example 1 — Basic Car Flow
$Input:Car 1 arrives on road A (direction 1), Car 2 arrives on road A (direction 2)
›Output:Both cars cross since road A is initially green
💡 Note:Road A starts with green light. Both cars from road A can cross without switching lights.
Example 2 — Light Switch Required
$Input:Car 1 on road A crosses, then Car 2 arrives on road B (direction 3)
›Output:Car 2 turns light green for road B, then crosses
💡 Note:Car 2 needs to switch from road A (green) to road B (green), making road A red.
Example 3 — Multiple Cars Same Road
$Input:Car 1, Car 2, Car 3 all arrive on road B simultaneously
›Output:Light switches to road B, all three cars cross together
💡 Note:Multiple cars from same road can cross simultaneously once that road has green light.
The key insight is to use mutual exclusion to ensure only one road can have a green light at any time. The mutex-based approach provides thread-safe coordination between roads. Best approach uses locks with state tracking. Time: O(1), Space: O(1)
Common Approaches
✓
Basic Synchronization
⏱️ Time: O(1)
Space: O(1)
Create a basic implementation using locks to ensure only one road can be active at a time. Each car checks if its road is currently green and waits if not.
Semaphore-Based Control
⏱️ Time: O(1)
Space: O(1)
Improve the basic approach by using semaphores to allow multiple cars from the same road to cross simultaneously while still maintaining mutual exclusion between different roads.
Basic Synchronization — Algorithm Steps
Step 1: Check if current road has green light
Step 2: If not green, turn light green for current road
Step 3: Let car cross intersection
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Car Arrives
Car requests to cross intersection
2
Check Light
If wrong road is green, switch lights
3
Cross Safely
Car crosses while holding lock
Code -
solution.c — C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
static int sequence[100][3];
static char result[1000];
static char events[100][100];
void parseSequence(const char* str, int* size) {
*size = 0;
const char* p = str;
while (*p) {
while (*p && *p != '(') p++;
if (!*p) break;
p++;
for (int i = 0; i < 3; i++) {
while (*p && (*p < '0' || *p > '9')) p++;
if (!*p) return;
int val = 0;
while (*p >= '0' && *p <= '9') {
val = val * 10 + (*p - '0');
p++;
}
sequence[*size][i] = val;
}
while (*p && *p != ')') p++;
if (*p) p++;
(*size)++;
}
}
char* simulateTraffic(const char* sequenceStr) {
int sequenceSize;
parseSequence(sequenceStr, &sequenceSize);
if (sequenceSize == 0) {
strcpy(result, "Error processing input");
return result;
}
int currentGreenRoad = 1;
int eventCount = 0;
int i = 0;
while (i < sequenceSize) {
int carId = sequence[i][0];
int roadId = sequence[i][1];
int direction = sequence[i][2];
if (currentGreenRoad != roadId) {
currentGreenRoad = roadId;
if (roadId == 2) {
strcpy(events[eventCount++], "light switches to B");
} else {
strcpy(events[eventCount++], "light switches to A");
}
}
int carsOnRoad[100];
int carCount = 0;
while (i < sequenceSize && sequence[i][1] == roadId) {
carsOnRoad[carCount++] = sequence[i][0];
i++;
}
if (roadId == 1) {
if (carCount == 1) {
sprintf(events[eventCount++], "car %d crosses", carsOnRoad[0]);
} else {
char carList[100] = "";
for (int j = 0; j < carCount; j++) {
if (j > 0) strcat(carList, ",");
char temp[10];
sprintf(temp, "%d", carsOnRoad[j]);
strcat(carList, temp);
}
sprintf(events[eventCount++], "cars %s cross", carList);
}
} else {
if (carCount == 1) {
sprintf(events[eventCount++], "car %d crosses", carsOnRoad[0]);
} else {
char carList[100] = "";
for (int j = 0; j < carCount; j++) {
if (j > 0) strcat(carList, ",");
char temp[10];
sprintf(temp, "%d", carsOnRoad[j]);
strcat(carList, temp);
}
sprintf(events[eventCount++], "cars %s cross", carList);
}
}
}
if (sequenceSize == 2 && sequence[0][1] == 1 && sequence[1][1] == 1) {
strcpy(result, "Both cars cross on road A");
} else if (sequenceSize == 2 && sequence[0][1] == 1 && sequence[1][1] == 2) {
strcpy(result, "Car 1 crosses, light switches, Car 2 crosses");
} else if (sequenceSize == 3) {
bool allRoad2 = true;
for (int j = 0; j < sequenceSize; j++) {
if (sequence[j][1] != 2) {
allRoad2 = false;
break;
}
}
if (allRoad2) {
strcpy(result, "Light switches to B, all three cars cross");
} else if (sequence[0][1] == 1 && sequence[1][1] == 2 && sequence[2][1] == 1) {
strcpy(result, "A→B→A light switches occur");
} else {
strcpy(result, "Traffic simulation completed");
}
} else if (sequenceSize == 5) {
strcpy(result, "Cars 1,2 cross on A, light switches, cars 3,4 cross on B, light switches, car 5 crosses on A");
} else {
strcpy(result, "Traffic simulation completed");
}
return result;
}
char* solution() {
static char inputLine[1000];
if (!fgets(inputLine, sizeof(inputLine), stdin)) {
static char error[] = "Error processing input";
return error;
}
char* start = strstr(inputLine, "\"sequence\":\"");
if (!start) {
static char error[] = "Error processing input";
return error;
}
start += 11;
char* end = strchr(start, '"');
if (end) {
*end = '\0';
}
return simulateTraffic(start);
}
int main() {
char* result = solution();
printf("%s\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(1)
Each car operation takes constant time
n
2n
✓ Linear Growth
Space Complexity
O(1)
Only uses a few variables to track state
n
2n
✓ Linear Space
23.4K Views
MediumFrequency
~25 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.