Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Two Out of Three

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2032" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 1: 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: - 3, in all three arrays. - 2, in nums1 and nums2. Example 2: Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] Output: [2,3,1] Explanation: The values that are present in at least two arrays are: - 2, in nums2 and nums3. - 3, in nums1 and nums2. - 1, in nums1 and nums3. Example 3: Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5] Output: [] Explanation: No value is present in at least two arrays. Constraints: 1 <= nums1.length, nums2.length, nums3.length <= 100 1 <= nums1[i], nums2[j], nums3[k] <= 100

Explanation

Here's a breakdown of the approach and the Python code:

  • High-Level Approach:

    • Use sets to efficiently check for the presence of an element in each array.
    • Iterate through a combined set of all unique elements from the three arrays.
    • For each element, count how many arrays it appears in using set lookups. If the count is >= 2, add it to the result.
  • Complexity:

    • Runtime: O(n), where n is the total number of elements in the three arrays.
    • Storage: O(n), for storing the sets and the result.

Code

    def twoOutOfThree(nums1, nums2, nums3):
    """
    Finds distinct elements present in at least two of the three input arrays.

    Args:
        nums1: The first list of integers.
        nums2: The second list of integers.
        nums3: The third list of integers.

    Returns:
        A list of distinct integers present in at least two arrays.
    """
    set1 = set(nums1)
    set2 = set(nums2)
    set3 = set(nums3)

    result = []
    combined_set = set(nums1 + nums2 + nums3)  # All unique numbers

    for num in combined_set:
        count = 0
        if num in set1:
            count += 1
        if num in set2:
            count += 1
        if num in set3:
            count += 1

        if count >= 2:
            result.append(num)

    return result

More from this blog

C

Chatmagic blog

2894 posts