Path Crossing

Given a string `path` where `path[i]` is 'N', 'S', 'E' or 'W', each moving one unit north, south, east or west, you start at the origin (0, 0) and walk the path. Return true if the path crosses itself at any point, that is, if you ever stand on a location you have already visited. Return false otherwise.

30:00

Path Crossing
easy
Free written solution
Topics
Companies

Given a string path where path[i] is 'N', 'S', 'E' or 'W', each moving one unit north, south, east or west, you start at the origin (0, 0) and walk the path. Return true if the path crosses itself at any point, that is, if you ever stand on a location you have already visited. Return false otherwise.

Example 1:
Input: {"path":"NES"}
Output: false
Constraints:
  • 1 <= path.length <= 10^4

  • path[i] is either 'N', 'S', 'E' or 'W'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"path":"NES"}

Start at (0, 0) and put it in the visited set. The path crosses itself the moment a step lands on a point that is already in the set.

path

N↑
E→
S↓

walk on the grid

visited point

walker

revisited point

origin

position

(0, 0)

moves walked

0 / 3

visited set size

1

Variables
VariableValue
x0
y0
visited1
DepthFunction Call
Stack empty
0/7