Decremental String Concatenation - Problem
You are given a 0-indexed array words containing n strings.
Let's define a join operation join(x, y) between two strings x and y as concatenating them into xy. However, if the last character of x is equal to the first character of y, one of them is deleted.
For example: join("ab", "ba") = "aba" and join("ab", "cde") = "abcde".
You are to perform n - 1 join operations. Let str0 = words[0]. Starting from i = 1 up to i = n - 1, for the ith operation, you can do one of the following:
- Make
stri = join(stri - 1, words[i]) - Make
stri = join(words[i], stri - 1)
Your task is to minimize the length of strn - 1.
Return an integer denoting the minimum possible length of strn - 1.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["aa", "ab", "bc"]
›
Output:
4
💡 Note:
Join "aa" + "ab" = "aab" (no overlap), then "aab" + "bc" = "aabc" (b matches, one deleted) = length 4. Alternative: "aa" + "bc" + "ab" would give length 6, so 4 is optimal.
Example 2 — With Overlap
$
Input:
words = ["ab", "ba"]
›
Output:
3
💡 Note:
join("ab", "ba") = "aba" because last char of "ab" (b) equals first char of "ba" (b), so one is deleted. Length = 3.
Example 3 — No Overlap
$
Input:
words = ["abc", "def"]
›
Output:
6
💡 Note:
No characters match, so join("abc", "def") = "abcdef" with length 6. Order doesn't matter here.
Constraints
- 2 ≤ words.length ≤ 10
- 1 ≤ words[i].length ≤ 50
- words[i] consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of strings to join optimally
2
Join Process
Try both orders, save character if boundaries match
3
Output
Minimum possible length after all joins
Key Takeaway
🎯 Key Insight: Use DP to track optimal joins by monitoring string boundaries (first/last chars)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code