Leetcode 2840: Check if Strings Can be Made Equal With Operations II

grid47
grid47
Exploring patterns and algorithms
Jan 28, 2024 5 min read

You are given two strings s1 and s2, both of length n, consisting of lowercase English letters. You can perform the following operation on any of the two strings: 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 s1 and s2 equal, and false otherwise.
Problem
Approach
Steps
Complexity
Input: The input consists of two strings, s1 and s2, each containing n lowercase English letters.
Example: s1 = 'aceb', s2 = 'caeb'
Constraints:
• s1 and s2 have the same length n.
• 1 <= n <= 10^5.
• s1 and s2 consist only of lowercase English letters.
Output: Return true if it's possible to make the two strings equal using the described operations, otherwise return false.
Example: true
Constraints:
• The output should be a boolean value indicating whether the strings can be made equal or not.
Goal: The goal is to determine if s1 can be transformed into s2 using the allowed swap operations.
Steps:
• For each character in s1 and s2, group them by their positions modulo 2 (even or odd indexed positions).
• Compare the counts of characters in corresponding groups for s1 and s2.
• If the counts match for both even and odd indexed positions, return true; otherwise, return false.
Goal: The constraints on the input are as follows:
Steps:
• Both s1 and s2 must have the same length n.
• s1 and s2 consist only of lowercase English letters.
• 1 <= n <= 10^5.
Assumptions:
• The problem assumes that swapping characters is the only allowed operation.
• The strings can have repeated characters.
Input: s1 = 'aceb', s2 = 'caeb'
Explanation: We can swap characters at indices 0 and 2 and then swap characters at indices 1 and 3 to make s1 equal to s2.

Input: s1 = 'abe', s2 = 'bea'
Explanation: It's not possible to transform s1 into s2 since there is no valid swap that can achieve this.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus