Leetcode 2937: Make Three Strings Equal

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

You are given three strings: s1, s2, and s3. In each operation, you can choose one of these strings and remove its rightmost character. The goal is to determine the minimum number of operations required to make all three strings identical. If it’s impossible to make them equal, return -1.
Problem
Approach
Steps
Complexity
Input: You are given three strings, s1, s2, and s3.
Example: s1 = 'hello', s2 = 'heco', s3 = 'heo'
Constraints:
• 1 <= s1.length, s2.length, s3.length <= 100
• s1, s2, and s3 consist only of lowercase English letters.
Output: Return the minimum number of operations required to make all strings equal, or -1 if it is impossible.
Example: For s1 = 'hello', s2 = 'heco', s3 = 'heo', the output is 2.
Constraints:
Goal: The goal is to find the minimum number of operations to make the strings identical by removing the rightmost character from one of the strings in each operation.
Steps:
• Start by comparing the longest common prefix among the three strings.
• For each common prefix, calculate how many characters need to be removed from each string to make them equal to the prefix.
• Return the smallest number of operations or -1 if no common prefix exists.
Goal: The strings are non-empty and consist of lowercase English letters.
Steps:
• 1 <= s1.length, s2.length, s3.length <= 100
• s1, s2, and s3 consist only of lowercase English letters.
Assumptions:
• The strings contain only lowercase English letters.
• Strings will not be empty.
Input: s1 = 'hello', s2 = 'heco', s3 = 'heo'
Explanation: By removing the rightmost character from both s1 and s2, all three strings become 'he'. Therefore, it takes 2 operations to make them equal.

Input: s1 = 'cat', s2 = 'dog', s3 = 'bat'
Explanation: The strings cannot be made equal because the first characters are different, so the answer is -1.

Link to LeetCode Lab


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