Data Structure Binary Search Practice Questions with Solutions

Introduction

Binary Search is an efficient searching technique used to find an element in a sorted array. Instead of checking every element one by one, it repeatedly divides the search range into two halves. In this chapter, we will practice Binary Search through practical JavaScript questions. The exercises cover basic searching, missing elements, duplicate values, insertion positions, and reusable Binary Search functions. Data Structure Binary Search Practice Questions with Solutions help to understand the concpezts.

Question 1: Find an Element Using Binary Search

Questions

Use Binary Search to find 40 in the sorted array.

let numbers = [10, 20, 30, 40, 50, 60];
let target = 40;

Solution

let numbers = [10, 20, 30, 40, 50, 60];
let target = 40;

let left = 0;
let right = numbers.length - 1;
let position = -1;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        position = mid;
        break;
    }

    if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

console.log("Position:", position);

Output

Position: 3

The value 40 is found at index 3.


Question 2: Search for an Element That Does Not Exist

Questions

Use Binary Search to check whether 35 exists in the sorted array.

let numbers = [10, 20, 30, 40, 50];

Solution

let numbers = [10, 20, 30, 40, 50];
let target = 35;

let left = 0;
let right = numbers.length - 1;
let found = false;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        found = true;
        break;
    }

    if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

console.log("Found:", found);

Output

Found: false

Since 35 is not present, the search eventually ends without finding it.


Question 3: Create a Binary Search Function

Questions

Create a reusable binarySearch() function that returns the index of the target element.

let numbers = [5, 15, 25, 35, 45, 55];

Solution

function binarySearch(array, target) {
    let left = 0;
    let right = array.length - 1;

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);

        if (array[mid] === target) {
            return mid;
        }

        if (array[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1;
}

let numbers = [5, 15, 25, 35, 45, 55];

console.log(binarySearch(numbers, 45));

Output

4

The function returns 4 because 45 is located at index 4.


Question 4: Count the Number of Search Steps

Questions

Use Binary Search to find 90 and count how many comparisons are required.

let numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90];

Solution

let numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90];
let target = 90;

let left = 0;
let right = numbers.length - 1;
let steps = 0;
let position = -1;

while (left <= right) {
    steps++;

    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        position = mid;
        break;
    }

    if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

console.log("Position:", position);
console.log("Steps:", steps);

Output

Position: 8
Steps: 4

Binary Search finds the element in only a few comparisons because the search area keeps getting divided.


Question 5: Find the First Occurrence of a Duplicate

Questions

The array contains duplicate values. Use Binary Search to find the first occurrence of 20.

let numbers = [10, 20, 20, 20, 30, 40];

Solution

let numbers = [10, 20, 20, 20, 30, 40];
let target = 20;

let left = 0;
let right = numbers.length - 1;
let firstPosition = -1;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        firstPosition = mid;
        right = mid - 1;
    } else if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

console.log("First occurrence:", firstPosition);

Output

First occurrence: 1

When 20 is found, the search continues toward the left side to check whether another 20 exists earlier.


Question 6: Find the Last Occurrence of a Duplicate

Questions

Use Binary Search to find the last occurrence of 30.

let numbers = [10, 20, 30, 30, 30, 40, 50];

Solution

let numbers = [10, 20, 30, 30, 30, 40, 50];
let target = 30;

let left = 0;
let right = numbers.length - 1;
let lastPosition = -1;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        lastPosition = mid;
        left = mid + 1;
    } else if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

console.log("Last occurrence:", lastPosition);

Output

Last occurrence: 4

After finding 30, the search continues toward the right side to locate a later occurrence.


Question 7: Find the Insertion Position

Questions

Find the correct position where 35 should be inserted into the sorted array while keeping the array sorted.

let numbers = [10, 20, 30, 40, 50];

Solution

let numbers = [10, 20, 30, 40, 50];
let target = 35;

