977. Self-Crossing Walk

Hard7.5 points estimatedGeometryMaths3 hints

A cleaning robot starts at the origin of an infinite floor. It walks distance[0] metres north, then distance[1] metres west, then distance[2] south, then distance[3] east, and keeps turning left after each leg in that repeating order (north, west, south, east, north, ...), using the next value of distance each time.

Return true if the path ever crosses or touches itself, including returning to the start or running along an earlier leg, and false otherwise. The ends of two consecutive legs naturally share a corner; that does not count.

Example 1

Input:
distance = [3,4,3,4]
Output:
true
Explanation:

The walk goes up 3, left 4, down 3, right 4: the last leg ends exactly on the starting point, which counts as touching its own path, so the answer is true.

Example 2

Input:
distance = [1,2,3,4,5,6]
Output:
false
Explanation:

Every leg is longer than the one two steps before, so the walk spirals outward and never meets itself: false.

Example 3

Input:
distance = [6,5,4,3,2,1]
Output:
false
Explanation:

Each leg is shorter than the one two steps earlier, so the walk spirals inward without ever touching an earlier leg: false.

Constraints

  • 1 ≤ distance.length ≤ 105
  • 1 ≤ distance[i] ≤ 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…