LeetCode Entry

1496. Path Crossing

23.12.2023 easy 2023 kotlin

Is path string of 'N', 'E', 'W', 'S' crosses

1496. Path Crossing easy blog post substack image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/448

Problem TLDR

Is path string of ‘N’, ‘E’, ‘W’, ‘S’ crosses

Intuition

We can simulate the path and remember visited coordinates

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


  fun isPathCrossing(path: String): Boolean {
    val visited = mutableSetOf(0 to 0)
    var x = 0
    var y = 0
    return !path.all { when (it) {
      'N' -> y++
      'S' -> y--
      'E' -> x++
      else -> x-- }
      visited.add(x to y)
    }
  }