Blog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2025 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmseasy

Explain Binary Search.

Tags
#search#binary-search#algorithm#complexity
Back to categoryPractice quiz

Answer

Binary search finds a target in a sorted array/list by comparing with the middle element and discarding half of the range each step. It requires sorted input and runs in O(log n) time (iteratively using O(1) extra space).

function binarySearch(arr: number[], target: number): number {
    let left = 0;
    let right = arr.length - 1;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

Related questions

Algorithms
Heap sort: what are its time complexity, space complexity, and stability?
#heapsort#sorting#complexity
Algorithms
Binary search on answer (parametric search): when is it applicable?
#binary-search#parametric-search#monotonic
Algorithms
Bitmask DP (subset DP): what is it and what is a typical complexity?
#dp#bitmask#subset
Algorithms
Sliding window: what is it and when is it better than nested loops?
#sliding-window#two-pointers#complexity
Algorithms
What does amortized O(1) mean? Explain with dynamic array growth.
#amortized#complexity#dynamic-array
Algorithms
Backtracking: what is it and when do you use it?
#backtracking#search#pruning