Related Tags

matrix
data structures
communitycreator

# How to find the minimum element of each row in a matrix

abhilash

### Problem overview

Given a m x n matrix, find the minimum element of each row in the matrix.

#### Example:

Matrix:

[[12, 43],
[234, 54],
[642, 687],
[23, 99]]


Result:

[12, 54, 642, 23]


### Algorithm

Every row in a matrix is an array. Hence, we need to find the minimum element of an array.

The steps of the algorithm are as follows:

• For every row in the matrix, perform the following steps:
• Initially, the first element will be considered the minimum element. The first element will be set as min, and then the row will be traversed.
• Each element will be compared with the min, and if the current element is lesser than the min, the min will be set to the current element.
• Finally, the min for the row is returned.
• Collect all the minimums from the previous step to an array.
• Time Complexity: O(m*n)
• Space Complexity: O(1)

### Code

import java.util.Arrays;

public class Main {

private static int minElement(int[] row){
int min = row[0];
for (int i : row) min = Math.min(min, i);
return min;
}

private static int[] minElementRow(int[][] matrix) {
int[] rowMinElements = new int[matrix.length];
int i = 0;
for(int[] row: matrix) {
rowMinElements[i] = minElement(row);
i++;
}
return rowMinElements;
}

public static void main(String[] args) {
int[][] matrix = { {12, 43},
{234, 54},
{642, 687},
{23, 99}
};
int[] maxElements = minElementRow(matrix);
System.out.println("Minimum elements in each row are as follows: ");
System.out.println(Arrays.toString(maxElements));
}
}

RELATED TAGS

matrix
data structures
communitycreator

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time