Itssuman1808

Write a function that returns `true` if two arrays have the

Apr 28th, 2020
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. #Write a function that returns `true` if two arrays have the same number of unique elements.
  2. #pYTHON pROGRAM
  3. #We can Use Hashing to solve this in O(n) time on average.
  4. #The idea is to traverse the given array from left to right
  5. #and keep track of visited elements in a hash set , as a set consists of only unique elements.
  6. # This function prints all distinct elements  
  7. def countDistinct(arr, n):
  8.     # Creates an empty hashset  
  9.     s = set()
  10.     # Traverse the input array  
  11.     res = 0
  12.     for i in range(n):
  13.         # If not present, then put it in  
  14.         # hashtable and increment result  
  15.         if (arr[i] not in s):
  16.             s.add(arr[i])
  17.             res += 1
  18.     return res  
  19. #this is the function returns `true` and print `true` if two arrays have the same number of unique elements
  20.  
  21. def CheckUniqeNoOfElement (arr1, arr2):
  22.   n1 = len (arr1)
  23.   n2 = len (arr2)
  24.   if (countDistinct(arr1, n1) == countDistinct(arr2, n2)):
  25.     print("true")
  26.   else:
  27.     print("false")
  28.    
  29. arr1 =[2]
  30. arr2 =[3, 3, 3, 3]
  31. CheckUniqeNoOfElement (arr1, arr2)
Add Comment
Please, Sign In to add comment