LeetCode 2839: Check Strings Equal (Easy Explanation + Code)

Problem Summary

You are given two strings s1 and s2, both of length 4.

You can perform the following operation any number of times:

  • Swap characters at indices:
    • 0 ↔ 2
    • 1 ↔ 3

Return true if you can make s1 equal to s2, otherwise false.


🔍 Key Observation

The allowed swaps create two independent groups of indices:

  • Group 1: {0, 2}
  • Group 2: {1, 3}

Within each group, characters can be freely swapped, but cannot move between groups.

👉 That means:

  • Characters at indices {0, 2} in s1 must match those in s2
  • Characters at indices {1, 3} in s1 must match those in s2

💡 Core Idea

Instead of simulating swaps, we:

  1. Compare characters in the same groups
  2. Sort or count them
  3. Check if both groups match between s1 and s2

✅ Approach

Step-by-step:

  1. Extract characters:
    • group1_s1 = [s1[0], s1[2]]
    • group2_s1 = [s1[1], s1[3]]
  2. Do the same for s2
  3. Sort both groups and compare

🧠 Why Sorting Works

Since we can swap freely inside a group, only the multiset (frequency) matters—not order.


🧾 Code Implementation

Python

class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
return (
sorted([s1[0], s1[2]]) == sorted([s2[0], s2[2]]) and
sorted([s1[1], s1[3]]) == sorted([s2[1], s2[3]])
)

Java

class Solution {
public boolean canBeEqual(String s1, String s2) {
char[] g1_s1 = {s1.charAt(0), s1.charAt(2)};
char[] g1_s2 = {s2.charAt(0), s2.charAt(2)};
char[] g2_s1 = {s1.charAt(1), s1.charAt(3)};
char[] g2_s2 = {s2.charAt(1), s2.charAt(3)}; Arrays.sort(g1_s1);
Arrays.sort(g1_s2);
Arrays.sort(g2_s1);
Arrays.sort(g2_s2); return Arrays.equals(g1_s1, g1_s2) && Arrays.equals(g2_s1, g2_s2);
}
}

C++

class Solution {
public:
bool canBeEqual(string s1, string s2) {
vector<char> g1_s1 = {s1[0], s1[2]};
vector<char> g1_s2 = {s2[0], s2[2]};
vector<char> g2_s1 = {s1[1], s1[3]};
vector<char> g2_s2 = {s2[1], s2[3]}; sort(g1_s1.begin(), g1_s1.end());
sort(g1_s2.begin(), g1_s2.end());
sort(g2_s1.begin(), g2_s1.end());
sort(g2_s2.begin(), g2_s2.end()); return g1_s1 == g1_s2 && g2_s1 == g2_s2;
}
};

⏱️ Complexity Analysis

  • Time Complexity: O(1)
    (Only 4 characters → constant work)
  • Space Complexity: O(1)

🧪 Example

Input

s1 = "abcd"
s2 = "cdab"

Explanation

  • Group1: a, c → matches c, a
  • Group2: b, d → matches d, b

✅ Output: true


🚀 Takeaway

This problem is not about simulating swaps—it’s about recognizing index grouping constraints.

Once you see the pattern:

“Swaps only within fixed index sets”

👉 It reduces to a simple group comparison problem.