#335

Self Crossing

Hard
ArrayMathGeometryGeometric properties of movementsArray manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages geometric properties to determine if the path crosses itself without explicitly tracking all visited points. By analyzing the movement pattern, we can identify crossing conditions based on the last few movements.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the path crosses based on the last four movements.
  2. 2Step 2: For each distance, update the current position and check if it crosses the previous segments.
  3. 3Step 3: Return true if any crossing condition is met, otherwise return false.
solution.py14 lines
1# Full working Python code
2
3def isSelfCrossing(distance):
4    n = len(distance)
5    if n < 4:
6        return False
7    for i in range(3, n):
8        if distance[i] >= distance[i - 2] and distance[i - 1] <= distance[i - 3]:
9            return True
10        if i >= 4 and distance[i - 1] == distance[i - 3] and distance[i] + distance[i - 4] >= distance[i - 2]:
11            return True
12        if i >= 5 and distance[i - 2] >= distance[i - 4] and distance[i] + distance[i - 4] >= distance[i - 2] and distance[i - 1] + distance[i - 3] >= distance[i - 1]:
13            return True
14    return False

Complexity note: The time complexity is O(n) because we only traverse the distance array once, checking conditions based on the last few movements, leading to linear growth in time complexity.

  • 1The path crosses itself if any of the last four segments intersect with previous segments.
  • 2Understanding the geometric properties of the movements helps in deriving conditions for crossings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.