Summed Matrix

Last Updated : 6 Sep, 2026

Given two integers and q, consider a n * n matrix where the value of each cell (i, j) is i + j, with both row and column indices starting from 1. Return the number of cells whose value is equal to q.

Note: The matrix uses 1-based indexing.

Examples:

Input: n = 4, q = 7
Output: 2
Explanation: Matrix becomes [[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]. The count of 7 is 2. Hence, the answer is 2.

Input: n = 5, q = 4
Output: 3
Explanation: Matrix becomes [[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10]]. The count of 4 is 3. Hence, the answer is 3.

Try It Yourself
redirect icon

[Naive Approach] Brute Force Approach - O(n^2) Time and O(1) Space

The simplest idea is to simulate the entire n × n matrix. For every cell (i, j), its value is i + j. Therefore, we check every cell and increment the count whenever its value is equal to q.

  • Initialize count = 0.
  • Traverse every row i from 1 to n.
  • For every row, traverse every column j from 1 to n.
  • Calculate the value of the current cell as i + j.
  • If i + j == q, increment count.
  • Return count.
C++
#include <bits/stdc++.h>
using namespace std;

// Returns the number of cells whose value is equal to q.
int sumMatrix(int n, int q)
{
    // Stores the number of cells having value q.
    int count = 0;

    // Traverse all rows.
    for (int i = 1; i <= n; i++)
    {
        // Traverse all columns.
        for (int j = 1; j <= n; j++)
        {
            // Check if the current cell has value q.
            if (i + j == q)
            {
                count++;
            }
        }
    }

    // Return the total count.
    return count;
}

int main()
{
    int n = 4;
    int q = 7;

    cout << sumMatrix(n, q) << endl;

    return 0;
}
Java
class GFG {
    static int sumMatrix(int n, int q)
    {
        // Stores the number of cells having value q.
        int count = 0;

        // Traverse all rows.
        for (int i = 1; i <= n; i++) {
            
            // Traverse all columns.
            for (int j = 1; j <= n; j++) {
                
                // Check if the current cell has value q.
                if (i + j == q) {
                    count++;
                }
            }
        }

        // Return the total count.
        return count;
    }

    public static void main(String[] args)
    {
        int n = 4;
        int q = 7;

        System.out.println(sumMatrix(n, q));
    }
}
Python
# Returns the number of cells whose value is equal to q.
def sumMatrix(n, q):
    # Stores the number of cells having value q.
    count = 0

    # Traverse all rows.
    for i in range(1, n + 1):
        
        # Traverse all columns.
        for j in range(1, n + 1):
            
            # Check if the current cell has value q.
            if i + j == q:
                count += 1

    # Return the total count.
    return count


# Driver Code
if __name__ == "__main__":
    n = 4
    q = 7

    print(sumMatrix(n, q))
C#
using System;

class GFG {
    static int sumMatrix(int n, int q)
    {
        // Stores the number of cells having value q.
        int count = 0;

        // Traverse all rows.
        for (int i = 1; i <= n; i++) {
            
            // Traverse all columns.
            for (int j = 1; j <= n; j++) {
                
                // Check if the current cell has value q.
                if (i + j == q) {
                    count++;
                }
            }
        }

        // Return the total count.
        return count;
    }

    static void Main()
    {
        int n = 4;
        int q = 7;

        Console.WriteLine(sumMatrix(n, q));
    }
}
JavaScript
// Returns the number of cells whose value is equal to q.
function sumMatrix(n, q)
{
    // Stores the number of cells having value q.
    let count = 0;

    // Traverse all rows.
    for (let i = 1; i <= n; i++) {
        
        // Traverse all columns.
        for (let j = 1; j <= n; j++) {
            
            // Check if the current cell has value q.
            if (i + j === q) {
                count++;
            }
        }
    }

    // Return the total count.
    return count;
}

// Driver Code
let n = 4;
let q = 7;

console.log(sumMatrix(n, q));

Output
2

[Better Approach] Row Wise Calculation - O(n) Time and O(1) Space

For each row, there can be at most one cell whose value is q. Therefore, instead of checking all n columns, directly calculate the required column and check whether it exists.

For a fixed row i: i + j = q

So, the required column is: j = q - i

Therefore, we only need to check whether this column lies within the valid range 1 to n.

  • Initialize count = 0.
  • Traverse each row i from 1 to n.
  • Calculate the required column as j = q - i.
  • If j lies between 1 and n, increment count.
  • Return count.
C++
#include <bits/stdc++.h>
using namespace std;

// Returns the number of cells whose value is equal to q.
int sumMatrix(int n, int q)
{
    // Stores the number of cells having value q.
    int count = 0;

    // Traverse all rows.
    for (int i = 1; i <= n; i++)
    {
        // Calculate the column required to make the cell value q.
        int j = q - i;

        // Check if the required column is within the matrix.
        if (j >= 1 && j <= n)
        {
            count++;
        }
    }

    // Return the total count.
    return count;
}

int main()
{
    int n = 4;
    int q = 7;

    cout << sumMatrix(n, q) << endl;

    return 0;
}
Java
class GFG {
    static int sumMatrix(int n, int q)
    {
        // Stores the number of cells having value q.
        int count = 0;

        // Traverse all rows.
        for (int i = 1; i <= n; i++) {
            // Calculate the column required to make the
            // cell value q.
            int j = q - i;

            // Check if the required column is within the
            // matrix.
            if (j >= 1 && j <= n) {
                count++;
            }
        }

        // Return the total count.
        return count;
    }

    public static void main(String[] args)
    {
        int n = 4;
        int q = 7;

        System.out.println(sumMatrix(n, q));
    }
}
Python
# Returns the number of cells whose value is equal to q.
def sumMatrix(n, q):

    # Stores the number of cells having value q.
    count = 0

    # Traverse all rows.
    for i in range(1, n + 1):
        # Calculate the column required to make the cell value q.
        j = q - i

        # Check if the required column is within the matrix.
        if j >= 1 and j <= n:
            count += 1

    # Return the total count.
    return count


# Driver Code
if __name__ == "__main__":
    n = 4
    q = 7

    print(sumMatrix(n, q))
C#
using System;

class GFG {
    static int sumMatrix(int n, int q)
    {
        // Stores the number of cells having value q.
        int count = 0;

        // Traverse all rows.
        for (int i = 1; i <= n; i++) {
            // Calculate the column required to make the
            // cell value q.
            int j = q - i;

            // Check if the required column is within the
            // matrix.
            if (j >= 1 && j <= n) {
                count++;
            }
        }

        // Return the total count.
        return count;
    }

    static void Main()
    {
        int n = 4;
        int q = 7;

        Console.WriteLine(sumMatrix(n, q));
    }
}
JavaScript
// Returns the number of cells whose value is equal to q.
function sumMatrix(n, q)
{
    // Stores the number of cells having value q.
    let count = 0;

    // Traverse all rows.
    for (let i = 1; i <= n; i++) {
        // Calculate the column required to make the cell
        // value q.
        let j = q - i;

        // Check if the required column is within the
        // matrix.
        if (j >= 1 && j <= n) {
            count++;
        }
    }

    // Return the total count.
    return count;
}

// Driver Code
let n = 4;
let q = 7;

console.log(sumMatrix(n, q));

Output
2

[Expected Approach] Using Mathematical Observation - O(1) Time and O(1) Space

The idea is to solve the problem directly by finding how many valid pairs (i, j) satisfy:

i + j = q.

Since, j = q - i

and both row and column indices must lie between 1 and n, we need:

1 ≤ i ≤ n and 1 ≤ q - i ≤ n.

From the second condition: q - n ≤ i ≤ q - 1

Combining both ranges, the valid values of i are:

max(1, q - n) ≤ i ≤ min(n, q - 1).

Every valid value of i corresponds to exactly one valid column j. Therefore, the number of valid values in this range is the answer.

  • Find the smallest valid row index using low = max(1, q - n).
  • Find the largest valid row index using high = min(n, q - 1).
  • If low > high, no valid cell exists, so return 0.
  • Otherwise, the number of valid rows is high - low + 1.
  • Return this count.
C++
#include <bits/stdc++.h>
using namespace std;

// Returns the number of cells whose value is equal to q.
int sumMatrix(int n, int q)
{
    // Find the valid range of row indices.
    int low = max(1, q - n);
    int high = min(n, q - 1);

    // No valid row exists.
    if (low > high)
    {
        return 0;
    }

    // Number of valid rows (and hence cells).
    return high - low + 1;
}

int main()
{
    int n = 4;
    int q = 7;

    cout << sumMatrix(n, q) << endl;

    return 0;
}
Java
class GFG {
    static int sumMatrix(int n, int q)
    {
        // Find the valid range of row indices.
        int low = Math.max(1, q - n);
        int high = Math.min(n, q - 1);

        // No valid row exists.
        if (low > high) {
            return 0;
        }

        // Number of valid rows (and hence cells).
        return high - low + 1;
    }

    public static void main(String[] args)
    {
        int n = 4;
        int q = 7;

        System.out.println(sumMatrix(n, q));
    }
}
Python
# Returns the number of cells whose value is equal to q.
def sumMatrix(n, q):
    # Find the valid range of row indices.
    low = max(1, q - n)
    high = min(n, q - 1)

    # No valid row exists.
    if low > high:
        return 0

    # Number of valid rows (and hence cells).
    return high - low + 1


# Driver Code
if __name__ == "__main__":
    n = 4
    q = 7

    print(sumMatrix(n, q))
C#
using System;

class GFG {
    static int sumMatrix(int n, int q)
    {
        // Find the valid range of row indices.
        int low = Math.Max(1, q - n);
        int high = Math.Min(n, q - 1);

        // No valid row exists.
        if (low > high) {
            return 0;
        }

        // Number of valid rows (and hence cells).
        return high - low + 1;
    }

    static void Main()
    {
        int n = 4;
        int q = 7;

        Console.WriteLine(sumMatrix(n, q));
    }
}
JavaScript
// Returns the number of cells whose value is equal to q.
function sumMatrix(n, q)
{
    // Find the valid range of row indices.
    let low = Math.max(1, q - n);
    let high = Math.min(n, q - 1);

    // No valid row exists.
    if (low > high) {
        return 0;
    }

    // Number of valid rows (and hence cells).
    return high - low + 1;
}

// Driver Code
let n = 4;
let q = 7;

console.log(sumMatrix(n, q));

Output
2
Comment