#1023
Camelcase Matching
MediumArrayTwo PointersStringTrieString MatchingTwo PointersString Matching
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pointer technique to efficiently match the pattern against each query. This approach reduces unnecessary checks and allows us to determine matches in linear time.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty result list.
- 2Step 2: For each query, initialize two pointers: one for the query and one for the pattern.
- 3Step 3: Traverse through the query and pattern simultaneously. If characters match, move both pointers; if they don't, only move the query pointer.
- 4Step 4: If the pattern pointer reaches the end, it means the pattern is matched; otherwise, it doesn't.
- 5Step 5: Store the result for each query.
solution.py8 lines
1def camelcaseMatching(queries, pattern):
2 def matches(query):
3 p_idx = 0
4 for char in query:
5 if p_idx < len(pattern) and char == pattern[p_idx]:
6 p_idx += 1
7 return p_idx == len(pattern)
8 return [matches(q) for q in queries]ℹ
Complexity note: The optimal solution runs in O(n) time for each query since we only traverse the query string once, making it efficient.
- 1The pattern must be matched in order, but can have lowercase letters in between.
- 2Using two pointers allows for efficient matching without unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.