Python 2215.py
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
a = set(nums1)
b = set(nums2)
return [list(a - b), list(b - a)]
Difficulty
and has an acceptance rate of about 82% (800k+ 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 findDifference method receives two integer arrays and produces a pair of collections. The first collection contains the distinct values that appear in the first array but not in the second, while the second collection contains the distinct values that appear in the second array but not in the first. The implementation relies on Python’s built-in set type to enforce uniqueness and to perform set-difference operations efficiently.
Key Steps
The method begins by converting each input list into a set, thereby discarding duplicate entries and enabling fast membership tests.
a = set(nums1)
b = set(nums2)
Next, it computes the elements that are exclusive to each set. The expression a - b yields all items that belong to a but not to b; similarly, b - a yields the opposite.
diff_a = a - b
diff_b = b - a
Finally, the method transforms the resulting sets back into list objects, because the required return type is a list of lists, and returns them as a two-element list.
return [list(diff_a), list(diff_b)]
Edge Cases Handled
When either input list is empty, the corresponding set is empty as well. The set-difference operation on an empty set naturally yields an empty result, so the method returns an empty list for that side of the difference.
If both input lists contain exactly the same elements, each set will be identical; the differences a - b and b - a both evaluate to empty sets, leading to a return value of [[], []].
Duplicate values inside a single input list are eliminated by the initial conversion to a set, ensuring that the output lists contain only unique elements regardless of how many times a value appears in the original arrays.
When one list is a superset of the other, the method correctly returns the extra elements in the larger list as the first component and an empty list as the second component, reflecting that there are no exclusive elements in the smaller list.
Performance Optimizations
The conversion to set provides constant-time average complexity for membership checks and eliminates the need for explicit loops to filter duplicates.
Set-difference (a - b and b - a) is implemented in C within the Python runtime, offering a highly optimized way to compute exclusive elements without manual iteration.
By postponing the conversion back to list until after the differences are computed, the code avoids repeated list constructions and keeps the intermediate data in the more efficient set representation for as long as possible.
Overall, the approach leverages Python’s built-in data structures to achieve concise logic while maintaining efficient execution for typical input sizes.
ELI5 - Simplified Explanation
Imagine you have two big boxes full of colorful building blocks. The first box has some blocks, and the second box has some different blocks. Some blocks might be the same in both boxes, like a blue square in box one and also a blue square in box two.
The first step is taking all the blocks out of the boxes and making sure there are no duplicates. A set is like a special pile where you only keep one of each kind of block, so if you had two red bricks, you just keep one red brick. Now you have two clean piles of unique blocks.
The next part is comparing the two piles. You look at the first pile and take away any blocks that are also found in the second pile. Those leftover blocks are the ones that are special because they only exist in that first box. Then you do the same thing for the second pile to find the blocks that only exist there. Finally, you put those two groups of special, leftover blocks into their own smaller boxes so you can see exactly which blocks are unique to each side.
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 | C++ | Python | TS | ||||||
| WalkCCC | Java | C++ | Python | ||||||||
| leetcode.ca | Java | C++ | Python | JS | Go | PHP | Rust | TS | |||
| Progiez | Java | C++ | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java |
Videos
Similar Problems
- problem 349: Intersection of Two Arrays
- problem 350: Intersection of Two Arrays II
- problem 2248: Intersection of Multiple Arrays
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
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