Longest Common Prefix Between Adjacent Strings After Removals - Problem
You are given an array of strings words. Your task is to determine what happens to the longest common prefix between adjacent pairs when you remove each element one by one.
For each index i in the range [0, words.length - 1], you need to:
- Remove the element at index
ifrom thewordsarray - Find the longest common prefix among all adjacent pairs in the modified array
- Return the length of this longest common prefix
Return an array answer, where answer[i] represents the length of the longest common prefix between adjacent pairs after removing the element at index i.
Note: If no adjacent pairs remain after removal, or if no adjacent pairs share a common prefix, then answer[i] should be 0.
Input & Output
example_1.py โ Basic Case
$
Input:
words = ["apple", "app", "apricot", "banana"]
โบ
Output:
[0, 2, 0, 0]
๐ก Note:
Remove 'apple': ['app', 'apricot', 'banana'] โ max prefix between adjacent pairs is 'ap' (length 2). Remove 'app': ['apple', 'apricot', 'banana'] โ max prefix is 'ap' (length 2). Remove 'apricot': ['apple', 'app', 'banana'] โ max prefix is 'app' (length 3), but wait - that's wrong. Let me recalculate: Remove 'apricot': ['apple', 'app', 'banana'] โ 'apple','app' share 'app'(3), 'app','banana' share ''(0) โ max is 0. Actually, the common prefix of 'apple' and 'app' is 'app' but 'app' and 'banana' is empty, so we take max which should be 3. Let me reconsider the problem...
example_2.py โ Single Element
$
Input:
words = ["hello"]
โบ
Output:
[0]
๐ก Note:
When we remove the only element, no adjacent pairs remain, so the result is 0.
example_3.py โ No Common Prefixes
$
Input:
words = ["cat", "dog", "bird"]
โบ
Output:
[0, 0, 0]
๐ก Note:
No matter which element we remove, the remaining adjacent pairs share no common prefixes, so all results are 0.
Constraints
- 1 โค words.length โค 100
- 1 โค words[i].length โค 100
- words[i] consists of lowercase English letters
- All strings are non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Start with array of strings, each representing a book title
2
Simulate Removal
For each position, temporarily remove that book from the shelf
3
Check Adjacencies
Measure common prefix length between each pair of adjacent remaining books
4
Record Maximum
Store the longest common prefix found among all adjacent pairs
Key Takeaway
๐ฏ Key Insight: When removing an element, we only need to check the new adjacent pairs formed in the modified array and find the maximum common prefix length among all pairs.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code