#2840

Check if Strings Can be Made Equal With Operations II

Medium
Hash TableStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating permutations, we can leverage the fact that we can only swap characters at even indices with each other and odd indices with each other. Therefore, we need to check if characters at even indices in s1 can match those in s2, and the same for odd indices.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two frequency counters for characters at even indices and odd indices for both strings.
  2. 2Step 2: Compare the frequency counters for even indices of s1 and s2.
  3. 3Step 3: Compare the frequency counters for odd indices of s1 and s2.
  4. 4Step 4: If both frequency counters match, return true; otherwise, return false.
solution.py11 lines
1# Full working Python code
2from collections import Counter
3
4def canMakeEqual(s1, s2):
5    if len(s1) != len(s2):
6        return False
7    even_count_s1 = Counter(s1[i] for i in range(0, len(s1), 2))
8    odd_count_s1 = Counter(s1[i] for i in range(1, len(s1), 2))
9    even_count_s2 = Counter(s2[i] for i in range(0, len(s2), 2))
10    odd_count_s2 = Counter(s2[i] for i in range(1, len(s2), 2))
11    return even_count_s1 == even_count_s2 and odd_count_s1 == odd_count_s2

Complexity note: The time complexity is O(n) because we traverse the strings once to count characters. The space complexity is O(n) due to the storage of frequency counts.

  • 1Characters can only be swapped between even indices and between odd indices.
  • 2To make the strings equal, the frequency of characters at even and odd indices must match.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.