Problem 1496 (Dec 23)
Question statement:
Given a string $\texttt{path}$, where $\texttt{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 $\texttt{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 $\texttt{false}$ otherwise.
Solution
Main idea:
- Start a new (hash) set $\texttt{pos = [(0,0)]}$
- Go through $\texttt{path}$ and for each new direction, calculuate current position in the 2D grid.
- Check if current position is already in $\texttt{pos}$. If so, return $\texttt{True}$.
- If not, append $\texttt{pos}$ with the current position.
- Return $\texttt{False}$ if end of $\texttt{path}$ is reached.
Code:
1 | def isPathCrossing(self, path: str) -> bool: |
Comments:
Time complexity: O(n).
At the time of submission, the above solution passes leetcode submission cases in 35ms, beats 83.59% of users. It uses 17.2MB of memory, beating 72.13% of users.