You are given a string path
, where path[i]
is the iᵗʰ
direction that you will move. The direction can be:
Starting from the origin (0, 0), return True
if the path crosses itself at any point, i.e., if any point in the path has been visited more than once, and False
otherwise.
Example:
path
?1 <= path.length <= 10^4
True
if the path crosses itself, otherwise False
.(0, 0)
.path
, we will move according to the direction characters and update our current position.True
; otherwise, continue and add the new position to the set.False
.O(n)
, where n
is the length of the string path
, since we are processing each character exactly once.def isPathCrossing(path: str) -> bool:
# Initial position
x, y = 0, 0
# Set to keep track of visited positions
visited = set()
visited.add((x, y))
# Mapping directions to (dx, dy)
move = {
'N': (0, 1),
'S': (0, -1),
'E': (1, 0),
'W': (-1, 0)
}
# Process each step in the path
for direction in path:
dx, dy = move[direction]
x += dx
y += dy
if (x, y) in visited:
return True
visited.add((x, y))
return False
# Example usages
print(isPathCrossing("NES")) # Output: False
print(isPathCrossing("NESWW")) # Output: True
This code will effectively track the path and determine if there is any crossing by checking for repeated coordinates.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?