714321. Add Minimum Characters

Medium

Add Minimum Characters

Summary

Given a string str and an integer k, find the minimum characters that need to be added to str so that all substrings of length k+1 contain at least one character from a given set of characters (e.g., lowercase English letters). The problem involves manipulating strings, which is relevant to the "Strings" topic tag.

Detailed Explanation

To solve this problem, we'll create a prefix tree (also known as a trie) to keep track of the characters in str and their positions. We'll then iterate through all substrings of length k+1 and check if they contain at least one character from the given set.

Here's a step-by-step breakdown:

  1. Create an empty prefix tree.
  2. Iterate through each character c in str.
  3. For each c, add it to the prefix tree as a new node or update its position if it already exists.
  4. Initialize a variable min_chars_needed to store the minimum characters needed.
  5. Iterate through all substrings of length k+1 in str. For each substring, check if it contains at least one character from the given set. If not, increment min_chars_needed.
  6. Return min_chars_needed.

Here's an ASCII art diagram illustrating the prefix tree:

          +---+
       c  |
     +---+---+
    a   b   c
  +-----+-----+
 e   f   g   h
|       |       |
i   j   k   l

Time complexity: O(n), where n is the length of str. Space complexity: O(m), where m is the size of the given set of characters.

Optimized Solutions

Java

View on GeeksforGeeks
public int addMinimumChars(String str, int k) {
    Trie trie = new Trie();
    for (int i = 0; i < str.length(); i++) {
        trie.insert(str.charAt(i), i);
    }
    int minCharsNeeded = 0;
    for (int i = 0; i <= str.length() - k - 1; i++) {
        if (!trie.containsAtLeastOneChar(str.substring(i, i + k + 1))) {
            minCharsNeeded++;
        }
    }
    return minCharsNeeded;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.