Python 2248.py
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
result = set(nums[0])
for row in nums[1 :]:
result &= set(row)
return sorted(result)
Difficulty
and has an acceptance rate of about 69% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
- Sorting
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 Solution class with a single method intersection. The method receives a two-dimensional list nums, where each inner list represents a collection of integers. Its purpose is to compute the set of values that appear in every inner list and return those values in ascending order. The algorithm relies on Python’s built-in set type to perform intersection operations efficiently.
Key Steps
Initialization of the Result Set
The first executable line inside the method creates a set from the first inner list:
result = set(nums[0])
By converting the first row to a set, the code establishes a baseline collection of candidate elements. Using a set eliminates duplicate values from the first row and enables fast membership checks in subsequent steps.
Iterative Intersection Across Remaining Rows
The method then iterates over the remaining rows, updating the result set with the intersection of itself and the current row:
for row in nums[1:]:
result &= set(row)
The &= operator performs an in-place intersection, retaining only those elements that are present in both result and the newly created set from row. This step is repeated for each subsequent inner list, progressively narrowing the candidate pool to values common to all rows processed so far.
Sorting the Final Result
After all rows have been processed, the method returns a sorted list derived from the final set:
return sorted(result)
The sorted function produces a new list containing the intersecting elements in non-decreasing order, satisfying the requirement for an ordered output.
Edge Cases Handled
The algorithm gracefully manages several edge conditions without additional conditional logic.
When nums contains only a single inner list, the slice nums[1:] yields an empty sequence, so the loop body is never executed. Consequently, result remains the set representation of that sole list, and the method returns its unique elements sorted.
If any inner list is empty, converting it to a set yields an empty set. The in-place intersection with an empty set clears result entirely, ensuring that the final output is an empty list. This behavior correctly reflects the mathematical definition of intersection when at least one operand lacks elements.
When duplicate values appear within an inner list, the conversion to a set automatically discards the duplicates. This prevents redundant work during intersection and guarantees that each value appears at most once in the final result.
If the outer list nums itself is empty, attempting to access nums[0] would raise an IndexError. However, the method’s contract assumes that at least one inner list is provided, which aligns with typical problem specifications for intersection tasks. Within the defined precondition, the code operates correctly.
Performance Optimizations
The implementation leverages the intrinsic properties of Python’s set type to achieve efficient computation.
The use of set(nums[0]) as the initial candidate pool means that the algorithm starts with the smallest possible representation of the first row, eliminating duplicate entries early and reducing the amount of data processed in later intersections.
The in-place intersection operator &= updates the existing result set rather than creating a new set on each iteration. This avoids the overhead of allocating additional set objects and reduces memory churn, especially when dealing with a large number of rows.
By converting each subsequent row to a set only when needed, the code avoids unnecessary conversions for rows that are never examined (which would not happen in this linear traversal but illustrates a disciplined approach to resource usage).
Finally, the call to sorted is performed once after all intersections are complete. Sorting a set of intersecting elements is typically far cheaper than sorting each row individually, because the size of the final set is bounded by the smallest row and often much smaller than the total number of input elements. This placement of the sorting step ensures that the algorithm spends minimal time on ordering operations.
ELI5 - Simplified Explanation
Imagine there are several groups of children, and each group has a basket full of numbered blocks. Some blocks are the same, and some are different. This code is like a magical game to find out which blocks show up in every single basket.
First, the code takes the first basket of blocks and calls it the starting collection. Then, it looks at each of the other baskets one by one. For every new basket, it compares the current collection with the new one and keeps only the blocks that exist in both places at the same time. After checking every single basket, the final collection contains only the blocks that were lucky enough to be in every basket. Finally, the code organizes those special blocks in order from the smallest number to the largest number so they look neat and tidy.
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 | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | PHP | TS | ||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| muhammadfarhankt | Go | |||||||||
| shreymehul | C# | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| muhammadfarhankt | Go | |||||||||
| shreymehul | C# | |||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2215: Find the Difference of Two Arrays
Solved On The Same Day
- problem 1619: Mean of Array After Removing Some Elements
- problem 2255: Count Prefixes of a Given String
- problem 2303: Calculate Amount Paid in Taxes
- problem 2475: Number of Unequal Triplets in Array
- problem 2490: Circular Sentence
- problem 2496: Maximum Value of a String in an Array
- problem 2788: Split Strings by Separator
- problem 2900: Longest Unequal Adjacent Groups Subsequence I
- problem 2946: Matrix Similarity After Cyclic Shifts
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