Day 8 – Binary Search: Variations & Applications

Yesterday, we learned the basic binary search algorithm and implemented it in JavaScript.
Today, we’ll push it further by looking at common variations and real-world problems that use binary search.


  • Works only on sorted arrays.

  • Repeatedly divides the search space in half.

  • Time complexity: O(log n).

  • Space complexity: O(1) for iterative, O(log n) for recursive.


2. Variation 1 – Finding First Occurrence

Sometimes, elements appear multiple times, and we want the first index.

Example:

javascriptCopyEditfunction firstOccurrence(arr, target) {
    let low = 0, high = arr.length - 1;
    let result = -1;

    while (low <= high) {
        let mid = Math.floor((low + high) / 2);

        if (arr[mid] === target) {
            result = mid;
            high = mid - 1; // keep searching left
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return result;
}

console.log(firstOccurrence([1,2,4,4,4,5,6], 4)); // Output: 2

3. Variation 2 – Finding Last Occurrence

Similar logic, but we search right after finding the target.

javascriptCopyEditfunction lastOccurrence(arr, target) {
    let low = 0, high = arr.length - 1;
    let result = -1;

    while (low <= high) {
        let mid = Math.floor((low + high) / 2);

        if (arr[mid] === target) {
            result = mid;
            low = mid + 1; // keep searching right
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return result;
}

console.log(lastOccurrence([1,2,4,4,4,5,6], 4)); // Output: 4

4. Variation 3 – Search in a Rotated Sorted Array

This is a common interview question.

Example problem:
Array [4,5,6,7,0,1,2] is sorted but rotated. Search for 0.

javascriptCopyEditfunction searchRotatedArray(arr, target) {
    let low = 0, high = arr.length - 1;

    while (low <= high) {
        let mid = Math.floor((low + high) / 2);

        if (arr[mid] === target) return mid;

        // Left half is sorted
        if (arr[low] <= arr[mid]) {
            if (target >= arr[low] && target < arr[mid]) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        // Right half is sorted
        else {
            if (target > arr[mid] && target <= arr[high]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
    }
    return -1;
}

console.log(searchRotatedArray([4,5,6,7,0,1,2], 0)); // Output: 4

  • Searching in dictionaries.

  • Autocomplete suggestion systems.

  • Searching for words in spell checkers.

  • Efficient lookups in databases.

  • Finding boundaries (like first bad version in version control).


6. Homework

Easy

Find the first and last occurrence of a target in a sorted array using binary search (combine variation 1 and 2 into one function).

Intermediate

Implement binary search recursively.

Hard

Given a sorted array of unknown size (you can only access it using a get(index) function that returns Infinity if out of bounds), implement binary search.

#CodeWithGift #DSA2025 #JavaScript #DayEight

1
Subscribe to my newsletter

Read articles from God'sgift Samuel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

God'sgift Samuel
God'sgift Samuel

About Me Tech enthusiast and developing web developer with a growing passion for blockchain technology. My journey spans 3 years of HTML/CSS crafting, 2 years of JavaScript exploration, and recent ventures into React, Node.js, and the blockchain space. Currently at the beginning of my blockchain journey while building a solid foundation in web development technologies. Fascinated by the potential of decentralized systems and eager to contribute to this evolving ecosystem. Technical Background I bring a diverse technical toolkit that includes: Strong foundation in web fundamentals (HTML/CSS: 3 years) Dynamic front-end development with JavaScript (2 years) and React (1 year) Modern UI implementation using Tailwind CSS and Bootstrap (7 months) Server-side programming with Node.js (1 year) and Python (2-3 years) Early-stage blockchain development knowledge Beginning exploration of Rust programming (4 months) Blockchain Journey While still at the beginner level in blockchain technology, I'm actively learning about distributed ledger concepts, smart contract fundamentals, and the broader implications of Web3. My interest in this space stems from a belief in the transformative potential of decentralized technologies and their ability to reshape digital interactions. Vision & Goals My development path is guided by a clear progression: mastering web development fundamentals, expanding into blockchain applications, and ultimately exploring the intersection of these technologies with artificial intelligence. I see tremendous potential in combining these domains to create innovative solutions for tomorrow's challenges. Collaboration Interests Open to connecting with fellow developers, blockchain enthusiasts, and mentors who share an interest in the convergence of web development and emerging technologies. Particularly interested in learning opportunities, knowledge exchange, and potential collaboration on projects that push the boundaries of what's possible in the decentralized space. Current Focus Deepening my understanding of React and Node.js ecosystems while simultaneously building knowledge in blockchain fundamentals and smart contract development. Committed to continuous learning and practical application of new skills.