Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings.
Return the minimum number of extra characters left over if you break up s optimally.
Example 1:
Input: s = "leetscode", dictionary = ["leet","code","leetcode"] Output: 1 Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.
Example 2:
Input: s = "sayhelloworld", dictionary = ["hello","world"] Output: 3 Explanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3.
Constraints:
1 <= s.length <= 501 <= dictionary.length <= 501 <= dictionary[i].length <= 50dictionary[i] and s consists of only lowercase English lettersdictionary contains distinct wordsProblem summary: You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings. Return the minimum number of extra characters left over if you break up s optimally.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Trie
"leetscode" ["leet","code","leetcode"]
"sayhelloworld" ["hello","world"]
word-break)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2707: Extra Characters in a String
class Solution {
public int minExtraChar(String s, String[] dictionary) {
Set<String> ss = new HashSet<>();
for (String w : dictionary) {
ss.add(w);
}
int n = s.length();
int[] f = new int[n + 1];
f[0] = 0;
for (int i = 1; i <= n; ++i) {
f[i] = f[i - 1] + 1;
for (int j = 0; j < i; ++j) {
if (ss.contains(s.substring(j, i))) {
f[i] = Math.min(f[i], f[j]);
}
}
}
return f[n];
}
}
// Accepted solution for LeetCode #2707: Extra Characters in a String
func minExtraChar(s string, dictionary []string) int {
ss := map[string]bool{}
for _, w := range dictionary {
ss[w] = true
}
n := len(s)
f := make([]int, n+1)
for i := 1; i <= n; i++ {
f[i] = f[i-1] + 1
for j := 0; j < i; j++ {
if ss[s[j:i]] && f[j] < f[i] {
f[i] = f[j]
}
}
}
return f[n]
}
# Accepted solution for LeetCode #2707: Extra Characters in a String
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
ss = set(dictionary)
n = len(s)
f = [0] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i - 1] + 1
for j in range(i):
if s[j:i] in ss and f[j] < f[i]:
f[i] = f[j]
return f[n]
// Accepted solution for LeetCode #2707: Extra Characters in a String
use std::collections::HashSet;
impl Solution {
pub fn min_extra_char(s: String, dictionary: Vec<String>) -> i32 {
let ss: HashSet<String> = dictionary.into_iter().collect();
let n = s.len();
let mut f = vec![0; n + 1];
for i in 1..=n {
f[i] = f[i - 1] + 1;
for j in 0..i {
if ss.contains(&s[j..i]) {
f[i] = f[i].min(f[j]);
}
}
}
f[n]
}
}
// Accepted solution for LeetCode #2707: Extra Characters in a String
function minExtraChar(s: string, dictionary: string[]): number {
const ss = new Set(dictionary);
const n = s.length;
const f = new Array(n + 1).fill(0);
for (let i = 1; i <= n; ++i) {
f[i] = f[i - 1] + 1;
for (let j = 0; j < i; ++j) {
if (ss.has(s.substring(j, i))) {
f[i] = Math.min(f[i], f[j]);
}
}
}
return f[n];
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.