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 Array INPUT String s: "iloveleetcode" Array words: "i" "love" "leetcode" "apples" [0] [1] [2] [3] Target to match: i love leetcode ALGORITHM STEPS 1 Initialize prefix = "" Start with empty string 2 Concat words[0] prefix = "i" 3 Concat words[1] prefix = "ilove" 4 Concat words[2] prefix = "iloveleetcode" Check: prefix == s ? "iloveleetcode" == "iloveleetcode" MATCH FOUND! k = 3 (first 3 words) FINAL RESULT Output: true s IS a prefix string Concatenation Result: i + love + leetcode = iloveleetcode OK Key Insight: Build the prefix incrementally by concatenating words one by one. After each concatenation, check if prefix equals s. If yes, return true. If prefix becomes longer than s, return false. Time: O(n) where n = length of s | Space: O(n) for building prefix string TutorialsPoint - Check If String Is a Prefix of Array | Optimized - Build and Check Incrementally
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