Problem 1496

Abstract / Summary

A person walks on a grid from the origin following instructions and we check if their path crosses itself.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1496.py

class Solution:
    def isPathCrossing(self, path: str) -> bool:
        # (x, y) offsets
        direction = { "N": (0, -1), "S": (0, +1), "W": (-1, 0), "E": (+1, 0) }

        # convert 2D to 1D for faster lookup
        norm = lambda x, y: (x * 100000) + y # abs(x) <= 10^4

        x = y = 0
        seen = set([ norm(x, y) ])
        for p in path:
            x += direction[p][0]
            y += direction[p][1]
            n  = norm(x, y)
            if n in seen:
                return True
            seen.add(n)

        return False
19 lines | 567 bytes | submitted December 12, 2023 | GitHub   21% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (300k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether a walking path, described by a string of cardinal directions, ever revisits a previously occupied coordinate. It treats the path as a sequence of moves on a two-dimensional grid, starting at the origin (0, 0). By tracking each visited point, the algorithm can immediately report a crossing as soon as a duplicate location is encountered.

Key Steps

The core logic is organized around a small set of data structures and a single loop that processes the input string character by character.

direction = { "N": (0, -1), "S": (0, +1), "W": (-1, 0), "E": (+1, 0) }

A dictionary maps each direction symbol to its corresponding offset in the Cartesian plane. The choice of using a dictionary enables constant-time lookup for the delta values associated with each step.

norm = lambda x, y: (x * 100000) + y

A lambda expression compresses a two-dimensional coordinate into a single integer. Multiplying the x-coordinate by a large constant (100 000) guarantees that distinct (x, y) pairs map to distinct integers, given the problem’s bound on coordinate magnitude (|x| ≤ 10⁴). This transformation allows the algorithm to store and query positions in a plain Python set without needing tuple hashing.

x = y = 0
seen = set([ norm(x, y) ])

The starting point is encoded with the norm function and placed into a set named seen. The set serves as the repository of all locations visited so far.

for p in path:
    x += direction[p][0]
    y += direction[p][1]
    n  = norm(x, y)
    if n in seen:
        return True
    seen.add(n)

The loop iterates over each character p in the input string path. For each step, the algorithm updates the current coordinates by adding the appropriate offset from the direction map. The new coordinate is normalized to a single integer n. A membership test checks whether n already exists in seen. If it does, a crossing has been detected and the function returns True. Otherwise, the new location is added to the set and the loop proceeds.

return False

If the loop completes without finding any duplicate location, the function concludes that the path never crosses itself and returns False.

Edge Cases

The code gracefully handles an empty path string. In that scenario, the loop body never executes, and the function returns False, correctly indicating that no crossing occurs when no movement is made.

When the path consists of a single direction character, the algorithm updates the coordinates once, adds the new location to seen, and then exits the loop. Since the starting point and the single step are distinct, the function returns False, reflecting the absence of a crossing.

The normalization function is designed to avoid collisions even when negative coordinates are involved. By scaling the x-coordinate with a sufficiently large positive factor before adding the y-coordinate, the mapping remains injective across the entire range of possible positions, including those in the negative quadrants.

If the input contains repeated direction characters that lead back to the origin (for example, "NS" or "EW"), the algorithm will detect the revisit because the normalized value for (0, 0) will already be present in seen. The early return ensures that the crossing is reported at the exact moment it occurs.

Performance Optimizations

The most notable optimization is the conversion of a two-dimensional point into a single integer using the norm lambda. This approach sidesteps the overhead of storing tuples in the set and leverages the fact that integer hashing in Python is faster than tuple hashing. By guaranteeing uniqueness through a large scaling factor, the algorithm retains correctness while benefiting from quicker membership checks and insertions.

Using a dictionary for direction offsets provides O(1) access to the delta values, eliminating the need for conditional branches or multiple if-else statements. This contributes to a tight inner loop where each iteration performs a constant amount of work: a dictionary lookup, two integer additions, a normalization multiplication, a set membership test, and a possible insertion.

The early exit on detection of a crossing prevents unnecessary processing of the remaining characters in the path. As soon as a duplicate location is found, the function returns immediately, which can dramatically reduce runtime for paths that cross early.

Finally, initializing the seen set with the normalized starting point ensures that the first move can be checked against the origin without a special-case condition inside the loop. This uniform handling simplifies the logic and avoids extra conditional checks.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a little robot moving on a giant piece of grid paper. The robot starts right in the middle at a spot called zero, zero. This code helps the robot figure out if it ever walks over a square that it has already visited before.

First, there is a list of directions telling the robot which way to step when it sees a letter like north, south, east, or west. Every time the robot moves, it changes its position on the grid. Because the grid is so big, the code uses a special trick to give every single square a secret name made of a long number.

The robot keeps a magical backpack called a set. Whenever it moves to a new square, it looks inside this backpack. Before taking a step, it checks the new square to see if that spot is already written down inside the backpack. If the spot is already in there, the robot knows it has crossed its own path. If the spot is new, the robot writes it down in the backpack and keeps moving to the next command. The loop keeps going until the robot runs out of instructions.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.00 | σ = 1.15

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim JS
fartem Ruby
FelixFan1122 C#
fpdjsns C++
fsq C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim JavaScript
fartem Ruby
FelixFan1122 C#
fpdjsns C++
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
30 links | 21 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

17 solutions   December 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality