Number of Sum Pairs in an Array using Swift - iOS Coding Challenge

Let's Code :


Remember we have to pass sorted array to this function :


func numberOfSumPair(sortedArray : [Int] , key : Int) -> Int {
    var startPointer = 0
    var endPointer = sortedArray.count - 1
    var sumPairs = 0
    if sortedArray.count < 2 {
        return sumPairs
    }
    while startPointer < endPointer {
        let sum = sortedArray[startPointer] + sortedArray[endPointer]
        if sum == key {
            print("Pairs : \(sortedArray[startPointer]) + \(sortedArray[endPointer])")
            sumPairs += 1
            startPointer += 1
        }
        if sum > key {
            endPointer -= 1
        }
        if sum < key {
            startPointer += 1
        }
        
    }
    
    return sumPairs
}

Let's call this function now :

let arr : [Int] = [10,2,5,-1,3,6,9,-2,20,12,11,45,19,22,1,10]
print("Input Array : \(arr)")

let sortedArray = arr.sorted()
print("Sorted Array : \(sortedArray)")

let num = numberOfSumPair(sortedArray: sortedArray,key: 20)
print("Num : \(num)")

So here is the result, we are trying to find '20' :



Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications