Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Replace Question Marks in String to Minimize Its Value

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3081" 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 a string s. s[i] is either a lowercase English letter or '?'. For a string t having length m containing only lowercase English letters, we define the function cost(i) for an index i as the number of characters equal to t[i] that appeared before it, i.e. in the range [0, i - 1]. The value of t is the sum of cost(i) for all indices i. For example, for the string t = "aab": cost(0) = 0 cost(1) = 1 cost(2) = 0 Hence, the value of "aab" is 0 + 1 + 0 = 1. Your task is to replace all occurrences of '?' in s with any lowercase English letter so that the value of s is minimized. Return a string denoting the modified string with replaced occurrences of '?'. If there are multiple strings resulting in the minimum value, return the lexicographically smallest one. Example 1: Input: s = "???" Output: "abc" Explanation: In this example, we can replace the occurrences of '?' to make s equal to "abc". For "abc", cost(0) = 0, cost(1) = 0, and cost(2) = 0. The value of "abc" is 0. Some other modifications of s that have a value of 0 are "cba", "abz", and, "hey". Among all of them, we choose the lexicographically smallest. Example 2: Input: s = "a?a?" Output: "abac" Explanation: In this example, the occurrences of '?' can be replaced to make s equal to "abac". For "abac", cost(0) = 0, cost(1) = 0, cost(2) = 1, and cost(3) = 0. The value of "abac" is 1. Constraints: 1 <= s.length <= 105 s[i] is either a lowercase English letter or '?'.

Explanation

Here's the solution:

  • Greedy Replacement: Iterate through the string s. Whenever a '?' is encountered, replace it with the smallest lexicographical character ('a', 'b', 'c', ...) that minimizes the cost(i) at that position. This greedy approach ensures the overall value is minimized and favors lexicographically smaller results.
  • Cost Calculation: For each '?', iterate through the possible replacements ('a' to 'z') and calculate the cost incurred if that replacement were used. Choose the replacement that results in the minimum cost.
  • Lexicographical Tiebreaker: If multiple characters result in the same minimum cost, choose the lexicographically smallest one.

  • Runtime Complexity: O(N * 26), where N is the length of the string s. This is because for each '?' we iterate up to 26 characters ('a' to 'z'). Storage Complexity: O(1). The solution uses a constant amount of extra space.

Code

    def minimize_string_value(s: str) -> str:
    """
    Replaces '?' in the given string s with lowercase English letters to minimize the string's value.

    Args:
        s: The input string containing lowercase English letters and '?'.

    Returns:
        The modified string with '?' replaced to minimize the value and be lexicographically smallest.
    """

    s_list = list(s)
    for i in range(len(s_list)):
        if s_list[i] == '?':
            min_cost = float('inf')
            best_char = ''
            for char_code in range(ord('a'), ord('z') + 1):
                char = chr(char_code)
                cost = 0
                for j in range(i):
                    if s_list[j] == char:
                        cost += 1

                if cost < min_cost:
                    min_cost = cost
                    best_char = char
                elif cost == min_cost and char < best_char:
                    best_char = char
            s_list[i] = best_char

    return "".join(s_list)

More from this blog

C

Chatmagic blog

2894 posts