Problem 2248

Abstract / Summary

Find the integers that appear in every array and list them in ascending order.

Note

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

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)
6 lines | 207 bytes | submitted February 23, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Counting
  • Hash Table
  • Sorting
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 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.

written by openai gpt

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.

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 = 8 | μ = 8.22 | σ = 0.99

Complexity Analysis

Time: polynomial
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 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
26 links | 14 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   February 23, 2024

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