/303. Range Sum Query - Immutable

303. Range Sum Query - Immutable

Easy
Arrays71.6% acceptance

Given an integer array data, implement a class ArraySumQuery with two methods: (1) __init__(self, data: List[int]) initializes the object with the array data; (2) sum_range(self, start_index: int, end_index: int) returns the sum of elements from start_index to end_index inclusive. Multiple queries may be performed. All indices are valid and satisfy 0 <= start_index <= end_index < len(data).

Example 1

Input: data = [4, -3, 7, 2, -6, 5] queries = [(1, 3), (0, 5), (2, 4)]

Output: [6, 9, 3]

Explanation: sum_range(1,3): -3+7+2=6; sum_range(0,5): 4-3+7+2-6+5=9; sum_range(2,4): 7+2-6=3

Example 2

Input: data = [10, 20, 30, 40] queries = [(0, 1), (2, 3), (1, 2)]

Output: [30, 70, 50]

Explanation: sum_range(0,1): 10+20=30; sum_range(2,3): 30+40=70; sum_range(1,2): 20+30=50

Constraints

  • 1 <= len(data) <= 10_000
  • -100_000 <= data[i] <= 100_000
  • 0 <= start_index <= end_index < len(data)
  • At most 10_000 calls to sum_range
Python (current runtime)

Case 1

Input: data = [1, 2, 3, 4, 5] queries = [(0, 2), (1, 4), (3, 3)]

Expected: [6, 14, 4]

Case 2

Input: data = [-10, 5, 0, 7, -2] queries = [(0, 4), (1, 3), (2, 2)]

Expected: [0, 12, 0]

Case 3

Input: data = [100] queries = [(0, 0)]

Expected: [100]