1961. Check If String Is a Prefix of Array LeetCode Solution
In this guide, you will get 1961. Check If String Is a Prefix of Array LeetCode Solution with the best time and space complexity. The solution to Check If String Is a Prefix of Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Check If String Is a Prefix of Array solution in C++
- Check If String Is a Prefix of Array solution in Java
- Check If String Is a Prefix of Array solution in Python
- Additional Resources

Problem Statement of Check If String Is a Prefix of Array
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.
Example 1:
Input: s = “iloveleetcode”, words = [“i”,”love”,”leetcode”,”apples”]
Output: true
Explanation:
s can be made by concatenating “i”, “love”, and “leetcode” together.
Example 2:
Input: s = “iloveleetcode”, words = [“apples”,”i”,”love”,”leetcode”]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
1 <= s.length <= 1000
words[i] and s consist of only lowercase English letters.
Complexity Analysis
- Time Complexity: O(\Sigma |\texttt{words[i]}|
- Space Complexity: O(\Sigma |\texttt{words[i]}|
1961. Check If String Is a Prefix of Array LeetCode Solution in C++
class Solution {
public:
bool isPrefixString(string s, vector<string>& words) {
string prefix;
for (const string& word : words) {
prefix += word;
if (prefix == s)
return true;
}
return false;
}
};
/* code provided by PROGIEZ */
1961. Check If String Is a Prefix of Array LeetCode Solution in Java
class Solution {
public boolean isPrefixString(String s, String[] words) {
StringBuilder sb = new StringBuilder();
for (final String word : words) {
sb.append(word);
// Do not call `toString()` unless the length matches.
if (sb.length() == s.length() && sb.toString().equals(s))
return true;
}
return false;
}
}
// code provided by PROGIEZ
1961. Check If String Is a Prefix of Array LeetCode Solution in Python
class Solution:
def isPrefixString(self, s: str, words: list[str]) -> bool:
prefix = []
for word in words:
prefix.append(word)
if ''.join(prefix) == s:
return True
return False
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.