Leetcode 1961: Check If String Is a Prefix of Array

grid47
grid47
Exploring patterns and algorithms
Apr 24, 2024 5 min read

You are given a string s and an array of strings words. Determine if the string s can be formed by concatenating the first k strings from the array words, for some value of k, where 1 <= k <= words.length. Return true if s is a prefix of words, or false otherwise.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` and an array of strings `words`. The string `s` is a potential prefix formed by concatenating the first `k` words from the array `words`.
Example: s = "hello", words = ["he", "llo"]
Constraints:
• 1 <= words.length <= 100
• 1 <= words[i].length <= 20
• 1 <= s.length <= 1000
• words[i] and s consist of only lowercase English letters.
Output: The output should be a boolean value indicating whether `s` is a prefix formed by concatenating the first `k` words in `words`.
Example: Output: true
Constraints:
• The string `s` must match the prefix formed by the concatenation of the words in `words`.
Goal: The goal is to check if the string `s` can be constructed by concatenating the first `k` strings in the array `words`.
Steps:
• Step 1: Traverse through the strings in `words`, concatenating them one by one.
• Step 2: Compare the concatenated string with `s` at each step.
• Step 3: If the concatenated string matches `s`, return true; otherwise, return false.
Goal: The problem constraints ensure that the length of `words` and `s` are manageable for efficient checking.
Steps:
• The length of `words` is at most 100.
• The length of each word is at most 20 characters.
• The length of `s` is at most 1000 characters.
Assumptions:
• The array `words` will not contain any empty strings.
Input: Input: s = "hello", words = ["he", "llo"]
Explanation: Here, the string `s` can be formed by concatenating the first two words from `words`, i.e., "he" + "llo" = "hello".

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus