#2839

Check if Strings Can be Made Equal With Operations I

Easy
StringHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(1)Space O(1)

Instead of generating permutations, we can analyze the positions of characters. The only characters that can swap are at indices 0 and 2, and 1 and 3. We can check if the characters at these positions can match.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the characters at indices 0 and 2 of s1 match with those in s2.
  2. 2Step 2: Check if the characters at indices 1 and 3 of s1 match with those in s2.
  3. 3Step 3: If both conditions are satisfied, return true; otherwise, return false.
solution.py5 lines
1# Full working Python code
2
3def can_make_equal(s1, s2):
4    return (s1[0] == s2[0] and s1[2] == s2[2] and s1[1] == s2[1] and s1[3] == s2[3]) or 
5           (s1[0] == s2[2] and s1[2] == s2[0] and s1[1] == s2[3] and s1[3] == s2[1])

Complexity note: The complexity is O(1) because we are only performing a constant number of comparisons, regardless of string length.

  • 1The only possible swaps are between specific pairs of indices.
  • 2Character frequency must match for the strings to be equal.

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