DSA
    beginner

    Binary Search

    Binary Search Algorithm

    O(log n)
    Step 1/7

    Halve the search space

    Sequence

    Order the steps of binary search on a sorted array.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What precondition is REQUIRED for Binary Search?

    Write the code

    Runs your solution

    Search Insert Position

    Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

    Example Cases

    Input:[[1,3,5,6], 5]
    Output:2
    Input:[[1,3,5,6], 2]
    Output:1
    Input:[[1,3,5,6], 7]
    Output:4
    javascript

    The short version

    Think of looking up a word in a dictionary. You open to the middle. If your word is after the page you see, you ignore the first half completely. You keep splitting the remaining pages in half until you find it.

    In more depth

    Divide and Conquer

    Binary Search is the most efficient way to search a Sorted array.

    1.Check the middle element.
    2.If it's the target, great!
    3.If it's larger than target, search the left half.
    4.If it's smaller, search the right half.

    This eliminates half the search space in every step, resulting in O(log n) complexity.

    Precondition: The data MUST be sorted.

    When to reach for this

    • Search in a **Sorted** array
    • Find a value where a condition changes (False -> True)
    • Search space can be divided in half (Monotonic function)

    Interview Questions

    Facebook
    Google
    Microsoft
    Amazon
    Facebook
    Facebook
    Google
    Amazon
    Apple
    Facebook
    Google
    LinkedIn
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required