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
Path Crossing - Hash Set Approach INPUT E W N S Start Cross! path = "NEESW" N E E S W Start: origin (0, 0) Walk path, check crossing ALGORITHM STEPS 1 Initialize HashSet visited = {(0,0)} pos = (0, 0) 2 Process Each Move N: y++ | S: y-- E: x++ | W: x-- 3 Check HashSet If pos in visited: return TRUE (cross!) 4 Add to HashSet visited.add(pos) Continue to next move Trace: visited set growth Init: {(0,0)} N: {(0,0),(0,1)} E,E,S: add (1,1),(2,1),(2,0) W: (1,0) found! CROSS FINAL RESULT Start Crossing! (1,0) Final HashSet: {(0,0), (0,1), (1,1), (2,1), (2,0)} Output: true Path crosses at (1,0) Position visited twice! Key Insight: Use a HashSet to store visited coordinates as (x, y) pairs. For each move, update position and check if it exists in the set. HashSet provides O(1) lookup, making total time complexity O(n). Space: O(n) for storing up to n unique positions. Simple direction mapping: N/S affect y, E/W affect x. TutorialsPoint - Path Crossing | Hash Set Optimization
Asked in
Google 15 Microsoft 12
23.4K Views
Medium Frequency
~8 min Avg. Time
845 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