Skip to content
Problem 335 · LeetCode 335(opens in a new tab)

Self Crossing

HardArrays

You start at the point (0, 0). You walk distance[0] units north, then distance[1] west, then distance[2] south, then distance[3] east, and keep turning left in that order for every value in distance.

Return true if the path ever touches or crosses a part of itself, and false if it never does.

Example 1

Input:  distance = [3, 2, 2, 3]
Output: true
Why:    the east move passes through (0, 1), on the first move
2 more examples and the constraints

Example 2

Input:  distance = [2, 3, 4, 5]
Output: false
Why:    each move is longer, so the path spirals outward

Example 3

Input:  distance = [1, 1, 2, 2, 1, 1]
Output: true
Why:    the last move ends back at (0, 0)

Constraints

  • 1 ≤ distance.length ≤ 100,000
  • 1 ≤ distance[i] ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every earlier segmentO(n²)
  2. Three local casesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeChecks for 100,000 movesVerdict
Every earlier segmentO(n²)
Too slow for long paths
Three local casesO(n)
Best; three checks per move

n = number of moves.

Edge cases to test

  • Fewer than four moves. [1], [1, 1] and [1, 1, 1] never cross; the loop does not run.
  • Touching counts. [1, 1, 1, 1] ends exactly on the start point, which counts as crossing.
  • Lined-up moves. [1, 2, 2, 2, 1] runs straight up into the start along the same line: case 2.
  • Grow, then shrink. A path can spiral out and then back in without crossing, as long as each inward move stays inside the last lines.

Common mistakes

  • Checking only case 1, which misses touching head-on (case 2) and the inward spiral that hits 5 back (case 3).
  • Using > instead of ≥; touching at a single point already counts.
  • Comparing a segment with the one just before it, which always shares a corner and gives a false crossing.

How to talk through it

  1. 1Clarify. Does touching count as crossing? The directions always go north, west, south, east?
  2. 2Start with geometry. Store segments as boxes and test overlap with each earlier one: O(n²).
  3. 3Use the left turns. The path is a spiral, so a new move can only reach the lines 3, 4 or 5 back.
  4. 4Name the cases. Write the length condition for each one with a small drawing.
  5. 5Test out loud. Try [1, 1, 1, 1], [1, 2, 2, 2, 1] and [1, 1, 2, 2, 1, 1], one for each case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?