Check if Strings Can be Made Equal With Operations II - Problem

You are given two strings s1 and s2, both of length n, consisting of lowercase English letters.

You can apply the following operation on any of the two strings any number of times:

Choose any two indices i and j such that i < j and the difference j - i is even, then swap the two characters at those indices in the string.

Return true if you can make the strings s1 and s2 equal, and false otherwise.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "abc", s2 = "bac"
Output: true
💡 Note: We can swap s1[0] and s1[2] (distance 2 is even) to get "cba", then swap s1[1] and s1[2] (distance 1 is odd, so this won't work). Actually, let's check frequencies: Even positions - s1: 'a','c' vs s2: 'b','c'. They don't match, so this should be false.
Example 2 — Same Characters Different Order
$ Input: s1 = "abcde", s2 = "caebd"
Output: false
💡 Note: Even positions: s1 has 'a','c','e' vs s2 has 'c','e','d'. Different frequencies, so impossible to make equal.
Example 3 — Already Equal
$ Input: s1 = "abc", s2 = "abc"
Output: true
💡 Note: Strings are already equal, so no operations needed.

Constraints

  • 1 ≤ n ≤ 105
  • s1.length == s2.length == n
  • s1 and s2 consist only of lowercase English letters

Visualization

Tap to expand
String Equality with Even-Distance SwapsCan swap positions i,j only if (j-i) is evenabcde01234Even positions (0,2,4) can swap among themselvesOdd positions (1,3) can swap among themselvesSolution: Check if character frequencies matchseparately for even and odd positions💡 Key Insight: Position parity is preserved by even-distance swaps
Understanding the Visualization
1
Input
Two strings s1 and s2 of equal length
2
Constraint
Can only swap positions where j-i is even
3
Key Insight
Even and odd positions form separate groups
Key Takeaway
🎯 Key Insight: Even-distance swaps keep even and odd positions separate, so we only need to check character frequency equality within each parity group
Asked in
Google 12 Microsoft 8
12.8K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen