Path Crossing (LeetCode 1496): Solution and Explanation

Easy
Hash Table
String

Walk a path of N, S, E and W moves from the origin and report whether you ever stand on the same point twice.

Intuition

Crossing yourself means standing on a spot you have stood on before. It does not matter which direction you came from or how long ago it was.

So the only thing to remember is the set of points already visited. Each move changes one coordinate by one, and after it you ask a single question: is this point in the set?

A hash set answers that in constant time, which makes the whole walk linear. The origin must be in the set from the start, because returning to (0, 0) also counts as a crossing.

Approach: Hash set of visited points

  1. Set x = y = 0 and put (0, 0) into a set.
  2. For each character, move one unit: N raises y, S lowers y, E raises x, W lowers x.
  3. If (x, y) is already in the set, return true.
  4. Otherwise add (x, y) to the set and continue.
  5. If every move lands on a new point, return false.

Step-by-step example

path = "NESWW"
  1. Start at (0, 0); the set is {(0,0)}.
  2. N moves to (0, 1), E to (1, 1), S to (1, 0). Each is new and is added.
  3. W moves to (0, 0), which is already in the set.
  4. Return true; the last W never needs to be walked.

Code: Python, Java, C++

1class Solution:
2    def isPathCrossing(self, path: str) -> bool:
3        x = y = 0
4        visited = {(0, 0)}
5        for d in path:
6            if d == 'N':
7                y += 1
8            elif d == 'S':
9                y -= 1
10            elif d == 'E':
11                x += 1
12            else:
13                x -= 1
14            if (x, y) in visited:
15                return True
16            visited.add((x, y))
17        return False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each move does one constant-time set lookup and one insert.

Space

O(n)

In the worst case every move lands on a new point, so the set holds n + 1 points.

Other approaches

Encode points as integers (time O(n), space O(n))

Coordinates stay within [-10^4, 10^4], so store x * 20001 + y (or a string "x,y") instead of a tuple. Same complexity, sometimes faster in languages without tuple hashing.

Brute force (time O(n^2), space O(n))

After each move, compare the new point with every earlier point. Simple, but O(n^2) time.

Common mistakes

  • Forgetting to add the origin to the set before walking. Then "NS" or "NESW" would wrongly return false.
  • Checking only whether the walk ends at the origin. Crossing can happen anywhere: "NEENWS" never returns to (0, 0), yet its last move lands on (1, 1) a second time.
  • Mixing up axes or signs. Pick one convention (N is +y, E is +x) and keep it; crossings do not depend on the orientation as long as it is consistent.

Frequently asked questions

Does touching the origin again count as a crossing?

Yes. The origin is the first visited point, so returning to it is a revisit and the answer is true.

Do I need to check edges, not just points?

No. Every move is exactly one unit along the grid, so two segments can only meet at grid points, and checking points is enough.

Can I stop early?

Yes. Return true as soon as the first repeated point appears; the rest of the path does not matter.

What are the time and space costs?

O(n) time and O(n) space for the visited set.