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 k no larger than words.length.

Return true if s is a prefix string of words, or false otherwise.

Input & Output

Example 1 — Perfect Match
$ Input: s = "iloveleetcode", words = ["i", "love", "leetcode", "apples"]
Output: true
💡 Note: Concatenating first 3 words: "i" + "love" + "leetcode" = "iloveleetcode" which equals s exactly
Example 2 — No Valid Prefix
$ Input: s = "iloveleetcode", words = ["apples", "i", "love", "leetcode"]
Output: false
💡 Note: First word "apples" doesn't match start of s="iloveleetcode", so no valid prefix exists
Example 3 — Partial Match Only
$ Input: s = "ccccccccc", words = ["c", "cc"]
Output: false
💡 Note: Concatenating all words gives "c" + "cc" = "ccc", but s has length 9, so s cannot be formed as a prefix

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ s.length ≤ 1000
  • 1 ≤ words[i].length ≤ 1000
  • s and words[i] consist of only lowercase English letters

Visualization

Tap to expand
Check If String Is a Prefix of ArrayInput:s = "iloveleetcode"words = ["i", "love", "leetcode", "apples"]Try k=1: "i"≠ "iloveleetcode"Try k=2: "ilove"≠ "iloveleetcode"Try k=3:"iloveleetcode"= "iloveleetcode" ✓Result: trueFound valid prefix at k=3
Understanding the Visualization
1
Input
String s and array of words
2
Process
Try concatenating first k words for each k
3
Output
Return true if any concatenation equals s
Key Takeaway
🎯 Key Insight: A string is a prefix of an array if it exactly matches the concatenation of the first k words for some k
Asked in
Facebook 15 Google 12 Amazon 8
25.4K Views
Medium Frequency
~15 min Avg. Time
890 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