Solving Leetcode Interviews in Seconds with AI: Occurrences After Bigram
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1078" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of "first second third". Example 1: Input: text = "alice is a good girl she is a good student", first = "a", second = "good" Output: ["girl","student"] Example 2: Input: text = "we will we will rock you", first = "we", second = "will" Output: ["we","rock"] Constraints: 1 <= text.length <= 1000 text consists of lowercase English letters and spaces. All the words in text are separated by a single space. 1 <= first.length, second.length <= 10 first and second consist of lowercase English letters. text will not have any leading or trailing spaces.
Explanation
Here's the solution:
- Tokenization: Split the input text into a list of words using spaces as delimiters.
- Iteration and Comparison: Iterate through the list of words, checking for occurrences of "first second". When a match is found, append the subsequent word (the "third" word) to the result list.
Edge Case Handling: Ensure that the iteration doesn't go out of bounds when checking for the "third" word.
Runtime Complexity: O(n), where n is the number of words in the text.
- Storage Complexity: O(k), where k is the number of occurrences of "third" words in the result list.
Code
def findOcurrences(text: str, first: str, second: str) -> list[str]:
"""
Finds all occurrences of the "third" word following "first second" in the given text.
Args:
text: The input text.
first: The first word to search for.
second: The second word to search for.
Returns:
A list of all "third" words.
"""
words = text.split()
result = []
for i in range(len(words) - 2):
if words[i] == first and words[i + 1] == second:
result.append(words[i + 2])
return result