#3042
Count Prefix and Suffix Pairs I
EasyArrayStringTrieRolling HashString MatchingHash FunctionHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
The optimal solution uses a HashMap to store the words and their lengths, allowing us to quickly check if a word can be a prefix or suffix of another. This reduces the number of comparisons needed.
⚙️
Algorithm
4 steps- 1Step 1: Create a HashMap to store the words and their lengths.
- 2Step 2: Iterate through each word and check for all possible lengths of prefixes that could also be suffixes in other words.
- 3Step 3: For each word, check if it exists in the HashMap with the required conditions.
- 4Step 4: Count valid pairs and return the total.
solution.py11 lines
1def countPairs(words):
2 word_map = {}
3 count = 0
4 for word in words:
5 word_map[word] = len(word)
6 for word in words:
7 for length in range(1, len(word) + 1):
8 prefix = word[:length]
9 if prefix in word_map and prefix != word:
10 count += 1
11 return countℹ
Complexity note: The time complexity is O(n * m) where n is the number of words and m is the average length of the words. The space complexity is O(n) due to the HashMap storing the words.
- 1Understanding prefix and suffix relationships is crucial.
- 2Utilizing data structures like HashMap can optimize search operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.