LeetCode, ๐ƒ๐š๐ฒ-20/365-DSA-Coding ๐‰๐จ๐ฎ๐ซ๐ง๐ž๐ฒโ€ฆGoogle Prepโ€ฆ

Aaqib Ali
3 min readJan 20, 2025

--

Today I Learned This Problem: First Complete Row or Column in a Matrix

Problem Overview

The problem involves determining the first instance in a sequence of numbers (arr) that completes an entire row or column in a given 2D matrix (mat). Each row and column in the matrix must be filled with elements from arr to qualify as "complete." The task is to find the index in arr where this happens for the first time.

This problem is a practical exercise in efficient mapping, grid traversal, and algorithmic optimization.

Challenges Involved

  1. Mapping Matrix Elements
    Efficiently linking each matrix element to its position within the matrix is crucial for quick access when processing elements from the array.
  2. Dynamic Row and Column Tracking
    Managing counters for rows and columns to dynamically track progress toward completion while minimizing redundant calculations.
  3. Optimal Performance
    Ensuring that the solution processes all elements in arr in linear time relative to its size, without unnecessary iterations over the matrix.

Explanation

To solve the problem, we take advantage of efficient data structures and step-by-step processing. Hereโ€™s the breakdown:

  1. Matrix Element Mapping
    Create a dictionary to map each value in the matrix to its (row, column) position. This allows for constant-time lookup of matrix coordinates for any element in arr.
  2. Initialize Row and Column Counters
    Use two separate arrays to count how many elements in each row and column have been covered. These counters dynamically track progress as we iterate through arr.
  3. Process Each Element in arr
    For each number in arr:
  • Retrieve its corresponding (row, column) from the mapping dictionary.
  • Increment the counters for its row and column.
  • Check if either the row or column is now fully covered. If so, return the current index.

4.Return the Result
The first index where either a row or a column is completed is the answer. If no row or column is completed (though this is unlikely in guaranteed solutions), return 0 as a fallback.

My Solution Approach

Initialization

  1. Create a dictionary to map matrix elements to their positions.
  2. Initialize two lists to track row and column coverage.

Iterate Through Array

  1. For each element in arr, find its position in the matrix.
  2. Update the corresponding row and column counters.
  3. Check if a row or column becomes fully covered.

Terminate Early

  1. As soon as a row or column is complete, return the current index.

Python Code

class Solution:
def firstCompleteIndex(self, arr, mat):
n, m = len(mat), len(mat[0])
rowcol = {mat[i][j]: (i, j) for i in range(n) for j in range(m)}
row, col = [0] * n, [0] * m

for i, num in enumerate(arr):
r, c = rowcol[num]
row[r] += 1
col[c] += 1
if row[r] == m or col[c] == n:
return i

return 0

Other Possible Solutions

  1. Brute Force
    Check the entire matrix for completion after processing each element in arr. This approach is highly inefficient and impractical for larger matrices and arrays.
  2. Alternative Data Structures
    Using sets instead of counters to track the elements seen in each row or column. This can simplify implementation but may add overhead for frequent set operations.

Learnings

  1. Efficient Mapping
    Mapping elements to their positions in a matrix simplifies lookup operations and reduces computational overhead.
  2. Dynamic Tracking
    Using counters for rows and columns enables real-time updates and eliminates the need for redundant checks.
  3. Optimized Grid Processing
    Leveraging both the matrix structure and the sequence of operations ensures that only necessary computations are performed.

Real-Life Applications

  1. Inventory Management
    Tracking completion of orders or stock levels in rows and columns of a warehouse grid.
  2. Game Mechanics
    Implementing row or column-based scoring in grid-based games like bingo or Sudoku.
  3. Data Visualization
    Highlighting completed rows or columns in heatmaps or matrix visualizations.

To Sum Up

This problem is an excellent example of using efficient data structures to solve matrix traversal challenges. By focusing on mapping, tracking, and iteration, we achieve a solution that is both performant and easy to implement. Let me know your thoughts or alternative approaches in the comments!

--

--

No responses yet