Path Crossing - Problem
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.
Input & Output
Example 1 — Path Crosses Itself
$
Input:
path = "NEESW"
›
Output:
false
💡 Note:
Start at (0,0). Move N→(0,1), E→(1,1), E→(2,1), S→(2,0), W→(1,0). All positions are unique, so the path does not cross itself.
Example 2 — Simple Loop
$
Input:
path = "NEEWS"
›
Output:
true
💡 Note:
Start at (0,0)→N to (0,1)→E to (1,1)→E to (2,1)→W to (1,1)→S to (1,0). After W, we return to (1,1) which we visited before.
Example 3 — No Crossing
$
Input:
path = "NES"
›
Output:
false
💡 Note:
Start at (0,0)→N to (0,1)→E to (1,1)→S to (1,0). All positions are unique: (0,0), (0,1), (1,1), (1,0).
Constraints
- 1 ≤ path.length ≤ 104
- path[i] is either 'N', 'S', 'E', or 'W'
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code