Check If String Is a Prefix of Array — LeetCode 1961 Python Solution

EasyArrayTwo PointersString
Problem
#1961
Reading time
2 min

The 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.

Example

Input
s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output
true
Explanation
s can be made by concatenating "i", "love", and "leetcode" together.

Python solution

Python
class Solution:
    def isPrefixString(self, s: str, words: List[str]) -> bool:
        n, m = len(s), 0
        for i, w in enumerate(words):
            m += len(w)
            if m == n:
                return "".join(words[: i + 1]) == s
        return False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1961. Check If String Is a Prefix of Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1961. Check If String Is a Prefix of Array?
LeetCode 1961. Check If String Is a Prefix of Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 1961. Check If String Is a Prefix of Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1961. Check If String Is a Prefix of Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1961. Check If String Is a Prefix of Array cover?
LeetCode 1961. Check If String Is a Prefix of Array is tagged Array, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview