#2255

Count Prefixes of a Given String

Easy
ArrayStringHash MapArray
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)

The optimal approach leverages the fact that we can directly check the prefix of 's' against the words in 'words' without unnecessary comparisons. This reduces the overall time complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Create a set of valid prefixes from 's' by iterating through its characters.
  3. 3Step 3: For each word in 'words', check if it exists in the set of prefixes.
  4. 4Step 4: If it exists, increment the counter.
  5. 5Step 5: Return the counter as the result.
solution.py3 lines
1def countPrefixes(words, s):
2    prefixes = {s[:i] for i in range(1, len(s) + 1)}
3    return sum(1 for word in words if word in prefixes)

Complexity note: The time complexity is O(n) because we create a set of prefixes in linear time and check each word against this set, which is efficient.

  • 1Understanding prefixes is crucial for string manipulation problems.
  • 2Using data structures like sets can optimize lookup times.

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