Path Crossing - Problem

Imagine you're a robot starting at the origin (0, 0) on a 2D coordinate plane. You receive a sequence of movement commands as a string, where each character represents a direction:

  • 'N' - Move one unit North (y + 1)
  • 'S' - Move one unit South (y - 1)
  • 'E' - Move one unit East (x + 1)
  • 'W' - Move one unit West (x - 1)

Your task is to determine if the robot's path crosses itself at any point. In other words, return true if the robot visits any coordinate it has previously been to, and false otherwise.

Example: If the path is "NESWW", the robot moves North to (0,1), East to (1,1), South to (1,0), West to (0,0), and West again to (-1,0). Since it revisits (0,0), the answer is true.

Input & Output

example_1.py โ€” Basic Path Crossing
$ Input: path = "NES"
โ€บ Output: false
๐Ÿ’ก Note: The robot moves North to (0,1), East to (1,1), then South to (1,0). All positions are unique, so no crossing occurs.
example_2.py โ€” Path Returns to Origin
$ Input: path = "NESWW"
โ€บ Output: true
๐Ÿ’ก Note: The robot moves North to (0,1), East to (1,1), South to (1,0), West to (0,0) - returning to the starting position, then West to (-1,0). Since it revisits (0,0), the path crosses itself.
example_3.py โ€” Single Character Path
$ Input: path = "N"
โ€บ Output: false
๐Ÿ’ก Note: The robot only moves once from (0,0) to (0,1). With only two unique positions, no crossing is possible.

Constraints

  • 1 โ‰ค path.length โ‰ค 104
  • path[i] is either 'N', 'S', 'E', or 'W'
  • The robot starts at the origin (0, 0)

Visualization

Tap to expand
Robot Path Crossing DetectionStart (0,0)E โ†’ (1,0)N โ†’ (1,1)W โ†’ (0,1)S โ†’ (0,0) DUPLICATE!Hash Setโœ“ (0,0)โœ“ (1,0)โœ“ (1,1)โœ“ (0,1)Checking (0,0)...Algorithm Steps1. Start: visited = {(0,0)}2. Move E: check (1,0)3. Move N: check (1,1)4. Move W: check (0,1)5. Move S: (0,0) EXISTS!๐ŸŽฏ Hash set enables O(1) position lookups, making the algorithm O(n) overall
Understanding the Visualization
1
Initialize
Robot starts at origin (0,0) and marks this position
2
Move
Robot moves based on command and calculates new position
3
Check
Look up if this position was visited before using hash set
4
Decision
If position exists, return true; otherwise, add to set and continue
Key Takeaway
๐ŸŽฏ Key Insight: Hash sets provide constant-time lookups, transforming an O(nยฒ) brute force problem into an optimal O(n) solution by eliminating the need to check all previous positions.
Asked in
Google 35 Amazon 28 Apple 22 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen