Find the largest index with prefix(i) <= value in O(lg N) NOTE: Requires that all values are non-negative! Parameters: value (int): value to find the largest index of Returns: -1: if value is smaller than all elements in prefix sum
(self, value: int)
| 196 | return self.query(index, index + 1) |
| 197 | |
| 198 | def rank_query(self, value: int) -> int: |
| 199 | """ |
| 200 | Find the largest index with prefix(i) <= value in O(lg N) |
| 201 | NOTE: Requires that all values are non-negative! |
| 202 | |
| 203 | Parameters: |
| 204 | value (int): value to find the largest index of |
| 205 | |
| 206 | Returns: |
| 207 | -1: if value is smaller than all elements in prefix sum |
| 208 | int: largest index with prefix(i) <= value |
| 209 | |
| 210 | >>> f = FenwickTree([1, 2, 0, 3, 0, 5]) |
| 211 | >>> f.rank_query(0) |
| 212 | -1 |
| 213 | >>> f.rank_query(2) |
| 214 | 0 |
| 215 | >>> f.rank_query(1) |
| 216 | 0 |
| 217 | >>> f.rank_query(3) |
| 218 | 2 |
| 219 | >>> f.rank_query(5) |
| 220 | 2 |
| 221 | >>> f.rank_query(6) |
| 222 | 4 |
| 223 | >>> f.rank_query(11) |
| 224 | 5 |
| 225 | """ |
| 226 | value -= self.tree[0] |
| 227 | if value < 0: |
| 228 | return -1 |
| 229 | |
| 230 | j = 1 # Largest power of 2 <= size |
| 231 | while j * 2 < self.size: |
| 232 | j *= 2 |
| 233 | |
| 234 | i = 0 |
| 235 | |
| 236 | while j > 0: |
| 237 | if i + j < self.size and self.tree[i + j] <= value: |
| 238 | value -= self.tree[i + j] |
| 239 | i += j |
| 240 | j //= 2 |
| 241 | return i |
| 242 | |
| 243 | |
| 244 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected