Placement Prep

Sum of Boundary Elements of a Matrix: C, C++, Java, Python

Two complete approaches: O(N+M) optimised and O(N×M) check-each, to find the sum of boundary elements of a matrix, in C, C++, Java, and Python.

By FACE Prep Team 6 min read
matrix arrays data-structures coding-interview time-complexity python cpp java

Boundary elements of an N × M matrix are all cells in the first row, last row, first column, and last column. Summing them is a standard DSA warm-up that tests 2D array indexing and loop bounds.

What Are Boundary Elements?

Given a matrix with N rows and M columns, a cell at position (i, j) is a boundary element if any of these conditions hold:

  • i == 0 (first row)
  • i == N-1 (last row)
  • j == 0 (first column)
  • j == M-1 (last column)

All other cells are interior elements. The total count of boundary cells follows directly from the definition. The first and last rows each contribute M cells. The left and right columns each contribute N cells, but the four corners are already counted in the row totals, so subtract 4:

  • Total boundary cells = 2M + 2(N − 2) = 2M + 2N − 4 = 2(N + M) − 4

For a square N × N matrix this simplifies to 4N − 4.

Verify with small examples:

  • 3 × 3, all ones: 2(3 + 3) − 4 = 8 boundary cells, sum = 8.
  • 4 × 4, all ones: 2(4 + 4) − 4 = 12 boundary cells, sum = 12.
  • 1 × 1 single cell: the formula gives 0, but the lone cell is on the boundary. This is the one edge case the formula does not cover. A 1 × 1 matrix has exactly 1 boundary cell.

The canonical 3 × 3 example makes the counting concrete:

Matrix:
1 2 3
4 5 6
7 8 9

Boundary elements: 1, 2, 3 (row 0), 4 (col 0, row 1), 6 (col 2, row 1), 7, 8, 9 (row 2)
Interior element: 5 only
Sum: 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 = 40

Only the single cell at position (1, 1) is interior. For any 3 × 3 matrix, exactly one cell sits in the interior.

The O(N+M) Optimised Approach

Instead of visiting every cell, iterate only the four edges directly. This touches exactly 2(N + M) − 4 cells for an N × M matrix.

The logic in steps:

  • Add all elements of row 0 (first row).
  • Add all elements of row N−1 (last row, if N > 1).
  • For rows 1 through N−2 (middle rows), add only column 0 and column M−1.

No cell is visited twice. Time complexity: O(N + M). Space complexity: O(1).

C

#include <stdio.h>

int boundarySum(int mat[][100], int n, int m) {
    int sum = 0;
    for (int j = 0; j < m; j++)
        sum += mat[0][j];              /* first row */
    if (n > 1) {
        for (int j = 0; j < m; j++)
            sum += mat[n-1][j];        /* last row */
    }
    for (int i = 1; i < n - 1; i++) {
        sum += mat[i][0];              /* left col, interior rows */
        sum += mat[i][m-1];            /* right col, interior rows */
    }
    return sum;
}

int main() {
    int mat[3][100] = {{1,2,3},{4,5,6},{7,8,9}};
    printf("Sum = %d\n", boundarySum(mat, 3, 3));  /* Output: 40 */
    return 0;
}

C++

#include <iostream>
#include <vector>
using namespace std;

int boundarySum(vector<vector<int>>& mat) {
    int n = mat.size(), m = mat[0].size();
    int sum = 0;
    for (int j = 0; j < m; j++)
        sum += mat[0][j];              /* first row */
    if (n > 1) {
        for (int j = 0; j < m; j++)
            sum += mat[n-1][j];        /* last row */
    }
    for (int i = 1; i < n - 1; i++) {
        sum += mat[i][0];              /* left col */
        sum += mat[i][m-1];            /* right col */
    }
    return sum;
}

int main() {
    vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
    cout << "Sum = " << boundarySum(mat) << endl;  /* Output: 40 */
    return 0;
}

The C 2D array documentation on cppreference.com covers the memory layout behind mat[i][j] indexing. It is worth reading if you are debugging boundary conditions in pointer-arithmetic code.

Java

public class BoundarySum {
    static int boundarySum(int[][] mat) {
        int n = mat.length, m = mat[0].length;
        int sum = 0;
        for (int j = 0; j < m; j++)
            sum += mat[0][j];           // first row
        if (n > 1) {
            for (int j = 0; j < m; j++)
                sum += mat[n-1][j];     // last row
        }
        for (int i = 1; i < n - 1; i++) {
            sum += mat[i][0];           // left col
            sum += mat[i][m-1];         // right col
        }
        return sum;
    }

    public static void main(String[] args) {
        int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println("Sum = " + boundarySum(mat));  // Output: 40
    }
}

Python

def boundary_sum(mat):
    n = len(mat)
    m = len(mat[0])
    total = sum(mat[0])                # first row
    if n > 1:
        total += sum(mat[n-1])         # last row
    for i in range(1, n - 1):
        total += mat[i][0]             # left col
        total += mat[i][m-1]           # right col
    return total

mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Sum =", boundary_sum(mat))      # Output: 40

Python’s list-of-lists model means mat[i][j] works the same way as in C and C++, just without explicit type declarations.

The O(N×M) Check-Each Approach

The alternative is to iterate over every cell and add it to the sum only when it sits on a boundary. This is easier to read for beginners because the boundary condition is explicit in the code.

def boundary_sum_check(mat):
    n = len(mat)
    m = len(mat[0])
    total = 0
    for i in range(n):
        for j in range(m):
            if i == 0 or i == n - 1 or j == 0 or j == m - 1:
                total += mat[i][j]
    return total

