Similar Problems

Similar Problems not available

Two Out Of Three - Leetcode Solution

Companies:

LeetCode:  Two Out Of Three Leetcode Solution

Difficulty: Easy

Topics: hash-table bit-manipulation array  

The Two Out of Three problem on LeetCode is a problem that requires you to find all the elements that are present in at least two out of three lists.

Here’s the detailed solution for the problem:

We will start by writing a function that takes three lists as input and returns a set of all the elements that are present in at least two out of the three lists.

def twoOutOfThree(list1, list2, list3):
    result = set()
    seen1 = set()
    seen2 = set()

    for num in list1:
        seen1.add(num)

    for num in list2:
        if num in seen1:
            result.add(num)
        else:
            seen2.add(num)

    for num in list3:
        if num in seen1 or num in seen2:
            result.add(num)

    return result

In this function, we first initialize an empty set called result. We will add all the elements that are present in at least two out of the three lists to this set.

We then create two sets called seen1 and seen2. We will use these sets to keep track of the elements we have seen so far.

We loop through the first list and add all the elements to seen1. We then loop through the second list and check if the element is present in seen1. If it is, we add it to result. If it is not, we add it to seen2.

We then loop through the third list and check if the element is present in seen1 or seen2. If it is, we add it to result.

Finally, we return the result set.

Note: In this solution, we are using sets to keep track of the elements we have seen and the elements that are present in at least two out of the three lists. Sets are a good choice for this problem because they provide fast membership testing.

Overall, this solution has a time complexity of O(n), where n is the total number of elements in all three lists.

Two Out Of Three Solution Code

1