Self Crossing Problem
Description
LeetCode Problem 335.
You are given an array of integers distance.
You start at 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.
Return true if your path crosses itself, and false if it does not.
Example 1:
Input: distance = [2,1,1,2]
Output: true
Example 2:
Input: distance = [1,2,3,4]
Output: false
Example 3:
Input: distance = [1,1,1,1]
Output: true
Constraints:
- 1 <=distance.length <= 10^5
- 1 <=distance[i] <= 10^5
Solution
Approach: Check the Three Ways to Cross
The path turns left after every move, so a new move i can only run into a few of the moves just before it. Moves i - 1 and i - 2 are attached to it and cannot be hit, and a move older than i - 5 is always shielded by the moves in between. That leaves exactly three cases to check for each i >= 3 (write d for distance):
- Move
icrosses movei - 3. This is the simplest crossing, as in[2,1,1,2]: moveiis at least as long as the parallel movei - 2, and movei - 1is no longer than movei - 3, so the path comes back over it. Condition:d[i] >= d[i-2]andd[i-1] <= d[i-3]. - Move
itouches movei - 4. Whend[i-1] == d[i-3], moveiruns along the same line as movei - 4toward it, as in[1,1,2,1,1]. It reaches it once the two lengths together cover movei - 2. Condition:d[i-1] == d[i-3]andd[i] + d[i-4] >= d[i-2]. - Move
icrosses movei - 5. The path was spiralling outward and now turns inward, so moveicuts back across movei - 5. Condition:d[i-2] >= d[i-4],d[i] + d[i-4] >= d[i-2],d[i-1] <= d[i-3]andd[i-1] + d[i-5] >= d[i-3].
If none of them holds for any i, the path never crosses itself.
The easy mistake is in case 3: all four conditions are needed. Leaving out d[i-2] >= d[i-4], for example, reports a crossing for [3,5,4,3,1,2], a path that is just spiralling inward and never reaches move i - 5.
Complexity: O(n) time, where n is the length of distance, and O(1) space.
class Solution:
def isSelfCrossing(self, distance: List[int]) -> bool:
d = distance
for i in range(3, len(d)):
# Case 1: move i crosses move i - 3 (the fourth move hits the first).
if d[i] >= d[i - 2] and d[i - 1] <= d[i - 3]:
return True
# Case 2: move i exactly meets move i - 4 (the fifth move touches the first).
if i >= 4 and d[i - 1] == d[i - 3] and d[i] + d[i - 4] >= d[i - 2]:
return True
# Case 3: move i crosses move i - 5 (the sixth move hits the first).
if (
i >= 5
and d[i - 2] >= d[i - 4]
and d[i] + d[i - 4] >= d[i - 2]
and d[i - 1] <= d[i - 3]
and d[i - 1] + d[i - 5] >= d[i - 3]
):
return True
return False