Day 16 Problem

Binary Search Introduction

Hello and welcome back brave human being,

Before we dig into the problem, I’m going to confess that this topic intimidated me before I understood it. I used to avoid it at all costs and thought it was only for geniuses.

But it isn’t.

Once you understand binary search you’ll start incorporating it everywhere.

What is the problem asking for?

A binary search problem can be identified with the golden keywords: “maximum” or “minimum”.

This technique aims to reduce the time complexity of a linear search. Since a linear search iterates a data structure and evaluates each element, resulting in an O(N) time complexity.

So, binary search might sound a bit overwhelming, but it's not as bad as it seems, so bear with me.

A binary search cuts the time complexity of a search to O(log n). It does it disregarding half of the array based on the set conditions.

Our introductory problem is going to be:

Given a sorted array and a target, write a function to search the target. If the target exists, then return its index. Otherwise, return -1.

Let's set an example…

Input: nums = [-1,0,3,5,9,12], target = 9

Output: 4

Explanation: 9 exists in nums and its index is 4

Here is to tackling our first binary search problem!

Denisse

Reply

or to participate.