Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,848 questions

51,768 answers

573 users

How to merge two sorted arrays without duplicates in Swift

2 Answers

0 votes
func mergeSortedArrays(_ array1: [Int], _ array2: [Int]) -> [Int] {
    var mergedArray = [Int]()
    var set = Set<Int>()
    var i = 0
    var j = 0

    while i < array1.count && j < array2.count {
        if array1[i] < array2[j] {
            if !set.contains(array1[i]) {
                mergedArray.append(array1[i])
                set.insert(array1[i])
            }
            i += 1
        } else if array1[i] > array2[j] {
            if !set.contains(array2[j]) {
                mergedArray.append(array2[j])
                set.insert(array2[j])
            }
            j += 1
        } else {
            if !set.contains(array1[i]) {
                mergedArray.append(array1[i])
                set.insert(array1[i])
            }
            i += 1
            j += 1
        }
    }

    while i < array1.count {
        if !set.contains(array1[i]) {
            mergedArray.append(array1[i])
            set.insert(array1[i])
        }
        i += 1
    }

    while j < array2.count {
        if !set.contains(array2[j]) {
            mergedArray.append(array2[j])
            set.insert(array2[j])
        }
        j += 1
    }

    return mergedArray
}

let array1 = [1, 3, 5, 7, 8]
let array2 = [2, 3, 6, 8, 9, 10]

let result = mergeSortedArrays(array1, array2)

print(result)



/*
run:

[1, 2, 3, 5, 6, 7, 8, 9, 10]

*/

 



answered Apr 26, 2025 by avibootz
0 votes
import Foundation

func mergeSortedArrays(_ arr1: [Int], _ arr2: [Int]) -> [Int] {
    // Combine the two arrays and remove duplicates using a Set
    var mergedSet = Array(Set(arr1 + arr2))
    
    // Sort the array
    mergedSet.sort()
    
    return mergedSet
}

let arr1 = [1, 2, 2, 3, 7, 7, 7, 8, 9]
let arr2 = [0, 0, 4, 4, 4, 5, 6, 7, 7, 8]

let mergedArray = mergeSortedArrays(arr1, arr2)

print(mergedArray.map { String($0) }.joined(separator: ", "))



/*
run:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

*/

 



answered Apr 26, 2025 by avibootz
edited Apr 27, 2025 by avibootz
...