Skip to content

2840. Check if Strings Can be Made Equal With Operations II 👍

  • Time: $O(n)$
  • Space: $O(2 \cdot 26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool checkStrings(string s1, string s2) {
    vector<vector<int>> count(2, vector<int>(26));

    for (int i = 0; i < s1.length(); ++i) {
      ++count[i % 2][s1[i] - 'a'];
      --count[i % 2][s2[i] - 'a'];
    }

    for (int i = 0; i < 26; ++i)
      if (count[0][i] > 0 || count[1][i] > 0)
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean checkStrings(String s1, String s2) {
    int[][] count = new int[2][26];

    for (int i = 0; i < s1.length(); ++i) {
      ++count[i % 2][s1.charAt(i) - 'a'];
      --count[i % 2][s2.charAt(i) - 'a'];
    }

    for (int i = 0; i < 26; ++i)
      if (count[0][i] > 0 || count[1][i] > 0)
        return false;

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def checkStrings(self, s1: str, s2: str) -> bool:
    count = [collections.Counter() for _ in range(2)]

    for i, (a, b) in enumerate(zip(s1, s2)):
      count[i % 2][a] += 1
      count[i % 2][b] -= 1

    return (all(freq == 0 for freq in count[0].values()) and
            all(freq == 0 for freq in count[1].values()))