Raffle Stub Lookup

Easybinary searchAlso known as Binary Search

You run the raffle at a school fair. Every ticket you sold left a stub, and the stubs are filed in one long list from the lowest ticket number to the highest. Not every number was sold, so there are gaps.

The head teacher reads out a winning number. Before anyone walks up to the stage, you want to know if that ticket was actually sold, and where its stub sits in your list.

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

Look at the middle stub first: index 3 holds 488. That is the drawn number, so the answer is 3 after a single look.

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

The middle stub is 488, which is less than 500, so 500 can only be to its right: 519, 760, 901. The middle of those is 760, too big, so look left of it: just 519. That is not 500 either, and nothing is left to check. Three looks, and 500 was never sold.

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 one by one from the start until you find the number or run out. That is correct and simple.

With 100,000 stubs it can take 100,000 looks for one call, and it ignores the most useful fact you have: the list is sorted. Binary search needs about 17 looks for the same list, 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