Problem 1078

Abstract / Summary

Given two words, find all words in a list that start with the last two letters of the first word and end with the first two letters of the second word.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1078.py

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        words = text.split()
        for i in range(2, len(words)):
            if words[i - 2] == first and words[i - 1] == second:
                yield words[i]
6 lines | 265 bytes | submitted November 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (100k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method findOcurrences. The method receives a string text and two target words first and second. Its purpose is to locate every occurrence in text where first is immediately followed by second, and then to return the word that follows this pair. The method processes the input by tokenizing the text, scanning the token list with a sliding window of three consecutive words, and yielding each qualifying third word as it is found.

Key Steps

The core logic can be broken down into three distinct operations, each reflected in a concise code fragment.

Tokenization The input string is split on whitespace, producing an array of individual words.

words = text.split()

Sliding-window scan A for loop starts at index 2 and walks to the end of the words list. For each position i, the code examines the two preceding entries (i-2 and i-1). If they match first and second respectively, the current word at index i satisfies the required pattern.

for i in range(2, len(words)):
    if words[i - 2] == first and words[i - 1] == second:
        yield words[i]

Result production The method uses the yield statement, turning the function into a generator. Consumers of findOcurrences can iterate over the returned generator to obtain each matching word without the need for an intermediate collection.

Edge Cases Handled

The implementation gracefully deals with several boundary conditions:

When text is empty or contains fewer than three words, the words list length is less than three. The range(2, len(words)) construct then produces an empty sequence, causing the loop body to be skipped entirely and resulting in an empty generator. No index errors occur because the loop never attempts to access words[i - 2] or words[i - 1] when those positions do not exist.

If first or second never appear in the required order, the conditional test never succeeds, and the generator yields no values. The method therefore returns an empty result set without raising exceptions.

When the pattern appears at the very end of the text, such that there is no word after the second token, the loop does not consider that position because the iteration stops at len(words) - 1. Consequently, the method does not attempt to access a non-existent third word, avoiding out-of-range access.

Overlapping occurrences are naturally supported. For a sequence like "a b a b c", with first = "a" and second = "b", the loop will evaluate indices 2, 3, and 4. At index 2 the condition holds and yields "a"; at index 4 the condition holds again and yields "c". The sliding window moves one step at a time, ensuring every valid triple is examined.

Performance Optimizations

The algorithm exhibits several efficiency-focused choices:

The text is tokenized a single time using split(). By storing the resulting list in words, the code avoids repeated splitting or scanning of the original string during the main loop.

The loop iterates directly over integer indices rather than creating auxiliary slices or sub-lists. Accessing words[i - 2], words[i - 1], and words[i] is an O(1) operation, keeping the per-iteration work minimal.

Using a generator (yield) eliminates the need to allocate a full list of results up front. Consumers receive each matching word as soon as it is discovered, which reduces memory pressure especially for large inputs with many matches.

The conditional check combines both equality tests in a single if statement, allowing the interpreter to short-circuit evaluation as soon as the first mismatch is detected. This avoids unnecessary comparisons for most iterations where the pattern does not match.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train made of many colorful toy cars. Each car has a word written on the side. To find the special cars, the computer looks at three cars at once, like a window moving along the train. It checks to see if the first two cars have specific words written on them. If the first car matches the word named first and the second car matches the word named second, then the third car right behind them is a winner. The computer grabs the word on that third car and keeps it. It slides the window forward by one car and checks again until it reaches the very last car of the train. Every time it finds that special pattern, it collects the secret word that comes after the pair.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.26 | σ = 1.35

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune Java
lkwq007 Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune Java
lkwq007 Python
suxrobGM C#
varunu28 Java
32 links | 19 authors | 9 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 medium
3 solutions   November 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality