arcbjorn

thoughtbook

RSS Feed

Monday, February 20, 2023

Range sum query - immutable

Leetcode 303 problem.

Go

  • Time complexity: O(n)O(n) - n is a length of an array
  • Auxiliary space: O(1)O(1) - constant amount of space
type NumArray struct {
    nums []int
}


func Constructor(nums []int) NumArray {
    return NumArray{
        nums: nums,
    }
}


func (this *NumArray) SumRange(left int, right int) int {
    sum := 0

    for i := left; i <= right; i++ {
        sum += this.nums[i]
    }

    return sum
}


/**
 * obj := Constructor(nums);
 * param_1 := obj.SumRange(left,right);
 */

Typescript

  • Time complexity: O(n)O(n) - n is a length of an array
  • Auxiliary space: O(1)O(1) - constant amount of space
class NumArray {
    nums: number[];

    constructor(nums: number[]) {
        this.nums = nums;
    }

    sumRange(left: number, right: number): number {
        let sum = 0;

        for (let i = left; i <= right; i++) {
            sum += this.nums[i];
        }

        return sum;
    }
}
Creative Commons Licence