To find the common elements between two sorted arrays, you can use a two-pointer technique, which is efficient with a time complexity of O(n + m), where n and m are the lengths of the two arrays. Here's how you can do it:
Approach
Initialize two pointers, one for each array, starting at the beginning (index 0).
Compare the elements at the current positions of the two pointers:
If the elements are equal, add the element to the result list and move both pointers forward.
If the element in the first array is smaller, move the pointer in the first array forward.
If the element in the second array is smaller, move the pointer in the second array forward.
Continue this process until one of the pointers reaches the end of its respective array.
Solution Code
python
def find_common_elements(arr1, arr2):
common_elements = []
i = j = 0
len1, len2 = len(arr1), len(arr2)
while i < len1 and j < len2:
if arr1[i] == arr2[j]:
common_elements.append(arr1[i])
i += 1
j += 1
elif arr1[i] < arr2[j]:
i += 1
else:
j += 1
return common_elements
Explanation
Initialization: We start with two pointers, i and j, both set to 0, pointing to the first elements of arr1 and arr2 respectively.
Comparison Loop: The loop continues as long as both pointers are within the bounds of their arrays.
Equal Elements: If the elements at arr1[i] and arr2[j] are equal, the element is added to the result list, and both pointers are incremented to move to the next elements.
Smaller Element in arr1: If the current element in arr1 is smaller, the pointer i is incremented to check the next element in arr1.
Smaller Element in arr2: If the current element in arr2 is smaller, the pointer j is incremented to check the next element in arr2.
Termination: The loop exits when either pointer reaches the end of its array, ensuring all possible common elements have been checked.
This approach efficiently finds the intersection of the two sorted arrays by leveraging their sorted order to minimize the number of comparisons needed.
User
Here is a test case and expected output.
Given:
code
# Example usage:
arr1 = [1, 2, 2, 2, 3, 4] # First sorted array
arr2 = [2, 4, 5] # Second sorted array
Return:
[2,2,2,4]
Assistant
Given the test case, the expected output is [2, 2, 2, 4]. However, the initial solution provided will return [2, 4] because it only includes each common element once (i.e., it treats duplicates as a single occurrence).
To match the expected output where all occurrences of common elements are included, we need to modify the approach slightly. Here's the corrected solution:
Approach
Two-pointer Technique: Use two pointers to traverse both arrays simultaneously.
Handling Duplicates: When a common element is found, include all occurrences of that element from the first array that match the current element in the second array. This involves moving the pointer in the first array past all duplicates of the current element while the pointer in the second array remains at the current element until it changes.
Solution Code
python
def find_common_elements(arr1, arr2):
common_elements = []
i = j = 0
len1, len2 = len(arr1), len(arr2)
while i < len1 and j < len2:
if arr1[i] == arr2[j]:
# Collect all occurrences of arr1[i] in arr1 that match arr2[j]
current_val = arr1[i]
# Move i past all duplicates of current_val in arr1
while i < len1 and arr1[i] == current_val:
common_elements.append(arr1[i])
i += 1
# Move j past all duplicates of current_val in arr2
while j < len2 and arr2[j] == current_val:
j += 1
elif arr1[i] < arr2[j]:
i += 1
else:
j += 1
return common_elements
Explanation
Initialization: The pointers i and j start at the beginning of arr1 and arr2 respectively.
Comparison Loop: The loop runs while both pointers are within their array bounds.
Equal Elements: When elements at arr1[i] and are equal, the code collects all occurrences of this element in (including duplicates) and appends them to the result list. The pointer is moved past all duplicates of this element in , and the pointer is moved past all duplicates of this element in .
arr2[j]
arr1
i
arr1
j
arr2
Smaller Element in arr1: If the current element in arr1 is smaller, the pointer i is incremented to check the next element in arr1.
Smaller Element in arr2: If the current element in arr2 is smaller, the pointer j is incremented to check the next element in arr2.
Termination: The loop exits when either pointer reaches the end of its array, ensuring all common elements, including duplicates, are collected.
This approach ensures that all occurrences of common elements are included in the result, matching the expected output [2, 2, 2, 4] for the given test case.