How to find the minimum element of each row in a matrix
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 themin, theminwill be set to the current element. - Finally, the
minfor the row is returned.
- Initially, the first element will be considered the minimum element. The first element will be set as
- Collect all the minimums from the previous step to an array.
- Time Complexity:
O(m*n) - Space Complexity:
O(1)
- Time Complexity:
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));}}