Skip to content
Algorithms for Beginners

Problems / Binary search

First and last

medium

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 whole numbers from smallest to largest, and the same number can appear many times in a row.

Return [first, last]: the first and last positions where target appears. If it doesn't appear, return [-1, -1].

Examples

  1. Example 1

    Input
    sorted = [1, 4, 4, 4, 6, 9], target = 4
    Output
    [1, 3]

    4 is at positions 1, 2 and 3.

  2. Example 2

    Input
    sorted = [1, 4, 4, 4, 6, 9], target = 5
    Output
    [-1, -1]

    There's no 5.

  3. Example 3

    Input
    sorted = [2, 2, 2, 2], target = 2
    Output
    [0, 3]

    Every item is a 2.

Rules

  • sorted has between 0 and 1,000,000 numbers, from smallest to largest.
  • Aim for O(log n) time. A value can repeat hundreds of thousands of times, so finding one copy and walking outwards is too slow.
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.
O(log n): logarithmic time
The work grows very slowly, because each step throws away half. A million items need only about 20 steps.
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 firstAndLast(sorted, target) {
  // Return [first position, last position], or [-1, -1].
}

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