Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Why do we need:if (low > 0) { return low - 1;}in our binary search?

Alberto Young

Apr 8, 2022

Why do we need:

if (low > 0) { return low - 1; }

in our binary search?

2

0

Comments
Comments
A
Alberto Young4 years ago

Looks like solution is giving incorrect output for the following testcase:

[0,0,1,2,3,3,4,7,7,8] 3 5

Design Gurus
Design Gurus4 years ago

What output are you seeing and what did you expect?

S
Shan 3 years ago

Output [3,4,7] Expected [3,3,4]

Design Gurus
Design Gurus3 years ago

Both outputs are correct as both "3" and "7" are at an equal distance from "5".

S
Shan 3 years ago

Given the following rules: An integer a is closer to x than an integer b if:

|a - x| < |b - x|, or |a - x| == |b - x| and a < b

This means 3,3,4 would be correct and 3,4,7 would not be correct.

Source: [https://leetcode.com/problems/find-k-closest-elements/](https://...

S
Shan 3 years ago

2 recommendations to pass on leetcode:

  1. remove the following from the binarySearch method, its not necessary, low is always pointing to the closest number: if (low > 0) { return low - 1; }

  2. The sort on priority queue should have a fallback in the case n1.key == n2...

Design Gurus
Design Gurus3 years ago

Yes, we don't this following restriction |a - x| == |b - x| and a < b

What it meant is that if the absolute difference of two numbers is the same then include the smaller number.

The solution you proposed looks correct if we have to include the restriction.

On this page