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
Self Crossing Path DetectionInput: distance = [2,1,1,2]Directions: North → West → South → EastStart (0,0)North: 2 unitsWest: 1 unitSouth: 1 unitEast: 2 unitsCrossing!Path Analysis:• Start at origin (0,0)• Move North 2 units• Move West 1 unit• Move South 1 unit• Move East 2 units→ East line crosses North line!Output: true
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.
Asked in
Google 25 Amazon 18
67.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen