Created
October 11, 2020 11:59
-
-
Save SandeepAggarwal/76fe5d9077f75bdec265f46fc2f69184 to your computer and use it in GitHub Desktop.
Given an unsorted array of integers, find a subarray which adds to a given number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
func findSubArrayWhoseCountMatches(targetValue: Int, in array: [Int]) -> [Int] { | |
var sum = 0 | |
var hashMap = [Int: Int]() | |
for index in 0..<array.count { | |
sum = sum + array[index] | |
if sum == target { | |
return [0, index] | |
} | |
if let valueIndex = hashMap[sum - targetValue] { | |
let startIndex = valueIndex + 1 | |
return [startIndex, index] | |
} | |
hashMap[sum] = index | |
} | |
return [] | |
} | |
let arr = [10, 2, -2, -20, 10] | |
let target = 0 | |
let subArrayIndexes = findSubArrayWhoseCountMatches(targetValue: target, in: arr) | |
print(subArrayIndexes) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment