Skip to content

Latest commit

 

History

History
23 lines (20 loc) · 789 Bytes

File metadata and controls

23 lines (20 loc) · 789 Bytes

1.4.12 Write a program that, given two sorted arrays of N int values, prints all elements that appear in both arrays, in sorted order. The running time of your program should be proportional to N in the worst case.

Solution: maintain two indices for each array. Because they are sorved we can compare values and increase less valued array. If values identical just print them and increase both indices.

func printDuplicates(a: [Int], b: [Int]) {
    var aIndex = 0
    var bIndex = 0

    while aIndex < a.count, bIndex < b.count {
        if a[aIndex] == b[bIndex] {
            print(a[aIndex])
            aIndex += 1
            bIndex += 1
        }
        if a[aIndex] < b[bIndex] {
            aIndex += 1
        } else {
            bIndex += 1
        }
    }
}