You are given a string path
that describes the movement of a person on a 2D grid. Each character in the string represents a move:
The person starts at the origin (0, 0) on the grid. Return true
if the path crosses itself at any point, that is, if the person visits a grid point more than once and false
otherwise.
false
.(x, y)
to track the current position on the grid.HashSet
to store positions that have been visited.HashSet
. If it is, return true
. If not, add the new position to the HashSet
.false
.import java.util.HashSet;
public class PathCrossing {
public boolean isPathCrossing(String path) {
// Initialize starting point at (0, 0)
int x = 0, y = 0;
// Use a HashSet to track visited coordinates
HashSet<String> visited = new HashSet<>();
visited.add(x + "," + y);
for (char move : path.toCharArray()) {
// Update coordinates based on move
switch (move) {
case 'N' -> y++;
case 'S' -> y--;
case 'E' -> x++;
case 'W' -> x--;
}
// Form a unique string for the current position
String currentPosition = x + "," + y;
// Check if current position is already visited
if (!visited.add(currentPosition)) {
return true; // Path crosses itself
}
}
// No crossing found
return false;
}
public static void main(String[] args) {
PathCrossing solution = new PathCrossing();
// Example test cases
System.out.println(solution.isPathCrossing("NES")); // Output: false
System.out.println(solution.isPathCrossing("NESWW")); // Output: true
}
}
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?