The same logic in C++:

int boundarySumCheck(vector<vector<int>>& mat) {
    int n = mat.size(), m = mat[0].size();
    int sum = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (i == 0 || i == n-1 || j == 0 || j == m-1)
                sum += mat[i][j];
    return sum;
}

Time complexity: O(N × M), all cells visited. Space complexity: O(1).

A concrete comparison for scale:

  • 3 × 3 matrix: check-each runs 9 iterations; O(N+M) runs 8 (the 8 boundary cells).
  • 1000 × 1000 matrix: check-each runs 1,000,000 iterations; O(N+M) runs 2(1000 + 1000) − 4 = 3,996 iterations.

For large matrices that difference is measurable.

Edge Cases: Single Row, Single Column, Single Cell

Three configurations where the formula and the loop bounds need attention:

1 × M single row

Every cell is in the first row (which is also the last row). Every cell is a boundary element. Both implementations handle this correctly:

  • O(N+M): adds row 0, then checks n > 1 before adding the last row (skipped since N = 1), then the middle-row loop runs 0 times (range 1 to N−2 is empty).
  • O(N×M): every cell satisfies i == 0, so all are added.

N × 1 single column

Every cell satisfies j == 0 and j == M−1 simultaneously (since M = 1). Both implementations add all cells.

1 × 1 single cell

The lone cell is at (0, 0). For the O(N+M) approach:

  • Row 0 adds the cell.
  • n > 1 is false, so row N−1 is skipped.
  • Middle-row loop runs 0 times.
  • Result: the single cell’s value. Correct.

For the O(N×M) approach, i == 0 and j == 0 are both true for (0, 0), so the cell is added exactly once. Correct.

A 4 × 4 example with distinct values to verify manually:

Matrix:
 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16

Boundary elements:
  Row 0: 1, 2, 3, 4
  Row 3: 13, 14, 15, 16
  Left col (rows 1-2): 5, 9
  Right col (rows 1-2): 8, 12

Sum: (1+2+3+4) + (13+14+15+16) + (5+9) + (8+12)
   = 10 + 58 + 14 + 20 = 102

Interior cells 6, 7, 10, and 11 are not touched.

Time and Space Complexity Comparison

ApproachTimeSpaceWhen to use
O(N+M) optimisedO(N + M)O(1)Preferred in interviews; efficient on large matrices
O(N×M) check-eachO(N × M)O(1)Easier to read; fine for small matrices

Both approaches use O(1) auxiliary space (only a running sum variable). The space complexity of algorithms article covers the O(1) vs O(N) distinction in detail with worked examples for sorting and searching.

The boundary-sum pattern generalises. Once you can iterate edges of a 2D array cleanly, spiral matrix traversal and layer-by-layer operations follow naturally. The symmetric pairs in an array problem applies similar two-condition boundary logic to pairs, and the sum of digits program is the 1D analogue where every iteration contributes to a running total.

These matrix problems appear across TCS NQT, Infosys InfyTQ, and AMCAT Automata as coding warm-ups. Solving them correctly under a 30-minute time limit comes down to one thing: clean loop bounds with no off-by-one errors, not algorithmic creativity.

The O(N+M) approach you practised here, iterating only the border cells and skipping the interior, is the same design principle behind context-window management in LLM inference. TinkerLLM at ₹499 is where that connection stops being a footnote: you build and deploy a working LLM project and see boundary-condition reasoning applied in a runtime you control.

Primary sources

Frequently asked questions

What are boundary elements of a matrix?

Boundary elements are all cells in the first row, last row, first column, and last column of the matrix. For an N × M matrix, that is 2(N + M) − 4 cells. The interior cells (those not on any edge) are everything else.

How many boundary elements does a 4 × 4 matrix have?

A 4 × 4 matrix has 4 × 4 − 4 = 12 boundary elements. The formula for a square N × N matrix is 4N − 4. For a non-square N × M matrix the formula is 2(N + M) − 4.

What is the sum of boundary elements of a 3 × 3 matrix with values 1 to 9?

The matrix is [[1,2,3],[4,5,6],[7,8,9]]. Boundary elements are 1, 2, 3 (row 0), 7, 8, 9 (row 2), 4 (col 0 middle), and 6 (col 2 middle). Sum = 1+2+3+7+8+9+4+6 = 40. The only non-boundary element is 5.

What is the time complexity of the optimised boundary sum approach?

O(N + M) time and O(1) space. The algorithm visits only the cells in the first row (M cells), last row (M cells), first column excluding corners (N-2 cells), and last column excluding corners (N-2 cells). Total = 2M + 2N − 4, which is O(N + M).

How do I handle a single-row or single-column matrix for boundary sum?

For a 1 × M matrix, the single row is simultaneously the first and last row, so every cell is a boundary element. Similarly for an N × 1 matrix. The sum equals the sum of all elements. Both code approaches handle this correctly without special-casing.

Is the boundary elements sum problem asked in placement interviews?

Yes, it appears in TCS NQT and AMCAT Automata coding rounds as a matrix warm-up. Interviewers use it to verify that candidates understand 2D array indexing and can reason about loop bounds without off-by-one errors.

What is the difference between O(N+M) and O(N×M) approaches for boundary sum?

The O(N+M) approach iterates only the border cells explicitly: first row, last row, left column interior, right column interior. The O(N×M) approach iterates every cell and checks whether it sits on the boundary using a condition. For large matrices the O(N+M) approach is faster, but both produce the same result.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹499)
Free AI Roadmap PDF