easy
0 views

Function matrixSum – CTS PATTERN

Fix syntax errors in the matrixSum function to correctly calculate the sum of all elements in a 2D matrix stored as a 1D array

Understand the Problem

Problem Statement

You are required to correct the syntax of the given code without changing its logic. You can click on Run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.

Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.

The function matrixSum(int *matrix, int m, int n) is supposed to return the sum of elements of the input array matrix having m rows and n columns.

The function looks fine but fails to return the desired result due to compilation and logical errors.

Your task is to fix the program so that it passes all test cases.

Constraints

  • 1 ≤ m ≤ 1000 (number of rows)
  • 1 ≤ n ≤ 1000 (number of columns)
  • Matrix elements are stored in row-major order as a 1D array
  • Matrix pointer is not null
  • Each matrix element can be any integer value
  • Function should handle edge cases where m or n is 1

Examples

Example 1
Input
matrix = [1, 2, 3, 4, 5, 6], m = 2, n = 3
Output
21
Explanation

The matrix is [[1, 2, 3], [4, 5, 6]]. Sum = 1 + 2 + 3 + 4 + 5 + 6 = 21

Example 2
Input
matrix = [10, 20, 30], m = 1, n = 3
Output
60
Explanation

The matrix is [[10, 20, 30]]. Sum = 10 + 20 + 30 = 60

Example 3
Input
matrix = [5, 15], m = 2, n = 1
Output
20
Explanation

The matrix is [[5], [15]]. Sum = 5 + 15 = 20

Solution

int matrixSum(int *matrix, int m, int n)
{
    int i, j, sum = 0;
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            sum += matrix[i * n + j];
        }
    }
    return sum;
}
Time:O(m × n) - The function visits each element of the matrix exactly once
Space:O(1) - Only uses a constant amount of extra space for variables (i, j, sum)
Approach:

Step-by-step explanation:

  1. Function signature: Uses int *matrix to accept a pointer to the first element of the matrix array
  2. Initialize sum: sum = 0 to accumulate the total
  3. Outer loop: Iterates through each row (i from 0 to m-1)
  4. Inner loop: For each row, iterates through each column (j from 0 to n-1)
  5. Array indexing: matrix[i * n + j] correctly calculates the position of element at row i, column j in the 1D array
  6. Accumulate sum: Adds each element to the running total
  7. Return result: Returns the final sum after processing all elements

Visual Explanation

Loading diagram...