Given that both arrays are already sorted, you can efficiently subset the larger array to contain only elements found in the smaller array using a two-pointer technique. This approach is optimal for sorted arrays and operates in linear time, O(n + m), where n and m are the lengths of the two arrays.
Approach
- Initialize two pointers: One for the larger array (
i) and one for the smaller array (j).
- Traverse both arrays:
- If the current element in the larger array is equal to the current element in the smaller array, include it in the result and move both pointers forward.
- If the current element in the larger array is smaller, move the larger array's pointer forward.
- If the current element in the larger array is larger, move the smaller array's pointer forward.
- Collect the results: The elements where both pointers meet are the elements present in both arrays.
Solution Code
def subset_larger_array(larger, smaller):
i = j = 0
result = []
len_larger = len(larger)
len_smaller = len(smaller)
while i < len_larger and j < len_smaller:
if larger[i] == smaller[j]:
result.append(larger[i])
i += 1
j += 1
elif larger[i] < smaller[j]:
i += 1
else:
j += 1
return result
Explanation
- Initialization: The pointers
i and j start at the beginning of the larger and smaller arrays, respectively.
- Traversal: The loop continues as long as both pointers are within their array bounds. The comparison between elements at the current pointers determines the next step:
- Equal Elements: If
larger[i] equals smaller[j], the element is added to the result list, and both pointers are incremented to check the next elements.
- Smaller Element in Larger Array: If
larger[i] is smaller than smaller[j], the pointer i is incremented to move to the next element in the larger array, as the current element cannot be in the smaller array (since both arrays are sorted).
- Larger Element in Larger Array: If
larger[i] is larger than smaller[j], the pointer j is incremented to move to the next element in the smaller array, as the current element in the smaller array is not present in the larger array at this position.
- Result Collection: The result list accumulates all elements found in both arrays during the traversal, which is then returned.
This method efficiently leverages the sorted property of both arrays to minimize the number of comparisons, making it optimal for this problem.