Two Out of Three — LeetCode 2032 Python Solution

EasyBit ManipulationArrayHash Table
Problem
#2032
Reading time
2 min

The problem

Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.

Example

Input
nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output
[3,2]
Explanation
The values that are present in at least two arrays are:

Python solution

Python
class Solution:
    def twoOutOfThree(
        self, nums1: List[int], nums2: List[int], nums3: List[int]
    ) -> List[int]:
        s1, s2, s3 = set(nums1), set(nums2), set(nums3)
        return [i for i in range(1, 101) if (i in s1) + (i in s2) + (i in s3) > 1]

Complexity

MeasureComplexity
TimeO(n_1 + n_2 + n_3)
SpaceO(n_1 + n_2 + n_3) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2032. Two Out of Three is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2032. Two Out of Three?
LeetCode 2032. Two Out of Three is rated Easy on LeetCode.
What is the time complexity of LeetCode 2032. Two Out of Three?
The Python solution on this page runs in O(n_1 + n_2 + n_3).
What is the space complexity of LeetCode 2032. Two Out of Three?
The Python solution on this page uses O(n_1 + n_2 + n_3) auxiliary space.
What topics does LeetCode 2032. Two Out of Three cover?
LeetCode 2032. Two Out of Three is tagged Bit Manipulation, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview