Raffle Stub Lookup

Easybinary searchAlso known as Binary Search

You run the raffle at a school fair. The stubs of sold tickets are filed in one list from lowest number to highest. Not every number was sold, so there are gaps.

The head teacher reads out a winning number. Before anyone walks up, you want to know whether it was sold and where its stub sits.

Your task

Write findTicket(tickets, drawn). tickets is sorted from smallest to largest and has no repeats. Return the index of drawn in tickets, or -1 if that number was never sold.

Use the sorted order: your solution should look at about log₂ n stubs, not all of them. An empty list returns -1.

findTicket(tickets: int[], drawn: int) → int

Examples

Example 1
Input
tickets = [102, 215, 340, 488, 519, 760, 901]
drawn = 488
Output
3
Why

The middle stub, index 3, holds 488, so the ticket is found with one look.

Example 2
Input
tickets = [102, 215, 340, 488, 519, 760, 901]
drawn = 500
Output
-1
Why

The middle stub, 488, is less than 500, so look right: 519, 760, 901. Their middle, 760, is too big, so look left of it: just 519. That stub is not 500 either and nothing is left, so the answer is -1 after three looks.

Constraints

  • 0 ≤ tickets.length ≤ 100,000
  • 1 ≤ tickets[i], drawn ≤ 1,000,000,000
  • tickets is strictly increasing (sorted, no repeats).
Start with brute force

Read the stubs from the start until you find the number or run out. This is correct and simple.

But with 100,000 stubs one call can take 100,000 looks, ignoring that the list is sorted. Binary search needs about 17, because 2¹⁷ is more than 100,000.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code