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
String Prefix Matching VisualizationTarget: "helloworld"helloworldStep 1: Match "hello""hello"index = 5Step 2: Match "world""world"index = 10โœ“ SUCCESS: index == target.length
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.

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track indices, no extra space for string building

n
2n
โœ“ 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
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen