Find Min and Max in Each Row of a Matrix
C and Python programs to find minimum and maximum elements in each row of a matrix. Includes algorithm, complexity analysis, and placement test variations.
Given a 2D matrix, finding the minimum and maximum element in each row is a single-pass traversal problem that appears regularly in AMCAT and CoCubes placement coding sections.
The task: for every row in an n×m matrix, output the smallest and largest value in that row. It tests whether you can correctly initialise running extremes and update them in one sweep, without needing a sorted copy or a second pass.
What the Problem Asks
Input is a matrix of integers with n rows and m columns. For each row, the output is a pair: the minimum element and the maximum element.
Sample input and output:
- Input: 3 rows, 3 columns
- Matrix:
1 4 9
3 5 1
2 8 5
- Expected output:
Row 0: min = 1, max = 9
Row 1: min = 1, max = 5
Row 2: min = 2, max = 8
The example contains a key observation: in Row 1, the minimum (1) is the last element, not the first. The algorithm cannot assume any ordering within a row.
Algorithm: One Pass Per Row
The two-scan approach runs one pass to find the minimum and a second pass to find the maximum. That is correct but doubles the work. A single pass does both simultaneously.
Steps:
- Step 1: Read n (rows) and m (columns).
- Step 2: Read all matrix elements into a 2D array.
- Step 3: For each row i from 0 to n-1:
- Step 3a: Set
min_val = matrix[i][0]andmax_val = matrix[i][0]. - Step 3b: For each column j from 1 to m-1, check both conditions:
- If
matrix[i][j]is less thanmin_val, updatemin_val. - If
matrix[i][j]is greater thanmax_val, updatemax_val.
- If
- Step 3c: Print or store
min_valandmax_valfor row i.
- Step 3a: Set
Initialising to matrix[i][0] (rather than to 0 or INT_MAX) means the algorithm handles negative integers and all-identical rows without any special-case logic. A row like [-5, -3, -8] initialises min_val = max_val = -5 and updates correctly from there.
Worked trace for Row 1 (values: 3, 5, 1):
- Initialise:
min_val = 3,max_val = 3 - j=1, element=5: 5 is greater than
max_val(3), somax_val = 5; 5 less thanmin_val(3)? No. - j=2, element=1: 1 is less than
min_val(3), somin_val = 1; 1 greater thanmax_val(5)? No. - Result: min = 1, max = 5. Matches expected output.
C Implementation
The program reads matrix dimensions and elements, then finds each row’s minimum and maximum with one inner loop.
#include <stdio.h>
int main() {
int n, m;
printf("Enter rows and columns: ");
scanf("%d %d", &n, &m);
int a[n][m];
printf("Enter matrix elements:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
scanf("%d", &a[i][j]);
printf("\nRow\tMin\tMax\n");
for (int i = 0; i < n; i++) {
int min_val = a[i][0];
int max_val = a[i][0];
for (int j = 1; j < m; j++) {
if (a[i][j] < min_val) min_val = a[i][j];
if (a[i][j] > max_val) max_val = a[i][j];
}
printf("%d\t%d\t%d\n", i, min_val, max_val);
}
return 0;
}
For the 3×3 sample input, output is:
Row Min Max
0 1 9
1 1 5
2 2 8
The inner loop starts at j = 1 because index 0 is already the initialised value. Starting at 0 would not produce a wrong answer, but it adds one redundant comparison per row.
Python Implementation
The Python version uses the same logic. The manual traversal is shown first because proctored and written placement tests often prohibit built-in function calls.
def row_min_max(matrix):
for i, row in enumerate(matrix):
min_val = row[0]
max_val = row[0]
for val in row[1:]:
if val < min_val:
min_val = val
if val > max_val:
max_val = val
print(f"Row {i}: min={min_val}, max={max_val}")
matrix = [
[1, 4, 9],
[3, 5, 1],
[2, 8, 5]
]
row_min_max(matrix)
Output:
Row 0: min=1, max=9
Row 1: min=1, max=5
Row 2: min=2, max=8
The built-in shortcut for the same result is [(min(row), max(row)) for row in matrix]. Both produce identical output for any valid input. The shortcut works well for production code and most online judges. Paper-based campus rounds at Tier-2 and Tier-3 colleges, and some proctored CoCubes tests, still require writing out the traversal logic explicitly.
Time and Space Complexity
Each element is visited exactly once across the two nested loops: one iteration per element regardless of whether it updates min, max, both, or neither.
| Metric | Value | Notes |
|---|---|---|
| Time complexity | O(n×m) | One pass over all n×m elements |
| Space (print-only) | O(1) | Two variables per row, reused each iteration |
| Space (store results) | O(n) | If collecting all (min, max) pairs into an output list |
The two-scan alternative has the same asymptotic time complexity but a higher constant factor:
- Single pass per row: n×(m-1) total comparisons across the matrix.
- Two scans per row: 2×n×(m-1) total comparisons across the matrix.
- For a 1,000-row by 1,000-column matrix: single pass makes roughly 999,000 comparisons; two scans make roughly 1,998,000.
In a timed placement coding section, that constant difference shows up when input sizes push toward the upper constraint limit.
For a broader treatment of how O(1) and O(n) space are categorised and when the distinction matters in interviews, see FACE Prep’s space complexity guide.
Common Variations in Placement Rounds
Placement coding tests extend the row-wise min/max problem in three common directions.
Column-wise min and max. Swap the loop indices: the outer loop iterates over columns (index j from 0 to m-1), and the inner loop iterates over rows (index i from 0 to n-1). Initialise min_val = max_val = matrix[0][j] at the start of each outer iteration.
Finding which row contains the global minimum. Maintain two extra variables outside the row loop: global_min and global_min_row. After updating min_val for a row, compare it to global_min and record the row index if it is smaller.
Returning results as a data structure. Instead of printing, return a list of tuples or a dictionary. In Python: {i: (min(row), max(row)) for i, row in enumerate(matrix)} produces a row-indexed dictionary. In C, store results in two separate arrays of length n.
Two related problems that use the same running-state pattern: finding all symmetric pairs in an array and finding the equilibrium index of an array. Both require maintaining a running variable that updates on each element visit, the same mental model as min_val and max_val here.
GeeksforGeeks covers the column-wise variant with additional discussion on optimised approaches for sparse matrices.
The single-pass logic in this problem (one initialisation, one update loop, one output step per row) is the same structural pattern behind vocabulary frequency scans in LLM tokeniser preprocessing, where a 50,000-entry vocabulary replaces the 3×3 matrix. TinkerLLM is a ₹299 sandbox where that pattern becomes concrete, with no GPU setup or environment configuration required.
Primary sources
Frequently asked questions
What is the time complexity of finding min and max in each row?
O(n×m) where n is the number of rows and m the number of columns. Each element is visited exactly once in a single traversal.
Can I use Python's built-in min() and max() for this problem?
Yes, min(row) and max(row) work correctly on a list. Campus placement written tests often require the manual traversal algorithm, so know both approaches.
How is row-wise min/max different from the global matrix minimum and maximum?
Row-wise finds the smallest and largest value per row independently. Global min/max finds the single smallest and largest value across the entire matrix, ignoring row boundaries.
What is the space complexity of this algorithm?
O(1) if you print results after each row. If you store all row results in output arrays, space complexity becomes O(n) for those arrays.
Do AMCAT and CoCubes ask matrix problems in their coding sections?
Yes. Row-wise and column-wise traversal problems appear in the AMCAT coding section and CoCubes technical screens, typically as warm-up problems before harder algorithmic questions.
What is the efficient way to find both min and max in a single pass?
Initialise both min and max to row[0], then iterate from index 1. Check both conditions for each element in sequence. This avoids a second full scan of the row.
What edge cases should I handle in this problem?
A row with a single element (min equals max), rows with all identical elements, and matrices containing negative integers. Initialising to row[0] rather than 0 or INT_MAX handles all these correctly.
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 (₹299 launch)