Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Make Three Strings Equal

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2937" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given three strings: s1, s2, and s3. In one operation you can choose one of these strings and delete its rightmost character. Note that you cannot completely empty a string. Return the minimum number of operations required to make the strings equal. If it is impossible to make them equal, return -1. Example 1: Input: s1 = "abc", s2 = "abb", s3 = "ab" Output: 2 Explanation: Deleting the rightmost character from both s1 and s2 will result in three equal strings. Example 2: Input: s1 = "dac", s2 = "bac", s3 = "cac" Output: -1 Explanation: Since the first letters of s1 and s2 differ, they cannot be made equal. Constraints: 1 <= s1.length, s2.length, s3.length <= 100 s1, s2 and s3 consist only of lowercase English letters.

Explanation

Here's the breakdown of the solution:

  • Greedy Approach: Iteratively compare the strings from left to right. If the characters at the current index are the same across all three strings, move to the next index.
  • Handle Mismatch: If a mismatch is found at any index, it's impossible to make the strings equal since we can only delete from the right.
  • Calculate Operations: If all characters match up to a certain length, the number of operations is the sum of the number of characters deleted from each string to reach that length.

  • Runtime Complexity: O(min(len(s1), len(s2), len(s3))) - Linear with respect to the length of the shortest string.

  • Storage Complexity: O(1) - Constant space.

Code

    def minOperations(s1: str, s2: str, s3: str) -> int:
    """
    Given three strings: s1, s2, and s3. In one operation you can choose one of these
    strings and delete its rightmost character. Note that you cannot completely empty
    a string. Return the minimum number of operations required to make the strings
    equal. If it is impossible to make them equal, return -1.
    """
    n1 = len(s1)
    n2 = len(s2)
    n3 = len(s3)

    min_len = min(n1, n2, n3)

    common_len = 0
    for i in range(min_len):
        if s1[i] == s2[i] == s3[i]:
            common_len += 1
        else:
            break

    if common_len == 0:
        return -1

    return n1 - common_len + n2 - common_len + n3 - common_len

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Make Three Strings Equal