#1961

Check If String Is a Prefix of Array

Easy
ArrayTwo PointersStringTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of building the prefix string step-by-step, we can directly compare the concatenated result of the first k words with the string `s`. This reduces unnecessary checks and string manipulations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable `prefixLength` to 0.
  2. 2Step 2: Iterate through the `words` array, adding the length of each word to `prefixLength`.
  3. 3Step 3: If at any point `prefixLength` equals the length of `s`, check if the concatenated substring of `s` matches the prefix formed by the first k words.
  4. 4Step 4: If `prefixLength` exceeds the length of `s`, return false.
  5. 5Step 5: If the loop completes and no match is found, return false.
solution.py15 lines
1# Full working Python code
2s = 'iloveleetcode'
3words = ['i', 'love', 'leetcode', 'apples']
4
5def is_prefix_string(s, words):
6    prefixLength = 0
7    for word in words:
8        prefixLength += len(word)
9        if prefixLength == len(s):
10            return s == ''.join(words[:words.index(word) + 1])
11        if prefixLength > len(s):
12            return False
13    return False
14
15print(is_prefix_string(s, words))

Complexity note: The time complexity is O(n) because we only iterate through the `words` array once, accumulating lengths and checking conditions, which is efficient compared to the brute force method.

  • 1Understanding how prefixes work is crucial for string manipulation problems.
  • 2Recognizing when to optimize a brute force solution can save time and resources.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.