Skip to content

Conversation

moonjs0113
Copy link

Prefix Sum

Description

This is a Prefix Sum implementation in Swift.
The code provides the same performance and functionality as the Python code below.
Prefix Sum in Python

Additionally, it returns nil when the values of start and end are not within a valid index range.

guard (0..<length ~= start) && (0..<length ~= end) && (start <= end) else {
    return nil
}

I have declared it as a generic type.

To enable the use of the + operation and the Set,
I have restricted it to types that adopt the AdditiveArithmetic and Hashable protocols.

The comments are written in the style of Apple Developer Documentation.
This is the first PR for this repository. I appreciate your consideration.🙇‍♂️

Code

final class PrefixSum<T: AdditiveArithmetic & Hashable> {
    public var array: [T]
    public var prefixSum: [T]

    init(array: [T]) {
        let length = array.count
        self.array = array
        self.prefixSum = Array(repeating: T.zero, count: length)
        if length > 0 {
            self.prefixSum[0] = array[0]
            for i in 1..<length {
                self.prefixSum[i] = self.prefixSum[i-1] + array[i]
            }
        }
    }

    public func getSum(start: Int, end: Int) -> T? {
        let length = array.count
        guard (0..<length ~= start) && (0..<length ~= end) && (start <= end) else {
            return nil
        }
        return self.prefixSum[end] - (start == 0 ? T.zero : self.prefixSum[start - 1])
    }

    public func containsSum(targetSum: T) -> Bool {
        var sumSet: Set<T> = [T.zero]
        for sumItem in self.prefixSum {
            if sumSet.contains(sumItem - targetSum) {
                return true
            }
            sumSet.insert(sumItem)
        }
        return false
    }
}

@moonjs0113
Copy link
Author

Also, I could not find contributing guidelines for the Swift repository.
If there are any guidelines I should review, please let me know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant