LeetCode Entry

1662. Check If Two String Arrays are Equivalent

01.12.2023 easy 2023 kotlin

Two dimensional array equals

1662. Check If Two String Arrays are Equivalent easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/423

Problem TLDR

Two dimensional array equals

Intuition

There is a one-liner that takes O(n) memory: ord1.joinToString("") == word2.joinToString(""). Let’s use two-pointer approach to reduce the memory footprint.

Approach

  • we can iterate with for on a first word, and use the pointer variable for the second

Complexity

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

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

Code


  fun arrayStringsAreEqual(word1: Array<String>, word2: Array<String>): Boolean {
    var i = 0
    var ii = 0
    for (w in word1) for (c in w) {
      if (i >= word2.size) return false
      if (c != word2[i][ii]) return false
      ii++
      if (ii >= word2[i].length) {
        i++
        ii = 0
      }
    }

    return i == word2.size
  }