Sponsored
Sponsored
The idea is to use a Set (or a HashSet in some languages) to store each coordinate visited during the path traversal. Starting from (0, 0), each movement updates the coordinates. If the updated coordinates are already in the Set, it means that the path has crossed itself, and we return true. Otherwise, continue until the end of the path and return false.
Time Complexity: O(n), where n is the length of the path, as we iterate through the path once, with O(1) operations for each set lookup.
Space Complexity: O(n), as we store up to n coordinates in the set.
1#include <unordered_set>
2#include <utility>
3
4class Solution {
5public:
6 bool isPathCrossing(string path) {
7 std::unordered_set<std::pair<int,int>, pair_hash> visited;
8 int x = 0, y = 0;
9 visited.insert({x, y});
10
11 for (char direction : path) {
12 if (direction == 'N') {
13 ++y;
14 } else if (direction == 'S') {
15 --y;
16 } else if (direction == 'E') {
17 ++x;
18 } else if (direction == 'W') {
19 --x;
20 }
21
22 if (visited.count({x, y})) {
23 return true;
24 }
25 visited.insert({x, y});
26 }
27 return false;
28 }
29
30private:
31 struct pair_hash {
32 template <class T1, class T2>
33 std::size_t operator () (const std::pair<T1, T2>& pair) const {
34 auto hash1 = std::hash<T1>{}(pair.first);
35 auto hash2 = std::hash<T2>{}(pair.second);
36 return hash1 ^ hash2;
37 }
38 };
39};
This C++ solution uses an unordered_set to track visited coordinates. It includes a custom hash function for a pair of integers since C++ does not provide one by default. Starting at (0, 0), it updates the coordinates for each direction and checks the set to see if the coordinates have been visited. If so, it returns true, else proceeds to the end returning false.
In this approach, we simulate movement on a 2D plane. Starting at the origin (0, 0), the path string is processed character by character to update the current position based on the direction: 'N' increases y, 'S' decreases y, 'E' increases x, and 'W' decreases x. A map or set records visits to each unique position. If a position is visited more than once, the path crosses itself.
Time Complexity: O(n), since every character in the path is processed.
Space Complexity: O(n), as we store coordinates in a set.
1using System;
2using System.Collections.Generic;
public class Solution {
public bool IsPathCrossing(string path) {
var visited = new HashSet<(int, int)>();
int x = 0, y = 0;
visited.Add((x, y));
foreach (char direction in path) {
if (direction == 'N') {
y++;
} else if (direction == 'S') {
y--;
} else if (direction == 'E') {
x++;
} else if (direction == 'W') {
x--;
}
var current = (x, y);
if (visited.Contains(current)) {
return true;
}
visited.Add(current);
}
return false;
}
}
C# solution leverages a HashSet for tracking coordinates using tuple structures, adjusting position per direction and verifying if any are revisited.