713541. Last cell in a Matrix

Easy

Last Cell in a Matrix

Summary

Given an m x n matrix, find the last cell that contains a valid value. A cell is considered invalid if its value is zero. The problem requires you to traverse the entire matrix and return the coordinates (row, column) of the last non-zero cell.

Detailed Explanation

To solve this problem, we can use a simple row-major traversal approach. We start from the top-right corner of the matrix and move towards the bottom-left corner until we find the first zero value or reach the end of the matrix.

Here's a step-by-step breakdown:

  1. Initialize two pointers row and col to the top-right corner of the matrix (i.e., (m-1, n-1)).
  2. Traverse the matrix in a row-major order, starting from the top-right corner.
  3. For each cell, check if its value is non-zero. If it's zero, break out of the loop and return the current coordinates as the last valid cell.
  4. If we reach the end of the matrix without finding a zero value, return the original coordinates (m-1, n-1).

The time complexity of this solution is O(m * n), where m is the number of rows and n is the number of columns in the matrix. The space complexity is O(1) as we only use a few extra variables to store the row and column indices.

Here's an ASCII art diagram illustrating the traversal:

  +--------+
  |        |
  |  *   *  |
  |  *   *  |
  |  *   *  |
  +--------+

In this example, * represents a non-zero value. We start from the top-right corner (*) and move towards the bottom-left corner.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] lastCell(int[][] matrix) {
    int m = matrix.length;
    int n = matrix[0].length;
    int row = m - 1;
    int col = n - 1;

    while (row >= 0 && col >= 0) {
        if (matrix[row][col] != 0) {
            return new int[]{row, col};
        }
        row--;
        col--;
    }

    return new int[]{-1, -1}; // not found
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.