Skip to content
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

Add solution to Leetcode #349 - intersection of two arrays #8

Open
wants to merge 1 commit into
base: master
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
37 changes: 37 additions & 0 deletions 300-400q/349.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'''
Given two arrays, write a function to compute their intersection.

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

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

class Solution:
def intersection(self, arrA: List[int], arrB: List[int]) -> List[int]:

arrA.sort()
arrB.sort()

intersection = []

aIndex = 0
bIndex = 0
recentOverlap = None

while aIndex < len(arrA) and bIndex < len(arrB):
if arrA[aIndex] > arrB[bIndex]:
bIndex += 1
elif arrA[aIndex] == arrB[bIndex]:
if arrB[bIndex] != recentOverlap: # skip duplicate overlapping elements
recentOverlap = arrB[bIndex]
intersection.append(recentOverlap)
bIndex += 1 # you could increment aIndex instead
else:
# arrA[aIndex] < arrB[bIndex]
aIndex += 1

return intersection
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
|378|[Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix) | [Python](./300-400q/378.py)|Medium|
|361|[Bomb Enemy](https://leetcode.com/problems/bomb-enemy)|[Python](./300-400q/361.py)|Medium|
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Python](./300-400q/350.py)|Easy|
|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [Python](./300-400q/349.py) | Easy |
|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](./300-400q/347.py)|Medium|
|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream)|[Python](./300-400q/346.py)|Easy|
|340|[Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters)|[Python](./300-400q/340.py)|Hard|
Expand Down