LeetCode 1496: Path Crossing Solution
Master LeetCode problem 1496 (Path Crossing), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1496. Path Crossing
Problem Explanation
Explanation
To solve this problem, we can keep track of the visited points in a set. We start at the origin (0,0) and iterate over each direction specified in the path. For each direction, we move one unit in that direction and add the current point to the set of visited points. If at any point, we reach a point that is already in the set, we return true indicating that the path crosses itself. If we complete the path traversal without crossing ourselves, we return false.
- Time complexity: O(n) where n is the length of the path string
- Space complexity: O(n) to store the visited points
Solution Code
class Solution {
public boolean isPathCrossing(String path) {
Set<String> visited = new HashSet<>();
visited.add("0,0");
int x = 0, y = 0;
for(char direction : path.toCharArray()) {
if(direction == 'N') y++;
else if(direction == 'S') y--;
else if(direction == 'E') x++;
else if(direction == 'W') x--;
String point = x + "," + y;
if(visited.contains(point)) return true;
visited.add(point);
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1496 (Path Crossing)?
This page provides optimized solutions for LeetCode problem 1496 (Path Crossing) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1496 (Path Crossing)?
The time complexity for LeetCode 1496 (Path Crossing) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1496 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1496 in Java, C++, or Python.