Learn
Exam

Sum of Specific Sections

Difficulty
STARTER

Problem

Given an array of integers numbers and an array sections containing the start and end indices of intervals, write a function solution that returns an array of the sums of numbers for each interval specified in sections in the order they appear.


Constraints

  • The length of numbers is between 1 and 100 inclusive.
  • Each element in numbers is an integer between -100 and 100 inclusive.
  • The length of sections is between 1 and 500 inclusive.
  • Each sections[i] is in the form [start, end] where:
    • start denotes the starting index of the interval.
    • end denotes the ending index of the interval.
    • 0 ≤ start ≤ end < length of numbers.

Test Case

Test Case Number numbers sections return
1 [1,2,3,4,5] [[0,1],[2,4]] [3,12]
2 [-1,-2,-3,-4,-5,-6,-7] [[0,3],[2,5],[1,6]] [-10,-18,-27]
3 [10,-10,10,-10,10,20,-20,30,-30,40] [[0,9],[1,5],[6,6]] [50,20,-20]

Explanation for Test Case 1

  • When numbers = [1,2,3,4,5] and sections = [[0,1],[2,4]]:
    1. For the first interval [0,1], numbers[0] + numbers[1] = 1 + 2 = 3.
    2. For the second interval [2,4], numbers[2] + numbers[3] + numbers[4] = 3 + 4 + 5 = 12.
    3. The result is [3,12].

Explanation for Test Case 2

  • When numbers = [-1,-2,-3,-4,-5,-6,-7] and sections = [[0,3],[2,5],[1,6]]:
    1. For the first interval [0,3], numbers[0] + numbers[1] + numbers[2] + numbers[3] = -1 + -2 + -3 + -4 = -10.
    2. For the second interval [2,5], numbers[2] + numbers[3] + numbers[4] + numbers[5] = -3 + -4 + -5 + -6 = -18.
    3. For the third interval [1,6], numbers[1] + numbers[2] + numbers[3] + numbers[4] + numbers[5] + numbers[6] = -2 + -3 + -4 + -5 + -6 + -7 = -27.
    4. The result is [-10,-18,-27].

Explanation for Test Case 3

  • When numbers = [10,-10,10,-10,10,20,-20,30,-30,40] and sections = [[0,9],[1,5],[6,6]]:
    1. For the first interval [0,9], the sum is 10 - 10 + 10 - 10 + 10 + 20 - 20 + 30 - 30 + 40 = 50.
    2. For the second interval [1,5], the sum is -10 + 10 - 10 + 10 + 20 = 20.
    3. For the third interval [6,6], the sum is -20.
    4. The result is [50,20,-20].