rewrite using binary search