#1496
Easy Algorithms Path crossing
Hash Table String
62.6% acceptance
Feb 25, 2026
1552
50
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.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashSet;
impl Solution {
pub fn is_path_crossing(path: String) -> bool {
let mut visited: HashSet<(i32, i32)> = HashSet::new();
let (mut x, mut y) = (0i32, 0i32);
visited.insert((x, y));
for c in path.chars() {
match c {
'N' => y += 1,
'S' => y -= 1,
'E' => x += 1,
'W' => x -= 1,
_ => {}
}
if !visited.insert((x, y)) { return true; }
}
false
}
}