Prefix sum using hash map

Hello guys, I am currently transitioning from java to swift, I cant turn the java code below to swift using the prefix sum and hash map. Can someone pls assist me ?

Given an array of integers, both -ve and +ve, find a contiguous subarray that sums to 0.For example: [2,4,-2,1,-3,5,-3] --> [4,-2,1,-3]

public void findSumZeroSubArrays( int [] arr) {

Map<Integer, Integer> sumMap = new HashMap<Integer, Integer>();

Integer sum = 0 ;

for ( int i = 0 ; i < arr.length; i++) {

sum += arr[i];

if (sum == 0 ) {

printSubArray(arr, 0 , i);

}

if (sumMap.get(sum) != null ) {

printSubArray(arr, sumMap.get(sum) + 1 , i);

} else {

sumMap.put(sum, i);

}

}

}

@lexypaul13 I tried to do a 1 to 1 translation. I hope it helps.

func findSumZeroSubArrays(_ array: [Int]) {
    var sumMap = [Int: Int]()
    var sum = 0

    for i in 0..<array.count {
        sum += array[i]

        if sum == 0 {
            printSubArrays(array, 0, i)
        }

        if let j = sumMap[sum] {
            printSubArrays(array, j + 1, i)
        } else {
            sumMap[sum] = i
        }
    }
}

func printSubArrays(_ array: [Int], _ start: Int, _ end: Int) {
    print(array[start...end])
}

findSumZeroSubArrays([2,4,-2,1,-3,5,-3])
/*
[4, -2, 1, -3]
[1, -3, 5, -3]
*/
1 Like

Thank you so much Francois. Your solution is beautiful and elegant; Can you please explain what this syntax means sumMap[sum] = I?

sumMap[sum] = i is the Swift equivalent to sumMap.put(sum, i). You can use the subscript notation to both get and set values. You can find more in the Collection Types section of the Swift Programming Language Guide.

1 Like