intersection
sorted arrays
algorithms
array manipulation
data structures

The intersection of two sorted arrays

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In computer science, the intersection of two sorted arrays is a common problem that often arises in various applications like database management, search engines, and data analysis. The intersection refers to the set of elements that appear in both input arrays. This article delves into different methods to achieve this intersection efficiently, considering the inherent sorted nature of the input arrays.

Problem Statement

Given two sorted arrays, find the intersection of these arrays with each element appearing as many times as it shows in both arrays. The result should also be sorted.

Algorithmic Approaches

Two-Pointer Technique

The most efficient method for finding the intersection of two sorted arrays involves using the Two-Pointer Technique. This method leverages the fact that the arrays are already sorted, allowing us to traverse both arrays simultaneously.

Algorithm

  1. Initialize two pointers, i for the first array and j for the second array, both starting at the beginning (zero index).
  2. While both pointers are within the bounds of their respective arrays:
    • If arr1[i] < arr2[j] , increment i .
    • If arr1[i] > arr2[j] , increment j .
    • If arr1[i] == arr2[j] , record the element (as it is part of the intersection) and increment both i and j .
  3. Continue until you reach the end of either array.

Example

Consider two sorted arrays:

  • arr1 = [1, 2, 4, 5, 6]
  • arr2 = [2, 3, 5, 7]

Using the two-pointer technique:

  • Start with i = 0 and j = 0 .
  • Compare arr1[0] and arr2[0] , i.e., 1 and 2 .
  • Since 1 < 2 , increment i to 1 .
  • Now, arr1[1] is 2 and arr2[0] is still 2 .
  • Elements are equal, record 2 , increment both i and j .
  • The process continues until the end of both arrays, resulting in the intersection [2, 5] .

Time and Space Complexity

  • Time Complexity: O(n+m)O(n + m), where n and m are the lengths of the two arrays. Each element is visited at most once.
  • Space Complexity: O(1)O(1), excluding the space required for the output.

Binary Search Method

For cases where the sizes of the arrays are significantly different, a binary search approach might be more efficient. This approach iteratively performs a binary search for elements of the smaller array in the larger array, ensuring that the complexity remains manageable.

Algorithm

  1. Iterate through each element of the smaller array.
  2. For each element, apply binary search on the larger array.
  3. If a match is found, include the element in the result set.

Time Complexity Analysis

  • Time Complexity: O(nlogm)O(n \log m) or O(mlogn)O(m \log n), depending on which array is smaller.
  • Space Complexity: O(1)O(1), similar to the two-pointer technique.

Implementation Notes

When implementing these algorithms, edge cases such as empty arrays and arrays with no intersection must be considered. Both approaches can be adapted to handle these without additional overhead.

Comparison Table

MethodTime ComplexitySpace ComplexitySuitable for
Two-PointerO(n+m)O(n + m)O(1)O(1)Arrays of similar size (both sorted)
Binary SearchO(nlogm)O(n \log m)O(1)O(1)Arrays of different sizes (both sorted)

Additional Considerations

Unsorted Arrays

For unsorted arrays, the above methods are not directly applicable without first sorting the arrays. This can be done using a sorting algorithm like Merge Sort, which will add an O(nlogn)O(n \log n) complexity to the entire process. Alternatively, hash-based methods can be used to achieve a balance between time and space efficiency.

Duplicate Handling

If the arrays contain duplicates, both of the aforementioned methods inherently handle duplicates by checking equality before recording an element as part of the intersection.

Practical Applications

  • Database Systems: Determining common records between tables.
  • Search Engines: Finding common terms between different documents.
  • Data Analysis Tools: Intersecting categories or tags between datasets to find commonalities.

Understanding the intersection of two sorted arrays is crucial in many fields where data efficiency and manipulation are critical. By leveraging the sorted property of arrays, the two-pointer and binary search methods offer efficient and scalable solutions to this problem.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.