Check If String Is a Prefix of Array - Problem
Given a string s and an array of strings words, determine whether s is a prefix string of words.
A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive integer k (where k โค words.length).
For example, if words = ["hello", "world", "leetcode"], then:
"hello"is a prefix string (k=1)"helloworld"is a prefix string (k=2)"helloworldleetcode"is a prefix string (k=3)"hellow"is NOT a prefix string (partial words not allowed)
Goal: Return true if s is a prefix string of words, or false otherwise.
Input & Output
example_1.py โ Basic Match
$
Input:
s = "iloveleetcode", words = ["i", "love", "leetcode", "apples"]
โบ
Output:
true
๐ก Note:
We can form "iloveleetcode" by concatenating the first 3 words: "i" + "love" + "leetcode" = "iloveleetcode"
example_2.py โ No Match
$
Input:
s = "iloveleetcode", words = ["apples", "i", "love", "leetcode"]
โบ
Output:
false
๐ก Note:
We cannot form "iloveleetcode" starting from "apples". We can only use words from the beginning of the array in order.
example_3.py โ Partial Word Not Allowed
$
Input:
s = "ilove", words = ["i", "love", "leetcode"]
โบ
Output:
true
๐ก Note:
We can form "ilove" by concatenating the first 2 words: "i" + "love" = "ilove". We don't need to use all words.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with an index at position 0 of the target string
2
Check Each Word
For each word, verify it matches the expected portion of target string
3
Advance or Stop
If word matches, advance index; if not, return false
4
Check Completion
If index equals target length exactly, we found a valid prefix
Key Takeaway
๐ฏ Key Insight: We can solve this efficiently in O(n) time by building incrementally and checking for exact matches, avoiding the need to rebuild strings multiple times.
Time & Space Complexity
Time Complexity
O(n)
n is the total number of characters in s. We examine each character at most once.
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track indices, no extra space for string building
โ Linear Space
Constraints
- 1 โค words.length โค 100
- 1 โค words[i].length โค 20
- 1 โค s.length โค 1000
- words[i] and s consist of only lowercase English letters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code