Skip to content
Algorithms for Beginners

Problems / Binary search

Where it would go

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

sorted is a list of different whole numbers, from smallest to largest. You want to add value to it and keep it sorted.

Return the position value should go at: the position of the first number that is not smaller than value. If value is already in the list, that's its own position. If it's bigger than everything, it goes at the end: position sorted.length.

Examples

  1. Example 1

    Input
    sorted = [2, 4, 7, 9], value = 7
    Output
    2

    7 is already there, at position 2.

  2. Example 2

    Input
    sorted = [2, 4, 7, 9], value = 5
    Output
    2

    5 belongs between 4 and 7, at position 2.

  3. Example 3

    Input
    sorted = [2, 4, 7, 9], value = 10
    Output
    4

    10 is bigger than everything, so it goes at the end.

Rules

  • sorted has between 0 and 1,000,000 different numbers, from smallest to largest.
Words on this page, in plain English (4)Open if any word is new to you
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Index (position)
Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
Length
How many items a list (or letters a string) has. The last position is always length - 1.
Sorted
In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function whereItGoes(sorted, value) {
  // Return the position value belongs at.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in binary search