Created
October 11, 2020 12:31
-
-
Save SandeepAggarwal/807767f457e285b5b5d0089ca8e02310 to your computer and use it in GitHub Desktop.
Given an unsorted array of integers, Count number of sub arrays in an array having sum k
This file contains hidden or 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 findAllSubArrayWhoseCountMatches(targetValue: Int, in array: [Int]) -> [[Int]] { | |
var sum = 0 | |
var hashMap = [Int: Int]() | |
var results = [[Int]]() | |
for index in 0..<array.count { | |
sum = sum + array[index] | |
if sum == target { | |
results.append([0, index]) | |
} | |
if let valueIndex = hashMap[sum - targetValue] { | |
let startIndex = valueIndex + 1 | |
results.append([startIndex, index]) | |
} | |
hashMap[sum] = index | |
} | |
return results | |
} | |
let arr = [10, 2, -2, -10, 0] | |
let target = 0 | |
let subArrayIndexes = findAllSubArrayWhoseCountMatches(targetValue: target, in: arr) | |
print(subArrayIndexes) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment