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: false
💡 Note: Even positions: s1 has 'a','c' vs s2 has 'b','c'. Different frequencies at even positions, so impossible to make equal.
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
Check if Strings Can be Made Equal II INPUT String s1: a i=0 b i=1 c i=2 String s2: b i=0 a i=1 c i=2 Index Parity Groups: Even (0, 2) a, c Odd (1) b s1 = "abc" s2 = "bac" ALGORITHM STEPS 1 Group by Index Parity Separate even/odd indices 2 Extract Characters Get chars at each group 3 Sort Each Group Sort chars alphabetically 4 Compare Groups Check if sorted match Comparison: s1 even: [a,c] --> [a,c] s2 even: [b,c] --> [b,c] X s1 odd: [b] --> [b] s2 odd: [a] --> [a] X Wait - let me recalculate... FINAL RESULT Correct Grouping: s1: even[0,2]=[a,c] odd[1]=[b] s2: even[0,2]=[b,c] odd[1]=[a] Swap i=0, j=2 in s1 (even diff) After Swap in s1: c b a s1 = "cba" Continue operations... s1 can become "bac" Output: true Strings can be equalized Key Insight: Characters at even indices can only swap with other even indices (diff is even). Characters at odd indices can only swap with other odd indices. Therefore, sort and compare even-indexed chars of both strings, and odd-indexed chars separately. If both match: true. TutorialsPoint - Check if Strings Can be Made Equal With Operations II | Optimal Solution
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