What data structure / algorithm should be used to find which section a given section is in, given the list of endpoints for each section?
For example, if I have a web page with section headings and content,
- Introduction (ends at 100 pixels)
- Section 1 (ends with 350px)
- Section 2 (ends at 700 pixels)
- Conclusion (ends at 1200 pixels)
- comments
and I'm at 130px now, it should be back, which Iβm now in the "Section 1" section.
Option 1
Binary search on an array of endpoints
from bisect import bisect_left arr = [100, 350, 700, 1200] pos = bisect_left(arr, 130, 0, arr[-1])
However, it can still take O (log n) for each change of position.
Option 2
Search the hash table of the current location table,
lookup = {0: "Introduction" 1: "Introduction" ... 10: "Section 1" 11: "Section 1" ... } section = lookup[130/10]
It's fast, but it spends a lot of space
Is there a general data structure / algorithm that deals with this type of problem?
source share