My Swift Solution with a Dictionary Explained


  • 0
    B

    This is my Swift solution.

    func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool {
            // Key is number, value is an array of indices index
            var dictionary = [Int: [Int]]()
            for (i, number) in nums.enumerated() {
                if let duplicateIndexes = dictionary[number] {
                    // Number is duplicate, check for index distance with all the previous indeces
                    for duplicateIndex in duplicateIndexes {
                        let distance = abs(duplicateIndex - i)
                        if distance <= k {
                            return true
                        }
                    }
                    // Append this index if it wasn't in the correct distance
                    dictionary[number]?.append(i)
                } else {
                    // Create new array with the first index found
                    dictionary[number] = [i]
                }
            }
            return false
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.