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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code