#2185
Counting Words With a Given Prefix
EasyArrayStringString MatchingString MatchingPrefix Trees
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * m) | O(n * m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n * m)Space O(1)
We can achieve better performance by directly checking the prefix without using additional string methods. This way, we can avoid unnecessary overhead.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter to zero.
- 2Step 2: Loop through each word in the words array.
- 3Step 3: For each word, compare the first characters up to the length of the prefix.
- 4Step 4: If the characters match the prefix, increment the counter.
- 5Step 5: After checking all words, return the counter.
solution.py9 lines
1# Full working Python code
2words = ["pay", "attention", "practice", "attend"]
3pref = "at"
4
5count = 0
6for word in words:
7 if word[:len(pref)] == pref:
8 count += 1
9print(count)ℹ
Complexity note: The time complexity remains O(n * m) since we still iterate through each word, but we avoid the overhead of method calls, making it more efficient in practice.
- 1Using string methods can simplify code but may add overhead.
- 2Direct character comparison can improve performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.