#1496
Path Crossing
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all previous positions, we can use a set to track visited coordinates efficiently. This allows us to check for crossings in constant time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a set to store visited positions, starting with the origin (0, 0).
- 2Step 2: For each direction in the path, update the current position accordingly.
- 3Step 3: After moving, check if the current position is in the set. If yes, return true; otherwise, add it to the set.
solution.py22 lines
1# Full working Python code
2path = "NESWW"
3
4def isPathCrossing(path):
5 visited = set()
6 visited.add((0, 0))
7 x, y = 0, 0
8 for direction in path:
9 if direction == 'N':
10 y += 1
11 elif direction == 'S':
12 y -= 1
13 elif direction == 'E':
14 x += 1
15 elif direction == 'W':
16 x -= 1
17 if (x, y) in visited:
18 return True
19 visited.add((x, y))
20 return False
21
22print(isPathCrossing(path))ℹ
Complexity note: The time complexity is linear because we only traverse the path once, and the space complexity is linear due to storing visited positions in a set.
- 1Using a set allows for O(1) average time complexity for checking previously visited positions.
- 2The problem can be visualized as navigating a grid, where each direction corresponds to a movement on the grid.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.