Ctrl K

Does the Robot Cross Its Trail

Hard
A robot stands at (0, 0) on a plane and follows the commands in steps. It first walks steps[0] meters north, then steps[1] west, steps[2] south, steps[3] east, then north again, and so on: after every step it turns left. The robot leaves a trail of segments behind it. Return true if the trail crosses or touches itself anywhere, and false otherwise. Try to solve it in one pass with O(1) extra memory.
Example 1
steps=[3, 1, 1, 2] → True

The path goes (0, 0) → (0, 3) → (−1, 3) → (−1, 2) → (1, 2). The last segment crosses the first one at (0, 2).

Example 2
steps=[2, 2, 3, 3, 4] → False

Each step is longer than the one two steps back, so the path keeps spiralling outwards and never touches itself.

Example 3
steps=[1, 1, 1, 1] → True

The robot walks around a square and returns to (0, 0). Touching an already visited point also counts as crossing.

Constraints
  • 1 ≤ len(steps) ≤ 10⁵
  • 1 ≤ steps[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStars on One Straight Line HardRope Around the Posts HardWater as Many Plants as Possible HardA Depot Close to All Shops HardBest View for a Turning Camera Hard
loading Python…
Input
steps=[3, 1, 1, 2]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.