Skip to content

Commit a86f085

Browse files
author
tarunkukreja003
committed
Time: 112 ms (52.70%), Space: 14.4 MB (93.48%) - LeetHub
1 parent 22acb02 commit a86f085

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from heapq import heapify, heappop, heappush
2+
3+
class Solution:
4+
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
5+
# sort according to the number of -> time complexity = for n rows -> nlogn
6+
# space complexity -> n because we are storing the tuple of number of soldiers in row i and index of i
7+
8+
# min heap
9+
10+
# when we do extract min element and we then we do getMin -> we compare whether they are equal or not, if they are then we check their indices, if the index of getMin is less than the popped element then we do another extarctMin and we place the index of recent pop before the one popped
11+
12+
# or maintain min heap according to two parameters -> first priority is number of soldiers and the second is the index if the number of soldiers in a row is same
13+
14+
heap = []
15+
16+
heapify(heap)
17+
18+
for i in range(len(mat)):
19+
soldierCount = 0
20+
for j in range(len(mat[0])):
21+
if mat[i][j] == 1:
22+
soldierCount += 1
23+
heappush(heap, (soldierCount, i))
24+
25+
26+
27+
28+
kWeakestRowsIndices = []
29+
30+
while k > 0:
31+
numberOfSoldiers, index = heappop(heap)
32+
kWeakestRowsIndices.append(index)
33+
k -= 1
34+
35+
return kWeakestRowsIndices
36+
37+
38+
39+

0 commit comments

Comments
 (0)