Skip to content

Instantly share code, notes, and snippets.

@SandeepAggarwal
Created October 11, 2020 10:58
Show Gist options
  • Save SandeepAggarwal/833f54f54dec6b4cfbbd2f9e10b20b65 to your computer and use it in GitHub Desktop.
Save SandeepAggarwal/833f54f54dec6b4cfbbd2f9e10b20b65 to your computer and use it in GitHub Desktop.
Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number.
import UIKit
import PlaygroundSupport
func findSubArrayWhoseCountMatches(targetValue: Int, in array: [Int]) -> [Int] {
var sum = 0
var startIndex = 0
for index in 0..<array.count {
sum = sum + array[index]
while sum > target {
sum = sum - array[startIndex]
startIndex = startIndex + 1
}
if sum == target {
return [startIndex, index]
}
}
return []
}
let arr = [1, 4, 20, 3, 10, 5]
let target = 33
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