Self Crossing - Problem
Self Crossing Path Detection
Imagine you're programming a robot to walk in a specific pattern on a grid. The robot starts at the origin
Your task is to determine if the robot's path will ever cross itself - that is, whether any line segment of the path intersects with a previously drawn line segment.
Input: An array of integers
Output: Return
Example: If
Imagine you're programming a robot to walk in a specific pattern on a grid. The robot starts at the origin
(0, 0) and follows a sequence of movements based on an array of distances. The robot moves in a counter-clockwise pattern: first north, then west, then south, then east, and so on.Your task is to determine if the robot's path will ever cross itself - that is, whether any line segment of the path intersects with a previously drawn line segment.
Input: An array of integers
distance where each element represents how far to move in the current direction.Output: Return
true if the path crosses itself, false otherwise.Example: If
distance = [2,1,1,2], the robot moves 2 units north, 1 unit west, 1 unit south, then 2 units east - creating a path that crosses itself. Input & Output
example_1.py — Simple Crossing
$
Input:
distance = [2,1,1,2]
›
Output:
true
💡 Note:
The path goes: 2 north → 1 west → 1 south → 2 east. The fourth line (east) crosses the first line (north), forming a self-intersecting rectangle.
example_2.py — No Crossing
$
Input:
distance = [1,2,3,4]
›
Output:
false
💡 Note:
The path spirals outward: 1 north → 2 west → 3 south → 4 east. Since each segment is longer than previous ones, the path doesn't cross itself.
example_3.py — Complex Crossing
$
Input:
distance = [1,1,2,1,1]
›
Output:
true
💡 Note:
This creates a more complex pattern where the fifth line crosses the second line, demonstrating Pattern 2 from our optimal solution.
Visualization
Tap to expand
Understanding the Visualization
1
Start Drawing
Begin at origin, move counter-clockwise following distance array
2
Track Recent Segments
Keep track of the last 3-5 line segments drawn
3
Check Patterns
Look for the three specific crossing patterns that can occur
4
Detect Crossing
Return true immediately when any pattern is detected
Key Takeaway
🎯 Key Insight: Self-crossings in counter-clockwise paths only happen in 3 specific geometric patterns, allowing O(n) detection instead of O(n²) brute force
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, checking only fixed number of patterns per step
✓ Linear Growth
Space Complexity
O(1)
Only store the last few line segment lengths, no additional data structures
✓ Linear Space
Constraints
- 1 ≤ distance.length ≤ 105
- 1 ≤ distance[i] ≤ 105
- The path always starts at origin (0,0) and moves counter-clockwise
- Movement directions cycle: North → West → South → East → North...
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code