Check If String Is a Prefix of Array — LeetCode 1961 Python Solution
- Problem
- #1961
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.