Skip to main content

Find minimum element of each row in a matrix

The problem to be tackled involves finding the minimum element in each row of a given matrix. A matrix is a two-dimensional array with rows and columns, and the goal is to determine and display the smallest element in each row.

Problem Statement

Given a matrix with dimensions ROW x COL, where each element is an integer, the objective is to find the minimum element in each row and display those minimum values.

Example

Consider the following matrix:

1  -1  2  3
4   8  1  4
3   4  2  0
2   5  3  3
6   3  5  7

The minimum elements in each row are: -1, 1, 0, 2, and 3.

Idea to Solve

Find minimum element in matrix rows

To solve this problem, iterate through each row of the matrix and identify the minimum element in that row. Initialize a variable to store the minimum element for each row and update it while traversing the row.

Pseudocode

Here's the pseudocode for the algorithm:

function minimumByRow(matrix):
    for i from 0 to ROW-1:
        min_element = matrix[i][0] // Initialize min_element with the first element of the row
        for j from 1 to COL-1:
            if matrix[i][j] < min_element:
                min_element = matrix[i][j] // Update min_element if a smaller element is found
        print min_element

Algorithm Explanation

  1. Define a function minimumByRow that takes a 2D matrix matrix as its input.
  2. Initialize a loop that iterates through each row of the matrix from 0 to ROW-1 (inclusive).
  3. Inside the outer loop, initialize a variable min_element with the value of the first element in the current row (matrix[i][0]).
  4. Implement an inner loop that starts from 1 and iterates through each column of the current row (from 1 to COL-1).
  5. Within the inner loop, compare the current element (matrix[i][j]) with min_element. If the current element is smaller than min_element, update min_element with the value of the current element.
  6. After the inner loop completes, print the value of min_element, representing the minimum element in the current row.
  7. The outer loop advances to the next row, and the process repeats until all rows are processed.

Code Solution

Time Complexity

The time complexity of this algorithm is O(ROW * COL), where ROW is the number of rows in the matrix and COL is the number of columns. The algorithm iterates through each element of the matrix exactly once to find the minimum element in each row. The nested loops contribute to the complexity.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment