#1078
Occurrences After Bigram
EasyStringSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By iterating through the words only once and checking adjacent pairs, we can efficiently find the occurrences without needing nested loops. This reduces our time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Split the input text into a list of words.
- 2Step 2: Initialize an empty result list.
- 3Step 3: Iterate through the list of words from the first to the second last index, checking if the current word and the next word match 'first' and 'second'. If they do, add the word after the second to the result list.
solution.py7 lines
1def findOcurrences(text, first, second):
2 words = text.split()
3 result = []
4 for i in range(len(words) - 2):
5 if words[i] == first and words[i + 1] == second:
6 result.append(words[i + 2])
7 return resultℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the list of words. The space complexity is O(n) due to the storage of the result list, which can grow depending on the number of matches found.
- 1Understanding the structure of the problem helps in identifying patterns.
- 2Recognizing that we can reduce complexity by avoiding nested loops is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.