Learn
Exam

Row Traversal for a Specific Range in a Two-Dimensional Array

Difficulty
BEGINNER

Problem

Given a n x m two-dimensional array numbers, a start index start, and an end index end, write a function solution that returns the sum of all elements within the range from start to end by row traversal.

Row traversal refers to traversing a two-dimensional array in a horizontal direction row by row.

start and end are defined as follows:

  • start = [sx,sy] (sx is the starting row, sy is the starting column)
  • end = [ex,ey] (ex is the ending row, ey is the ending column)

For example, given the following numbers, start, and end:

numbers = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]

start = [1,1]
end = [2,0]

The sum of the elements from (1,1) to (2,0) in numbers is calculated as: numbers[1][1] + numbers[1][2] + numbers[2][0] = 5 + 6 + 7 = 18.


Constraints

  • The dimensions of numbers (n and m) are between 1 and 50 inclusive.
  • Each element numbers[i][j] is a natural number between 1 and 100 inclusive.
  • The row indices of the range satisfy 0 ≤ sx ≤ ex < n.
  • The column indices of the range satisfy 0 ≤ sy, ey < m. Additionally, if sx == ex, then sy ≤ ey.

Test Case

Test Case Number numbers start end return
1 [[1,2,3],[4,5,6],[7,8,9]] [1,1] [2,0] 18
2 [[10,20],[30,40]] [0,0] [1,1] 100
3 [[5]] [0,0] [0,0] 5

Explanation for Test Case 1

  • For numbers=[[1,2,3],[4,5,6],[7,8,9]], start=[1,1], and end=[2,0]:
    1. The row traversal path is numbers[1][1] → numbers[1][2] → numbers[2][0].
    2. The sum of these elements is 5 + 6 + 7 = 18.
    3. The function returns 18.

Explanation for Test Case 2

  • For numbers=[[10,20],[30,40]], start=[0,0], and end=[1,1]:
    1. The row traversal path is numbers[0][0] → numbers[0][1] → numbers[1][0] → numbers[1][1].
    2. The sum of these elements is 10 + 20 + 30 + 40 = 100.
    3. The function returns 100.

Explanation for Test Case 3

  • For numbers=[[5]], start=[0,0], and end=[0,0]:
    1. The row traversal path includes only the single element numbers[0][0].
    2. The sum of this element is 5.
    3. The function returns 5.