|
| 1 | +import heapq |
| 2 | + |
| 3 | +def find_k_weakest_rows(matrix, k): |
| 4 | + |
| 5 | + # Get the number of rows and columns in matrix |
| 6 | + m = len(matrix) |
| 7 | + n = len(matrix[0]) |
| 8 | + |
| 9 | + # Helper function to perform binary search on each row |
| 10 | + def binary_search(row): |
| 11 | + |
| 12 | + low = 0 |
| 13 | + high = n |
| 14 | + |
| 15 | + while low < high: |
| 16 | + mid = low + (high - low) // 2 |
| 17 | + |
| 18 | + if row[mid] == 1: |
| 19 | + low = mid + 1 |
| 20 | + else: |
| 21 | + high = mid |
| 22 | + |
| 23 | + return low |
| 24 | + |
| 25 | + # Priority queue (min-heap) to store k weakest rows |
| 26 | + pq = [] |
| 27 | + |
| 28 | + for i, row in enumerate(matrix): |
| 29 | + strength = binary_search(row) |
| 30 | + entry = (-strength, -i) |
| 31 | + |
| 32 | + # Add row to heap |
| 33 | + if len(pq) < k or entry > pq[0]: |
| 34 | + heapq.heappush(pq, entry) |
| 35 | + |
| 36 | + # Remove strongest row from heap |
| 37 | + if len(pq) > k: |
| 38 | + heapq.heappop(pq) |
| 39 | + |
| 40 | + # Extract the k weakest rows from the heap |
| 41 | + indexes = [] |
| 42 | + |
| 43 | + while pq: |
| 44 | + strength, i = heapq.heappop(pq) |
| 45 | + indexes.append(-i) |
| 46 | + |
| 47 | + # Reverse order from weakest to strongest |
| 48 | + indexes = indexes[::-1] |
| 49 | + return indexes |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +# Time Complexity = O(mlognk) |
| 54 | +# Space Complexity = O(k) |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | +################################################################## |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | +def main(): |
| 63 | + matrix_list = [ |
| 64 | + [[1, 1, 0, 0, 0], [1, 1, 1, 1, 0], [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1]], |
| 65 | + [[1, 1, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1], [1, 1, 0, 0]], |
| 66 | + [[1, 1], [1, 1], [0, 0], [1, 0], [1, 1]], |
| 67 | + [[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 1], [1, 0, 0, 0]], |
| 68 | + [[1, 0, 0], [0, 0, 0], [1, 1, 1], [1, 1, 0]] |
| 69 | + ] |
| 70 | + k_values = [2, 3, 3, 2, 1] |
| 71 | + |
| 72 | + for i in range(len(matrix_list)): |
| 73 | + print(f"{i + 1}.\tInput matrix: \n\tmatrix = {matrix_list[i]}\n\tk = {k_values[i]}") |
| 74 | + weakest_rows = find_k_weakest_rows(matrix_list[i], k_values[i]) |
| 75 | + print(f"\n\tIndexes of the {k_values[i]} weakest rows: {weakest_rows}") |
| 76 | + print("-" * 100) |
| 77 | + |
| 78 | +if __name__ == '__main__': |
| 79 | + main() |
0 commit comments