#2707

Extra Characters in a String

Medium
ArrayHash TableStringDynamic ProgrammingTrieDynamic ProgrammingSubstring Search
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)

Using dynamic programming, we can keep track of the minimum extra characters needed to form valid substrings up to each index. This allows us to build on previous results and avoid redundant checks.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a DP array where DP[i] represents the minimum extra characters for the substring s[0:i].
  2. 2Step 2: Initialize DP[0] to 0 (no characters, no extras).
  3. 3Step 3: For each index i, check all substrings ending at i and update DP[i] based on previous DP values.
  4. 4Step 4: If a substring is found in the dictionary, update DP[i] to the minimum of its current value and DP[start] (where start is the beginning of the substring).
  5. 5Step 5: If no valid substring is found, increment the extra count from DP[i-1] by 1.
solution.py10 lines
1def minExtraChars(s, dictionary):
2    word_set = set(dictionary)
3    n = len(s)
4    dp = [0] * (n + 1)
5    for i in range(1, n + 1):
6        dp[i] = dp[i - 1] + 1  # Assume the character is extra
7        for j in range(i):
8            if s[j:i] in word_set:
9                dp[i] = min(dp[i], dp[j])
10    return dp[n]

Complexity note: The time complexity remains O(n²) due to the nested loops for substring checks, but we optimize the process by storing results in a DP array. The space complexity is O(n) for the DP array.

  • 1Dynamic programming helps break down the problem into manageable parts.
  • 2Using a set for the dictionary allows for O(1) average time complexity for lookups.

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