# LeetCode: Binary Search Solution

Classic problem

## Approach

Given that the array is sorted ascending

Compare the middle element with

target

• if greater than, continue searching on the left
• if smaller than, continue searching on the right
• else we are done

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var search = function (nums, target) {2  const n = nums.length3  let lo = 04  let hi = n - 15  let res = -16
7  while (lo <= hi) {8    let mid = Math.floor((lo + hi) / 2)9    if (nums[mid] > target) {10      hi = mid - 111    } else if (nums[mid] < target) {12      lo = mid + 113    } else {14      res = mid15      break16    }17  }18
19  return res20}```

## References

Codility's Material

LeetCode's official solution

Original problem

leetcode

array

binary search

## Next Post

Sep 13, 2021

Luckily, mid calculation in JS did not throw overflow error

## Previous Post

LeetCode: Reverse Prefix of Word

Sep 12, 2021

Substring manipulating

Search Posts