Self Crossing - Problem
You are given an array of integers distance. You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on.
In other words, after each move, your direction changes counter-clockwise. The directions cycle as: North → West → South → East → North...
Return true if your path crosses itself, or false if it does not.
Input & Output
Example 1 — Basic Crossing
$
Input:
distance = [2,1,1,2]
›
Output:
true
💡 Note:
Starting at (0,0): North 2→(0,2), West 1→(-1,2), South 1→(-1,1), East 2→(1,1). The fourth line (East) crosses the first line (North).
Example 2 — No Crossing
$
Input:
distance = [1,2,3,4]
›
Output:
false
💡 Note:
The path forms an expanding spiral. Starting at (0,0): North 1→(0,1), West 2→(-2,1), South 3→(-2,-2), East 4→(2,-2). No lines intersect.
Example 3 — Simple Square
$
Input:
distance = [1,1,1,1]
›
Output:
true
💡 Note:
Forms a perfect 1×1 square: North→(0,1), West→(-1,1), South→(-1,0), East→(0,0). The fourth line ends exactly at the starting point.
Constraints
- 1 ≤ distance.length ≤ 105
- 1 ≤ distance[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of distances [2,1,1,2] for N,W,S,E moves
2
Path Generation
Draw lines counter-clockwise from (0,0)
3
Crossing Check
Detect if any lines intersect
Key Takeaway
🎯 Key Insight: Due to counter-clockwise movement, a line can only intersect with one of the previous 3 lines, enabling O(n) pattern recognition.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code