Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created August 16, 2022 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theabbie/51b194667e2a132a4460496e87f57bcb to your computer and use it in GitHub Desktop.
Save theabbie/51b194667e2a132a4460496e87f57bcb to your computer and use it in GitHub Desktop.
Sparse Table Implementation in Python
def genSparse(arr):
n = len(arr)
k = len("{:b}".format(n))
table = [[float('inf')] * k for _ in range(n)]
for l in range(k):
for i in range(n):
if l == 0:
table[i][l] = arr[i]
else:
a = table[i][l - 1]
b = float('inf')
if i + (1 << l - 1) < n:
b = table[i + (1 << l - 1)][l - 1]
table[i][l] = min(a, b)
return table
def getMin(table, l, r):
bits = "{:b}".format(r - l)[::-1]
res = float('inf')
for i, b in enumerate(bits):
if b == "1":
res = min(res, table[l][i])
l += 1 << i
return res
arr = [10, 2, 8, 7, 5, 7, 3, 4, 1, 6]
table = genSparse(arr)
print(getMin(table, 1, 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment