#3081

Replace Question Marks in String to Minimize Its Value

Medium
Hash TableStringGreedySortingHeap (Priority Queue)CountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating all combinations, we can replace '?' with the least frequent letters in the string to minimize the cost. This approach is efficient and ensures we get the lexicographically smallest string.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in the string, ignoring '?' characters.
  2. 2Step 2: For each '?', replace it with the character that has the lowest frequency, ensuring that we maintain the lexicographical order.
  3. 3Step 3: Construct the final string with the replacements.
solution.py13 lines
1# Full working Python code
2from collections import Counter
3
4def min_value_string(s):
5    count = Counter(c for c in s if c != '?')
6    result = list(s)
7    for i in range(len(result)):
8        if result[i] == '?':
9            # Find the character with the minimum frequency
10            min_char = min((chr(c) for c in range(ord('a'), ord('z') + 1)), key=lambda x: count[x])
11            result[i] = min_char
12            count[min_char] += 1
13    return ''.join(result)

Complexity note: The complexity is O(n) because we only traverse the string a couple of times: once for counting and once for replacing, making it linear in terms of input size.

  • 1The cost function depends on the frequency of characters, not their order.
  • 2Replacing '?' with the least frequent characters minimizes the overall cost.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.