Skip to content

Intersection of two arrays #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions GeeksforGeeks/move_all_zeros.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def pushZerosToEnd(self, arr, n):
count = 0
for i in arr:
if i != 0:
arr[count] = i
count += 1
while count < n:
arr[count] = 0
count += 1
return arr


arr = [3, 5, 0, 0, 4]
n = 5
print(Solution().pushZerosToEnd(arr=arr, n=n))
19 changes: 19 additions & 0 deletions LeetCode/intersection_two_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import List


class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
hash_set = set(nums1)
result = []
for i in nums2:
if i in hash_set:
result.append(i)
hash_set.remove(i)
return result


nums1 = [2, 2]
nums2 = [9, 4, 9, 2, 2]

solution = Solution().intersect(nums1, nums2)
print(solution)
20 changes: 20 additions & 0 deletions LeetCode/intersection_two_array_two.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import List
from collections import Counter


class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
counter = Counter(nums1)
result = []
for item in nums2:
if counter[item] > 0:
result.append(item)
counter[item] -= 1
return result


nums1 = [2, 2]
nums2 = [9, 4, 9, 2, 2]

solution = Solution().intersect(nums1, nums2)
print(solution)
34 changes: 34 additions & 0 deletions LeetCode/intersection_two_array_two_sorted.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import List
from collections import Counter


class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()

pointer_one = 0
pointer_two = 0
result = []

while pointer_one < len(nums1) and pointer_two < len(nums2):

if nums1[pointer_one] < nums2[pointer_two]:
pointer_two += 1

elif nums1[pointer_two] > nums2[pointer_one]:
pointer_one += 1

else:
result.append(nums1[pointer_one])
pointer_two += 1
pointer_one += 1

return result


nums1 = [4, 9, 5]
nums2 = [9, 4, 9, 8, 4]

solution = Solution().intersect(nums1, nums2)
print(solution)