Skip to content

Instantly share code, notes, and snippets.

@MorrisLaw
Last active June 29, 2022 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorrisLaw/03c39a43513397f7d8dc021137169a22 to your computer and use it in GitHub Desktop.
Save MorrisLaw/03c39a43513397f7d8dc021137169a22 to your computer and use it in GitHub Desktop.
running sum
// O(n) time, O(n) space
func runningSum(nums []int) []int {
if len(nums) <= 1 { return nums }
var result []int // O(n) space complexity
result = append(result, nums[0])
for i := 1; i < len(nums); i++ { // O(n) time complexity
result = append(result, nums[i]+(result[i-1]))
}
return result
}
// O(n) time, O(1) space
func runningSum(nums []int) []int {
if len(nums) <= 1 { return nums }
runSum := nums[0]
for i := 1; i < len(nums); i++ { // O(n) time complexity
nums[i-1] = runSum
runSum += nums[i]
}
nums[len(nums)-1] = runSum
return nums
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment