Similar Problems

Similar Problems not available

Delete Greatest Value In Each Row - Leetcode Solution

Companies:

LeetCode:  Delete Greatest Value In Each Row Leetcode Solution

Difficulty: Easy

Topics: matrix heap-priority-queue array sorting simulation  

The problem "Delete Greatest Value In Each Row" on Leetcode is as follows:

Given a matrix, each row is sorted in non-decreasing order. Delete the greatest value in each row. Return the resulting matrix sorted row-wise in non-decreasing order.

Example 1: Input: [[5, 3, 2, 4], [1, 6, 4, 2], [9, 7, 8, 3]] Output: [[2, 3, 4], [1, 2, 4], [3, 7, 8, 9]] Explanation: Before deleting, the matrix is: [[5, 3, 2, 4], [1, 6, 4, 2], [9, 7, 8, 3]] After deleting, the matrix becomes: [[2, 3, 4], [1, 2, 4], [3, 7, 8, 9]] Then we sort the matrix row-wise and get: [[2, 3, 4], [1, 2, 4], [3, 7, 8, 9]]

Solution:

The problem can be solved by iterating through the matrix row-wise and deleting the maximum value in each row. Then, sort the matrix row-wise to get the desired output.

The steps for the solution are:

Step 1: Iterate through the matrix row-wise and delete the maximum value in each row. Step 2: Sort the matrix row-wise.

Let's see how to implement these steps in Python.

Step 1: Iterate through the matrix row-wise and delete the maximum value in each row.

We can iterate through the matrix row-wise using a for loop. For each row, we can find the index of the maximum value using the index() function, and delete that value using the pop() function.

Here's the Python code for step 1:

n_rows = len(matrix)
for i in range(n_rows):
    max_val = max(matrix[i])
    max_idx = matrix[i].index(max_val)
    matrix[i].pop(max_idx)

Step 2: Sort the matrix row-wise.

We can sort the matrix row-wise using the sorted() function with the key argument set to lambda x: x[0]. This sorts the matrix based on the first element of each row.

Here's the final Python code for the problem:

class Solution:
    def deleteGreatestValueInEachRow(self, matrix: List[List[int]]) -> List[List[int]]:
        # Iterate through the matrix row-wise and delete the maximum value in each row
        n_rows = len(matrix)
        for i in range(n_rows):
            max_val = max(matrix[i])
            max_idx = matrix[i].index(max_val)
            matrix[i].pop(max_idx)

        # Sort the matrix row-wise
        sorted_matrix = sorted(matrix, key=lambda x: x[0])

        return sorted_matrix

This solution has a time complexity of O(n^2 log n), where n is the number of elements in the matrix. The max() function and the sorted() function both have a time complexity of O(n log n), and we use both functions twice in the solution.

Delete Greatest Value In Each Row Solution Code

1