<jupyter_start><jupyter_text>1337. The K Weakest Rows in a MatrixDifficulty: **Easy**You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.A row i is weaker than a row j if one of the following is true:* The number of soldiers in row i is less than the number of soldiers in row j.* Both rows have the same number of soldiers and i < j.Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.<jupyter_code>from typing import List
def kWeakestRows(mat: List[List[int]], k: int) -> List[int]:
    scores = sorted(range(len(mat)), key=lambda row: sum(mat[row]))
    return scores[:k]<jupyter_output><empty_output><jupyter_text>Using binary search and a heap* We make the counting of 1's efficient by using a binary search. We search for the index of the first element with a zero. Because ones are at the beginning of the row finding the leftmost zero gives the number of ones in a row. Binary search reduces the Complexity from `O(n)` to `O(logn)`.* The use of a heap reduces the space complexity to `O(k)` from `O(m)` as we need to keep track of only the `k` smallest rows.<jupyter_code>from heapq import heapify, heappush, heappushpop, heappop

def bsearch(row):
    left, right = 0, len(row)-1
    
    while left<=right:
        mid = left+(right-left)//2
        if row[mid] == 1:
            left = mid+1
        else:
            right = mid-1

    return left
    
def kWeakestRows_bsearch(mat: List[List[int]], k: int) -> List[int]:
    scores = []
    heapify(scores)
    
    for i, row in enumerate(mat):
        ones = bsearch(row)
        item = (-ones, -i)
        if len(scores) < k:
            heappush(scores, item)
        else:
            heappushpop(scores, item)
    
    res = []
    while scores:
        res.append(-heappop(scores)[1])
    
    return res[::-1]<jupyter_output><empty_output><jupyter_text>Examples<jupyter_code>mat1 = [[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]] 
k1 = 3

kWeakestRows(mat1, k1)
kWeakestRows_bsearch(mat1, k1)
mat2 = [[1,0,0,0],
 [1,1,1,1],
 [1,0,0,0],
 [1,0,0,0]]
k2 = 2<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11808278867102397, 'fraction_numerical': 0.02962962962962963, 'mean_word_length': 3.3984674329501914, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '205328', 'license': 'Apache-2.0', 'n_tokens_mistral': 823, 'n_tokens_neox': 786, 'n_words': 286, 'path': 'leetcode/1337_k_weakest_rows.ipynb', 'repo_name': 'Kaushalya/algo_journal', 'size': '2295'}