Skip to content
← All posts

Check If String Is a Prefix of Array

4 min read
leetcodeproblemeasyarraysstrings

LeetCode 1961, Check If String Is a Prefix of Array, gives you a string s and an array of strings words. You need to determine whether s is a "prefix string" of words. A prefix string is a string formed by concatenating the first k strings of words for some positive k no larger than words.length. Return true if s is a prefix string, or false otherwise.

For example, s = "iloveleetcode" and words = ["i", "love", "leetcode", "apples"]. Concatenating the first three words gives "i" + "love" + "leetcode" = "iloveleetcode", which equals s. So the answer is true.

siloveleetcodewordswords[0]iwords[1]lovewords[2]leetcodewords[3]apples
s = "iloveleetcode". Concatenating words[0..2] gives "i" + "love" + "leetcode" = "iloveleetcode", which matches s. Return true.

Why this problem matters

Even easy problems teach useful patterns. This one reinforces incremental string building and early termination, two ideas that show up constantly in harder problems. You are not searching for a substring or matching a pattern. You are building up a candidate string one piece at a time and checking whether it matches the target at each step.

The simplicity is the point. When you drill a clean pattern on a problem like this, it becomes second nature. Then when you see the same building blocks buried inside a medium or hard problem, you recognize them immediately.

The key insight

You do not need to concatenate all the words first and then compare. Instead, build the concatenation incrementally, one word at a time. After adding each word, check if the running concatenation equals s. If it ever grows longer than s, you can stop early because no future concatenation will shrink it back.

There are exactly three outcomes at each step:

  • The concatenation matches s exactly: return true.
  • The concatenation is longer than s, or a character does not match the prefix of s: return false.
  • The concatenation is shorter than s and still matches the corresponding prefix: keep going.

The solution

def is_prefix_string(s, words):
    concat = ""
    for word in words:
        concat += word
        if concat == s:
            return True
        if len(concat) > len(s):
            return False
    return False

Step-by-step walkthrough

Step 1: Concatenate words[0]

siloveleetcodeconcati

concat = "i". Compare with s: "i" vs "iloveleetcode". It is a prefix of s, but not equal. Keep going.

Step 2: Concatenate words[1]

siloveleetcodeconcatilove

concat = "ilove". Compare with s: "ilove" vs "iloveleetcode". Still a prefix, not yet equal. Keep going.

Step 3: Concatenate words[2]

siloveleetcodeconcatiloveleetcode= s

concat = "iloveleetcode". This equals s exactly. Return true.

In step 1, concatenating just "i" gives a string shorter than s. It matches the first character of s, so we continue. In step 2, "ilove" still matches the corresponding prefix of s but is too short. In step 3, "iloveleetcode" matches s exactly, and we return true.

If s had been "iloveleeco" (ending partway through "leetcode"), the concatenation after three words would be "iloveleetcode", which is longer than s. We would return false because s does not align with any whole-word boundary.

Complexity analysis

ApproachTimeSpace
Incremental concatenationO(n), where n = len(s)O(n) for the concat string

You iterate through words and build up at most len(s) characters. Once the concatenation reaches or exceeds the length of s, you stop. Each character is appended exactly once.

If you want to avoid the O(n) space for building the concatenation string, you can use an index pointer instead. Walk through s character by character, matching against each word in sequence. This brings space down to O(1) while keeping the same O(n) time.

Edge cases

Empty words array. If words is empty, no concatenation can be formed. Return false (unless s is also empty, but the constraints guarantee s has at least one character).

s shorter than the first word. If words[0] is already longer than s, the first concatenation exceeds s immediately. Return false.

Exact match at k = 1. If s equals words[0], the function returns true on the very first iteration.

s matches a prefix of the concatenation but not at a word boundary. For example, s = "il" and words = ["i", "love"]. After words[0], concat = "i" which is too short. After words[1], concat = "ilove" which is too long. The function correctly returns false because "il" does not align with a complete word boundary.

All words concatenated are still shorter than s. The loop exhausts all words without ever matching. The function falls through to return False.

The building blocks

This problem is built on two fundamental techniques.

Incremental string construction

Rather than computing the full concatenation up front, you build it one word at a time. This lets you check intermediate states and bail out early. The same idea applies in problems like Find the Index of the First Occurrence in a String, where you compare partial matches as you slide through the input.

Early termination

The moment the concatenation exceeds the length of s, you know the answer is false. You do not need to process the remaining words. This pattern of "stop as soon as you have enough information" appears everywhere, from binary search to prefix matching to validation problems.

From understanding to recall

You can follow this solution without any trouble. Concatenate words one at a time, check for equality, stop early if it gets too long. But will you write it cleanly from scratch in two weeks? The small details matter: checking len(concat) > len(s) for early exit, returning false at the end if the loop finishes without a match, and recognizing that partial-word matches are always invalid.

Spaced repetition drills these details into long-term memory. You practice writing the solution from scratch at increasing intervals. After a few reps, the incremental build-and-check pattern is automatic. When you encounter a similar "does this sequence build up to a target" problem, the structure is already in your hands.

Related posts