SUMMER TRAINING Free Tutorials  Go To Your University  Placement Preparation 
Project Based Best Summer Training Courses in Jaipur
Join our Telegram Channel To take free Online Courses
0 like 0 dislike
218 views
in Coding Questions by Goeduhub's Expert (2.3k points)

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

1 Answer

0 like 0 dislike
by Goeduhub's Expert (2.3k points)
 
Best answer

Simple count all the occurance of each number for nums 1 and then compare its freq from nums 2 to get final ans.

class Solution:

    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:

        dict1 = dict()

        for i in nums1:

            if i not in dict1:

                dict1[i] = 1

            else:

                dict1[i] += 1

        ret = []

        for i in nums2:

            if i in dict1 and dict1[i]>0:

                ret.append(i)

                dict1[i] -= 1

        return ret

eg : ans = Solution()

nums1 = [1,2,2,1], nums2 = [2,2]

ans.intersect(nums1, nums2)

Output -

[2,2]

Our Mentors(For AI-ML)


Sharda Godara Chaudhary

Mrs. Sharda Godara Chaudhary

An alumna of MNIT-Jaipur and ACCENTURE, Pune

NISHA (IIT BHU)

Ms. Nisha

An alumna of IIT-BHU

Related questions

0 like 0 dislike
1 answer 188 views
asked Sep 14, 2020 in Coding Questions by Vaibhav98 Goeduhub's Expert (2.3k points)
0 like 0 dislike
1 answer 26 views
0 like 0 dislike
1 answer 146 views
asked Aug 24, 2020 in Coding Questions by Vaibhav98 Goeduhub's Expert (2.3k points)
0 like 0 dislike
1 answer 80 views
0 like 0 dislike
1 answer 80 views
asked Sep 11, 2020 in Coding Questions by Vaibhav98 Goeduhub's Expert (2.3k points)

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...