Skip to content

1662. Check If Two String Arrays are Equivalent 👍

  • Time: $O(|\texttt{word1}| + |\texttt{word2}|)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  bool arrayStringsAreEqual(std::vector<std::string>& word1,
                            std::vector<std::string>& word2) {
    int i = 0;  // word1's index
    int j = 0;  // word2's index
    int a = 0;  // word1[i]'s index
    int b = 0;  // word2[j]'s index

    while (i < word1.size() && j < word2.size()) {
      if (word1[i][a] != word2[j][b])
        return false;
      if (++a == word1[i].size()) {
        ++i;
        a = 0;
      }
      if (++b == word2[j].size()) {
        ++j;
        b = 0;
      }
    }

    return i == word1.size() && j == word2.size();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
    int i = 0; // word1's index
    int j = 0; // word2's index
    int a = 0; // word1[i]'s index
    int b = 0; // word2[j]'s index

    while (i < word1.length && j < word2.length) {
      if (word1[i].charAt(a) != word2[j].charAt(b))
        return false;
      if (++a == word1[i].length()) {
        ++i;
        a = 0;
      }
      if (++b == word2[j].length()) {
        ++j;
        b = 0;
      }
    }

    return i == word1.length && j == word2.length;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
    i = 0  # word1's index
    j = 0  # word2's index
    a = 0  # word1[i]'s index
    b = 0  # word2[j]'s index

    while i < len(word1) and j < len(word2):
      if word1[i][a] != word2[j][b]:
        return False
      a += 1
      if a == len(word1[i]):
        i += 1
        a = 0
      b += 1
      if b == len(word2[j]):
        j += 1
        b = 0

    return i == len(word1) and j == len(word2)