LeetCode 1213. Intersection of Three Sorted Arrays Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1213. Intersection of Three Sorted Arrays

Description

Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.

 

Example 1:

Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
Output: [1,5]
Explanation: Only 1 and 5 appeared in the three arrays.

Example 2:

Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]
Output: []

 

Constraints:

  • 1 <= arr1.length, arr2.length, arr3.length <= 1000
  • 1 <= arr1[i], arr2[i], arr3[i] <= 2000

Solutions

Solution 1: Counting

Traverse the three arrays, count the occurrence of each number, then traverse any one of the arrays. If the count of a number is 3, add it to the result array.

The time complexity is O(n), and the space complexity is O(m). Here, n and m are the length of the array and the range of numbers in the array, respectively.

PythonJavaC++GoPHP
class Solution: def arraysIntersection( self, arr1: List[int], arr2: List[int], arr3: List[int] ) -> List[int]: cnt = Counter(arr1 + arr2 + arr3) return [x for x in arr1 if cnt[x] == 3](code-box)

Solution 2: Binary Search

Traverse the first array. For each number, use binary search to find this number in the second and third arrays. If found in both, add this number to the result array.

The time complexity is O(n × log n), and the space complexity is O(1). Here, n is the length of the array.

PythonJavaC++Go
class Solution: def arraysIntersection( self, arr1: List[int], arr2: List[int], arr3: List[int] ) -> List[int]: ans = [] for x in arr1: i = bisect_left(arr2, x) j = bisect_left(arr3, x) if i < len(arr2) and j < len(arr3) and arr2[i] == x and arr3[j] == x: ans.append(x) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !