Solution: Self Crossing

Let’s solve the Self Crossing problem using the Math and Geometry pattern.

Statement

You are given an array of integers, distance, where each element represents the length of a move you will make on an X-Y plane. You start at the origin, which is point (0,0)(0, 0), and move according to the array. Specifically, you move distance[0] meters north, distance[1] meters west, distance[2] meters south, distance[3] meters east, and continue this pattern in a counterclockwise direction. Each step follows the sequence—north, west, south, east—repeating as long as there are remaining distances in the array.

Your task is to determine whether this path crosses itself at any point. This means checking whether you revisit any previously visited position (including the origin or any other point) at any step. Return TRUE if the path intersects itself, and FALSE otherwise.

Constraints:

  • 1 \leq distance.length \leq 10310^3

  • 1 \leq distance[i] \leq 10310^3

Solution

The essence of this solution lies in recognizing the geometric patterns formed when a path moves sequentially in a structured, counterclockwise manner—north, west, south, and east. This problem follows the math and geometry coding pattern, where mathematical conditions detect self-crossings based on movement distances alone rather than explicitly tracking coordinates.

Instead of maintaining a coordinate system, we analyze movement distances and use mathematical comparisons to determine if the path intersects itself. The key insight is that self crossing occurs when a new line overlaps or intersects a previous one. By iterating through the distance list, we identify specific conditions used to dynamically handle any path length effectively. This approach ensures scalability and optimal efficiency.

Specifically, there are three primary cases where self crossing might initially occur, each described below.

Note: While these cases describe initial intersections involving the 4th, 5th, and 6th lines explicitly, the conditions themselves are dynamically applied at every subsequent step for longer paths:

  • Fourth line crosses the first: This scenario occurs when the current step (distance[i]) crosses over the line from two steps before (distance[i - 2]), and the previous step (distance[i -1]) is less than or equal to the distance of three steps back (distance[i - 3]).

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.