Recommended Posts

DSA (Easy) — Sets — Find the Difference of Two Arrays (Python, Typescript & Go)

0 comments

simplestack0.312 months agoPeakD4 min read


https://files.peakd.com/file/peakd-hive/simplestack/23z7Byuj3ivG4wAkuk5gb1uxHMdGHNudJ9yusShbnM2nPy6Zgt9NeU8QUnwH5sQy9YfTG.png

Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:

  • answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
  • answer[1] is a list of all distinct integers in nums2 which are not present in nums1.

Note that the integers in the lists may be returned in any order.

Example 1

Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Explanation:
For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].

Example 2

Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
Output: [[3],[]]
Explanation:
For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
Every integer in nums2 is present in nums1. Therefore, answer[1] = [].

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • -1000 <= nums1[i], nums2[i] <= 1000

Solutions

Using Sets

Think of each input list as a collection of unique items. Convert each list into a mathematical set. This removes duplicates and makes it easy to perform set operations.

Set Difference

✔️set1 - set2: This operation gives you all the elements that are in set1 but not in set2.

✔️set2 - set1: This operation gives you all the elements that are in set2 but not in set1.

Convert Back to Lists

✔️The results of the set difference operations are sets. Convert them back into lists to match the required output format.

Why Sets Are Efficient

✔️Sets are designed for fast membership testing (checking if an element is in the set). This makes the difference operations very efficient, especially for large lists.

✔️Sets automatically handle the removal of duplicates.

Without Using Sets (Go)

Imagine you have two bags of marbles (lists of numbers).

  1. You create two separate containers (maps) and put each unique marble from the first bag into the first container, and each unique marble from the second bag into the second container.
  2. Then, you look at each marble in the first container. If that marble isn't in the second container, you put it in a new, third bag.
  3. You do the same, but you look at the marbles in the second container and put any that aren't in the first container into a fourth bag.
  4. Finally, you return the third and fourth bags.

Implementations

Python

class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        set1 = set(nums1)
        set2 = set(nums2)

        difference1 = list(set1 - set2)
        difference2 = list(set2 - set1)

        return [difference1, difference2]

Typescript

function findDifference(nums1: number[], nums2: number[]): number[][] {
    const setNums1 = new Set(nums1)
    const setNums2 = new Set(nums2)

    const nums1DiffNums2 = setNums1.difference(setNums2)
    const nums2DiffNums1 = setNums2.difference(setNums1)

    return [
        [...nums1DiffNums2],
        [...nums2DiffNums1]
    ]
};

Go

func findDifference(nums1 []int, nums2 []int) [][]int {
    set1 := make(map[int]bool)
    set2 := make(map[int]bool)

    for _, num := range nums1 {
        set1[num] = true
    }
    for _, num := range nums2 {
        set2[num] = true
    }

    diff1 := []int{}
    for num := range set1 {
        if !set2[num] {
            diff1 = append(diff1, num)
        }
    }

    diff2 := []int{}
    for num := range set2 {
        if !set1[num] {
            diff2 = append(diff2, num)
        }
    }

    return [][]int{diff1, diff2}
}

If you liked this article I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.

Muchas gracias!

Follow me for more content like this.

X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium

Down below you can find other ways to tip my work.

BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"

Comments

Sort byBest