Skip to content

Commit 7522112

Browse files
Synced
2 parents 705e0b0 + b9b5d7a commit 7522112

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//This problem was asked by Goldman Sachs.
2+
//
3+
//Given a list of numbers L, implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j).
4+
//
5+
//For example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return sum([2, 3]), which is 4.
6+
//
7+
//You can assume that you can do some pre-processing. sum() should be optimized over the pre-processing step.
8+
9+
class SumMap{
10+
var list: [Int] = []
11+
var sumAtIndexMap: [Int:Int] = [:]
12+
var sum = 0
13+
var count = 0
14+
15+
func addInt(integer: Int) {
16+
list.append(integer)
17+
sum += integer
18+
sumAtIndexMap[count] = sum
19+
count += 1
20+
}
21+
22+
func getSum(i: Int, j: Int) -> Int {
23+
print(sumAtIndexMap)
24+
if i < list.count, j < list.count {
25+
var ithVal : Int = (sumAtIndexMap[j] ?? 0)
26+
var jthVal : Int = (sumAtIndexMap[i] ?? 0)
27+
print("ithVal: \(ithVal)")
28+
print("jthVal: \(jthVal)")
29+
return ithVal - jthVal
30+
}
31+
return 0
32+
}
33+
}
34+
35+
36+
var sumMap: SumMap = SumMap()
37+
38+
sumMap.addInt(integer: 1) // 0
39+
sumMap.addInt(integer: 2) // 1
40+
sumMap.addInt(integer: 3) // 2
41+
sumMap.addInt(integer: 4) // 3
42+
sumMap.addInt(integer: 5) // 4
43+
44+
var sumVal = sumMap.getSum(i: 2, j: 3)
45+
print("SumVal is \(sumVal)")

Swift/DailyCodingProblemsWithSwift.playground/contents.xcplayground

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@
88
<page name='Day1047'/>
99
<page name='Day1050'/>
1010
<page name='SmallestDifference'/>
11+
<page name='Day1004'/>
1112
</pages>
1213
</playground>

0 commit comments

Comments
 (0)