Path Crossing — LeetCode 1496 Python Solution

EasyHash TableString
Problem
#1496
Pattern
Hash Map
Reading time
3 min

The problem

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.

Example

Input
path = "NES"
Output
false
Explanation
Notice that the path doesn't cross any point more than once.

Python solution

Python
class Solution:
    def isPathCrossing(self, path: str) -> bool:
        i = j = 0
        vis = {(0, 0)}
        for c in path:
            match c:
                case 'N':
                    i -= 1
                case 'S':
                    i += 1
                case 'E':
                    j += 1
                case 'W':
                    j -= 1
            if (i, j) in vis:
                return True
            vis.add((i, j))
        return False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1496. Path Crossing is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1496. Path Crossing?
LeetCode 1496. Path Crossing is rated Easy on LeetCode.
What is the time complexity of LeetCode 1496. Path Crossing?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1496. Path Crossing?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1496. Path Crossing cover?
LeetCode 1496. Path Crossing is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview