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 Problem INPUT 2 1 1 2 CROSS! Start N S W E distance array: 2 1 1 2 [0] [1] [2] [3] ALGORITHM STEPS 1 Identify Patterns 3 crossing patterns exist 2 Pattern Check For i >= 3, check d[i] vs d[i-2] relationship 3 Check Case 1 d[i] >= d[i-2] AND d[i-1] <= d[i-3] 4 Apply to Input i=3: d[3]=2 >= d[1]=1 d[2]=1 <= d[0]=2 i=3: Check conditions 2 >= 1 --> TRUE 1 <= 2 --> TRUE CROSSING DETECTED! FINAL RESULT Output: true Path crosses itself! OK Key Insight: Self-crossing can only happen in 3 specific patterns. Pattern 1: Line i crosses line i-3 when d[i] >= d[i-2] AND d[i-1] <= d[i-3]. This O(n) approach checks each position once, avoiding the O(n^2) brute force comparison of all line segments. TutorialsPoint - Self Crossing | Optimized 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