How to find intersection of two sorted array

[Question] In given two sorted arrays find intersection.
// Ex–>    A: [1 2 3 3 4 5 6] , B: [3 3 5] Output: 3,3,5
#Approach: // TC O(n) // SC O(1)

func findIntersactionOfElements(array1: [Int], array2: [Int]) -> [Int] {
    let firstLength = array1.count
    let secondLength = array2.count
    var i = 0, j = 0
    var intersactionArray: [Int] = []
    
    while i < firstLength && j < secondLength {
        // Intersaction means elements are equal so we just compare i & j
        if array1[i] == array2[j] {
            intersactionArray.append(array1[i])
            i+=1
            j+=1
        } else  if array1[i] < array2[j] {
            i+=1
        } else  {
            j+=1
        }
    }
            
    return intersactionArray
}
let firstArray = [1, 2, 3, 3, 4, 5, 6]
let secondArray = [3,3,5]

let intersactionArray = findIntersactionOfElements(array1: firstArray, array2: secondArray)
print("intersactionArray-Array->", intersactionArray)

Leave a Comment

Your email address will not be published. Required fields are marked *