Leetcode 1496: Path Crossing

grid47
grid47
Exploring patterns and algorithms
Jun 10, 2024 5 min read

You are given a string path where each character represents a movement direction (‘N’ for north, ‘S’ for south, ‘E’ for east, ‘W’ for west). Starting from the origin (0, 0), follow the path and check if you cross your own path at any point, meaning visiting a location more than once. Return true if the path crosses itself, and false otherwise.
Problem
Approach
Steps
Complexity
Input: The input is a string path consisting of 'N', 'S', 'E', and 'W', where each character represents a movement direction.
Example: path = "NEWS"
Constraints:
• 1 <= path.length <= 10^4
• path[i] is one of 'N', 'S', 'E', 'W'.
Output: Return true if the path crosses itself, meaning you visit a location you have already been to. Otherwise, return false.
Example: Output: false
Constraints:
• The path will contain at least one character.
Goal: The goal is to track the movements and check if any position is visited more than once using a set data structure.
Steps:
• Initialize a set to store visited coordinates.
• Iterate through the characters in the path, updating the current position based on the direction.
• If the current position has been visited before, return true.
• If the loop finishes without revisiting a position, return false.
Goal: The length of the path is between 1 and 10^4. The path consists of the characters 'N', 'S', 'E', and 'W'.
Steps:
• 1 <= path.length <= 10^4
• path[i] is either 'N', 'S', 'E', or 'W'.
Assumptions:
• The path consists of valid directions only.
Input: path = "NEWS"
Explanation: The path starts at the origin, moves north, then east, then west, and finally south, visiting no location twice, so it does not cross itself.

Input: path = "NESWN"
Explanation: After moving north, east, south, west, and then north again, the path revisits the origin, so it crosses itself.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus