Python 2395.py
class Solution:
def findSubarrays(self, nums: List[int]) -> bool:
have = set()
for a, b in zip(nums, nums[1:]):
if a + b in have:
return True
have.add(a + b)
return False
Difficulty
and has an acceptance rate of about 67% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method findSubarrays. The method receives a list of integers and determines whether any two consecutive elements in the list produce a sum that has already been observed from a previous pair of consecutive elements. If such a repeated sum exists, the method returns True; otherwise it returns False. The algorithm relies on a set to record sums that have been seen so far, enabling constant-time membership checks.
Key Steps
The first step creates an empty set named have. This set will store the sums of each adjacent pair as the iteration proceeds.
have = set()
The core of the algorithm iterates over the list using zip(nums, nums[1:]). This construct pairs each element with its immediate successor, producing a sequence of tuples (a, b) where a and b are consecutive values from the original list.
for a, b in zip(nums, nums[1:]):
Inside the loop, the sum of the current pair a + b is checked against the have set. If the sum is already present, the method immediately returns True, indicating that a duplicate adjacent-pair sum has been found.
if a + b in have:
return True
If the sum is not present, it is added to the set for future comparisons.
have.add(a + b)
After the loop completes without encountering a repeated sum, the method returns False, signifying that all adjacent-pair sums were unique.
return False
Edge Cases
The algorithm gracefully handles several edge conditions without additional code. When the input list contains fewer than two elements, the zip expression yields an empty iterator, causing the loop body to be skipped entirely. In this situation the method proceeds directly to the final return False, correctly indicating that no pair of consecutive elements exists to produce a sum.
If the list consists of exactly two elements, the loop executes once, computes the single possible sum, adds it to the set, and then exits. Since there is no second pair to compare against, the method returns False, which aligns with the expectation that a duplicate sum cannot arise from a single pair.
When the list contains repeated values or patterns that generate identical sums from different positions, the set membership test captures the duplication. For example, a sequence like [1, 2, 3, 0] yields sums 3, 5, and 3; the second occurrence of 3 triggers the early return of True. The set structure ensures that only the existence of a sum matters, not how many times it has been added.
Performance Optimizations
The primary optimization stems from the use of a hash set (have). Adding an element to a set and checking for membership are both average-case constant-time operations. This choice eliminates the need for nested loops or repeated scanning of previously computed sums, allowing the algorithm to process the input in a single pass.
By employing zip(nums, nums[1:]), the code avoids explicit index arithmetic and bounds checking. The iterator produced by zip stops automatically before the last element, guaranteeing that each pair is formed safely without risking an out-of-range access. This approach also reduces the overhead associated with manual loop counters.
The early exit on detection of a duplicate sum further improves efficiency. As soon as a repeated sum is found, the method returns immediately, bypassing any remaining iterations. In the best case-when a duplicate appears early-the algorithm terminates after only a few steps, saving work compared to a full traversal.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered toy blocks lined up on the floor. This code acts like a little robot helper that walks along the row to look at two blocks at a time. It picks up the first block and its neighbor right next to it, then adds their values together to get a new secret sum.
The robot carries a special magic box to keep track of every sum it finds. Before putting the new sum into the box, the robot checks to see if that same sum is already inside. If the sum is already hiding in the box, the robot knows it found a pair of sums that are exactly the same. The robot then moves one step forward to look at the next pair of neighbors and does the same thing all over again. If it finishes walking through all the blocks without ever finding a sum that matches one already in the box, the job is done.
Code Quality
Complexity Analysis
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
Other Solutions
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 | Java | Python | C++ | TS | |||||
| WalkCCC | Java | Python | C++ | |||||||
| leetcode.ca | Java | Python | C++ | C | Go | Rust | TS | |||
| Progiez | Java | Python | C++ | |||||||
| github | charles-wangkai | Java | ||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| charles-wangkai | Java | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1: Two Sum
- problem 416: Partition Equal Subset Sum
- problem 1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
Solved On The Same Day
- problem 2389: Longest Subsequence With Limited Sum
- problem 2399: Check Distances Between Same Letters
- problem 2400: Number of Ways to Reach a Position After Exactly k Steps
- problem 2328: Number of Increasing Paths in a Grid
Extra
- 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