binary search twice to ensure worst case in O(logn)