let left = 0;
let right = numbers.length;

while (left < right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid;
    }
}

console.log("Insertion position:", left);

Output

Insertion position: 3

35 should be inserted at index 3.

The resulting array would be:

[10, 20, 30, 35, 40, 50]


Question 8: Search for a Student ID

Questions

Student IDs are stored in sorted order. Use Binary Search to find student ID 104.

let studentIds = [101, 102, 103, 104, 105, 106];

Solution

let studentIds = [101, 102, 103, 104, 105, 106];
let target = 104;

let left = 0;
let right = studentIds.length - 1;
let position = -1;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (studentIds[mid] === target) {
        position = mid;
        break;
    }

    if (studentIds[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

if (position !== -1) {
    console.log("Student found at index:", position);
} else {
    console.log("Student not found");
}

Output

Student found at index: 3


Question 9: Binary Search in a Descending Array

Questions

The array is sorted in descending order. Use Binary Search to find 70.

let numbers = [100, 90, 80, 70, 60, 50, 40];

Solution

let numbers = [100, 90, 80, 70, 60, 50, 40];
let target = 70;

let left = 0;
let right = numbers.length - 1;
let position = -1;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        position = mid;
        break;
    }

    if (numbers[mid] > target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

console.log("Position:", position);

Output

Position: 3

For a descending array, the direction of the search conditions must be reversed compared with an ascending array.


Question 10: Find the Closest Element Using Binary Search

Questions

Use Binary Search to find the element closest to 34.

let numbers = [10, 20, 30, 40, 50];

Solution

let numbers = [10, 20, 30, 40, 50];
let target = 34;

let left = 0;
let right = numbers.length - 1;

while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (numbers[mid] === target) {
        console.log("Closest element:", numbers[mid]);
        break;
    }

    if (numbers[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

if (left > right) {
    if (right < 0) {
        console.log("Closest element:", numbers[left]);
    } else if (left >= numbers.length) {
        console.log("Closest element:", numbers[right]);
    } else {
        let leftDifference = Math.abs(numbers[right] - target);
        let rightDifference = Math.abs(numbers[left] - target);

        if (leftDifference <= rightDifference) {
            console.log("Closest element:", numbers[right]);
        } else {
            console.log("Closest element:", numbers[left]);
        }
    }
}

Output

Closest element: 30

30 is 4 away from 34, while 40 is 6 away, so 30 is the closest element.

Key Takeaways

  • Binary Search works on sorted data.
  • It repeatedly divides the search range into two halves.
  • The middle element is checked during every iteration.
  • If the target is greater than the middle value, search the right half.
  • If the target is smaller, search the left half.
  • Binary Search has O(log n) time complexity.
  • Its best-case time complexity is O(1).
  • Binary Search can be modified to find the first and last occurrence of duplicates.
  • It can also be used to find an insertion position.
  • Binary Search can be adapted for descending-order arrays.
  • The array must be sorted according to the comparison logic being used.

FAQs

1. What is Binary Search?

Binary Search is an efficient searching algorithm that repeatedly divides a sorted search range into two parts to locate a target element.

2. Does Binary Search require a sorted array?

Yes. Standard Binary Search requires the data to be sorted.

3. What is the time complexity of Binary Search?

The time complexity is O(log n) because the search space is reduced by approximately half after every comparison.

4. Can Binary Search work with duplicate values?

Yes. With a modified implementation, Binary Search can find the first or last occurrence of a duplicate value.

5. What is the difference between Linear Search and Binary Search?

Linear Search checks elements one by one and works on unsorted data. Binary Search repeatedly divides a sorted array into halves and is generally much faster for large sorted datasets.

6. Can Binary Search work on a descending array?

Yes. The comparison conditions must be adjusted because the values decrease instead of increase.

7. When should Binary Search be used?

Binary Search is useful when you have sorted data and need to perform searches efficiently, especially when the dataset is large.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top