|
| 1 | +""" |
| 2 | +Meta Binary Search (One-Sided Binary Search) |
| 3 | +
|
| 4 | +Meta Binary Search is a variation of binary search that uses |
| 5 | +bit manipulation to determine the index of the target element |
| 6 | +in a sorted array. Instead of repeatedly dividing the search |
| 7 | +space like traditional binary search, it constructs the index |
| 8 | +bit by bit from the most significant bit to the least. |
| 9 | +
|
| 10 | +Time Complexity: O(log n) |
| 11 | +Space Complexity: O(1) |
| 12 | +
|
| 13 | +Reference: |
| 14 | +https://www.geeksforgeeks.org/meta-binary-search-one-sided-binary-search/ |
| 15 | +""" |
| 16 | + |
| 17 | + |
| 18 | +def meta_binary_search(arr: list[int], target: int) -> int: |
| 19 | + """ |
| 20 | + Perform Meta Binary Search on a sorted list. |
| 21 | +
|
| 22 | + The algorithm determines the index by checking bits from |
| 23 | + the most significant bit down to the least significant bit. |
| 24 | +
|
| 25 | + Parameters |
| 26 | + ---------- |
| 27 | + arr : list[int] |
| 28 | + A sorted list of integers where the search will be performed. |
| 29 | + target : int |
| 30 | + The element to search for. |
| 31 | +
|
| 32 | + Returns |
| 33 | + ------- |
| 34 | + int |
| 35 | + Index of the target element if found, otherwise -1. |
| 36 | +
|
| 37 | + Examples |
| 38 | + -------- |
| 39 | + >>> meta_binary_search([2, 4, 6, 8, 10], 6) |
| 40 | + 2 |
| 41 | + >>> meta_binary_search([2, 4, 6, 8, 10], 7) |
| 42 | + -1 |
| 43 | + >>> meta_binary_search([], 5) |
| 44 | + -1 |
| 45 | + """ |
| 46 | + |
| 47 | + n = len(arr) |
| 48 | + if n == 0: |
| 49 | + return -1 |
| 50 | + |
| 51 | + # Step 1: Find the Most Significant Bit position |
| 52 | + max_idx = n - 1 |
| 53 | + msb_pos = 0 if max_idx == 0 else max_idx.bit_length() - 1 |
| 54 | + |
| 55 | + idx = 0 # Initialize index before using it! |
| 56 | + |
| 57 | + # Step 2: Iterate from MSB down to LSB |
| 58 | + for i in range(msb_pos, -1, -1): |
| 59 | + new_idx = idx | (1 << i) |
| 60 | + |
| 61 | + if new_idx < n and arr[new_idx] <= target: |
| 62 | + idx = new_idx |
| 63 | + |
| 64 | + # Step 3: Final verification |
| 65 | + if idx < n and arr[idx] == target: |
| 66 | + return idx |
| 67 | + return -1 |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + example_array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] |
| 72 | + |
| 73 | + print(meta_binary_search(example_array, 14)) # Expected output: 6 |
| 74 | + print(meta_binary_search(example_array, 5)) # Expected output: -1 |
0 commit comments