←
Class 12 Computer Science
6. Searching · 6 / 13
⌕
Chapter 6 of 13

6. Searching

7 sections · 7,844 words

Opening

391 words · 2 min read

Big idea: A search method is useful only when its assumptions match the data.

Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.

  • State the exact result a search must return, including the not-found case.
  • Trace linear search and count its comparisons on found, first-position and missing targets.
  • Trace binary search mid by mid and explain why sorted order is required.
  • Use hashing with a collision policy and compare real keys inside a bucket.

Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.

This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.

The previous chapter arranged records in order. This chapter finds one record among many. Both chapters care about how data are organised, but the goal changes from arranging everything to locating one thing.

The chapter builds in stages. First the shared vocabulary: target, match, contract and not-found result.

Then three methods, each with its own worked traces. Then a comparison of their costs.

Each section reuses the same running datasets, so results stay comparable.

Study by tracing. Cover the expected output and predict it first. When a prediction fails, find the first line where your trace diverged. That line holds the lesson.

The running example is a small contact list on a phone. Five saved entries are searched in every section.

The list starts unsorted for linear search, then appears sorted for binary search, then its keys are hashed into buckets. Watch how the same question gets a different route each time.

Trace tables and diagrams carry much of the teaching. A trace table shows one row per step: what was compared, what was decided, and what remains.

A diagram shows the loop shape: where it repeats and where it leaves. Read each figure before reading on, and say its conclusion in your own words.

Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.

6.1 INTRODUCTION

1,038 words · 5 min read

Sometimes you only need to know whether a record exists. Sometimes you need its position, its first occurrence or every occurrence. Start by stating which answer your search should produce.

The organisation of the data affects the available methods. An unsorted list allows a scan. An ordered sequence allows intervals to be ruled out. A key index can direct you toward a smaller candidate set.

  1. Write a clear found-result contract.
  2. Choose a not-found result that cannot be confused with a valid answer.
  3. Match the method’s assumptions to the way the data are stored.
In simple words: A search is correct only when its result means what the caller expects.

Finding one saved entry is a different task from arranging all entries.

A search asks whether a target is present. It may also return its location or its stored record. A target is the value being looked for. A match is an entry equal to the target under the agreed comparison.

A search contract states what counts as found and what is returned when nothing matches.

State the required result first. The contract may ask for any matching position, the first match, every match, or only a yes-or-no answer.

These are different contracts when duplicate values exist. A program that returns one index has not answered a question that asked for all of them.

ContractWhat the caller receives
Any matchOne position of the target, if any exists.
First matchThe earliest position in scan order.
Every matchAll positions, or an empty collection when absent.
MembershipOnly whether the target is present.

Read the table. Each row names a different promise. The same data can satisfy one row and fail another. Choosing the row is part of the task, not a detail to skip.

Search performance depends on the organisation of the data and the permitted preprocessing. A once-only search of a small unsorted list may not justify sorting it first.

Many repeated searches may justify an index or a different representation.

OrganisationPossible method
Unsorted sequential valuesLinear scan.
Sorted random-access sequenceBinary search.
Hash-indexed keysHash lookup with a collision policy.

Read the table. Each row pairs a data layout with a method that fits it. The method does not create the layout. Sorting must happen before binary search, and buckets must be built before hash lookup.

State the result contractCheck how data are storedPick scan, halves or hashHandle the not-found case
Choosing a search method from the contract and the data layout.

Read the diagram. The first box fixes the promise: what the answer must look like.

The second box inspects the data: order, access and available indexes. The third box selects the method whose assumptions hold.

The last box plans the failure path, because every search needs one.

A tiny membership test shows the contract idea. The in operator answers only the membership row of the table above. It cannot report a position.

Write down what this program should print before you read the expected output.

codes = [11, 18, 24, 31, 40, 47, 55, 63]
print(47 in codes)
print(30 in codes)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 stores eight codes in ascending order.
  2. Line 2 asks whether 47 is present. It is, so the answer is True. No position is reported.
  3. Line 3 asks whether 30 is present. It is not, so the answer is False. Membership is the whole answer.

Output
True
False

Replace 47 with 63 and 30 with 11. Predict both printed lines.

A method is correct only when its assumptions match the data. Cost comparisons must include preparation, not only the final lookup.

You need one missing tag from a short unsorted list. Should you automatically sort the list first?

Goal. Decide whether sorting first is automatically the cheapest total workflow.

Approach. Compare the preparation cost against the lookup saving for a single search.

Trace. Sorting has a cost and changes the order unless performed on a copy. A linear scan needs no ordering prerequisite.

Result. Sorting first is not automatic; for one lookup on a short list the scan is the cheaper total.

Result: Use the method that meets the full task; binary search is not automatically the cheapest total workflow.

A phone book app will answer thousands of lookups on the same contact list. Which preparation pays off?

Goal. Choose a method for many repeated searches on slowly changing data.

Approach. Spread the one-time preparation cost across all future lookups.

Trace. Sorting once, or building buckets once, serves every later query. Each lookup then avoids a full scan.

Result. Preparation pays off here because one build cost is shared by thousands of cheap lookups.

Result: Sort once or index once, then use the fast lookup for every query.

Sorting for binary search should not destroy the original order. The sorted helper builds a new ordered list and leaves the arrival order untouched. Later tasks that need arrival order still work.

Try to predict the printed result first. The trace below explains every line.

def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

arrival = [23, 8, 17]
ordered = sorted(arrival)
print(ordered)
print(arrival)
print(binary_search(ordered, 17))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 to 12 define the taught binary search, unchanged.
  2. Line 14 stores three values in arrival order. Line 15 builds a new ascending list.
  3. Line 16 prints the new list: ascending and ready for binary search.
  4. Line 17 prints the original: still in arrival order, untouched by the sort.
  5. Line 18 searches the ordered copy. The first middle is index 1, which matches at once. Sorting a copy serves both orders.

Output
[8, 17, 23]
[23, 8, 17]
1

Search the ordered copy for 8. Predict the printed index.

Sorting is preparation, not part of binary search itself. Quote its cost separately.
Common mistake: Do not compare only lookup cost while ignoring required preparation.

⚡ Quick Check Flashcards3 questions
Question 1
What must a not-found result make clear?
Try answering before revealing!
Question 2
Why specify duplicate behaviour?
Try answering before revealing!
Question 3
Which contract does the in operator answer?
Try answering before revealing!

6.2 LINEAR SEARCH

1,486 words · 7 min read

Look at the current entry and ask, “Is this the target?” If not, move to the next entry. That is the complete idea of a linear scan. No sorted order is required.

If you return immediately on a match, you find the first matching entry in scan order. If the whole scan finishes without a match, you return the documented missing result.

  1. Inspect each candidate once in the chosen order.
  2. Stop at a match only if that fulfils the contract.
  3. Handle the not-found result before using it as an index.
In simple words: A negative sentinel is a message to the caller, not permission to index the list from its end.

A roll call reads names one by one until the wanted name is heard.

Start at the beginning and compare each entry with the target. Return as soon as the required match is found. If the scan finishes without a match, return the documented not-found value. Ordering is unnecessary.

Linear search compares entries in order and stops at the first match. No sorted order is needed.

Predict the output before running this complete example.

def linear_search(values, target):
    for index, value in enumerate(values):
        if value == target:
            return index
    return -1

values = [17, 8, 23, 8]
print(linear_search(values, 8))
print(linear_search(values, 99))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Enumerate supplies both the current position and its value.
  2. Equality tests the current value against the target.
  3. A match returns immediately, so later entries are not checked.
  4. The final negative return is reached only if the loop found no match.

Output
1
-1

Put the target at the beginning, at the end, and nowhere in the list. Compare the work needed.

Line 1 defines the function. The enumerate helper supplies each index beside its value.

Line 2 compares the current entry with the target. Line 3 returns the index at once on a match.

Line 5 runs only when no entry matched, returning the sentinel.

The first call prints 1. The scan checks index 0 holding 17, then index 1 holding 8, which matches. The second call prints -1. Every entry is checked and none matches.

This implementation returns the first matching zero-based index. The sentinel is negative, so callers must test it explicitly: using it as a Python list index would access the last element instead of reporting failure.

Look at the next entryMatch, so return positionEnd reached, so return -1Check -1 before indexing
Linear search checks entries in order until a match or the end.

Read the diagram. The first two boxes repeat for every entry: inspect, then leave at once on a match.

The third box runs only after the last entry fails. The last box is a warning about the sentinel, not part of the loop.

The table below replays the first call above. Read across each row: position, value, decision. The scan stops at the first row whose decision is a match.

StepIndexValueDecision
1017Not the target; continue.
218Match; return 1 at once.

Read the table. Only two entries are inspected although the list holds four. Stopping early is the normal behaviour, not a shortcut. A miss would need all four rows.

Counting comparisons makes the cost visible. Each loop step performs exactly one key comparison between the current value and the target.

On eight codes, a target at the front costs one comparison, a target at index five costs six, and a miss costs all eight.

Before running the program, say the output in your own words.

def linear_count(values, target):
    comparisons = 0
    for index, value in enumerate(values):
        comparisons += 1
        if value == target:
            return index, comparisons
    return -1, comparisons

codes = [11, 18, 24, 31, 40, 47, 55, 63]
print(linear_count(codes, 11))
print(linear_count(codes, 47))
print(linear_count(codes, 30))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 to 7 define a counting scan. Each step adds one to the counter, then tests the entry.
  2. Lines 9 to 12 call it three times on the eight codes. The value 11 sits at index 0, so the first print shows 1 comparison.
  3. The value 47 sits at index 5, so six entries are inspected: 6 comparisons.
  4. The value 30 is absent, so all eight entries are inspected: 8 comparisons and the sentinel -1.

Output
(0, 1)
(5, 6)
(-1, 8)

Search for 63 instead of 47. Predict the printed pair.

The comparison table below summarises the three calls. Position in the list decides the cost. Nothing about the values themselves matters.

TargetReturned indexComparisons
1101
4756
30 (absent)-18

Read the table. Earlier targets cost less.

The absent target always costs the full length. For n entries the best case needs one comparison and the worst case needs n.

Average cost depends on how targets and misses are distributed.

Think about the average plainly. When every position is equally likely and the target is always present, about half the entries are inspected on average.

Misses always cost the full scan. A test report should therefore state the case it measured: best, average or worst.

Predict the comparisons for target 24 in the eight codes.

Goal. State the returned index and the comparison count without running code.

Approach. Walk the codes in order, counting one comparison per entry until the match.

Trace. 11, 18, then 24 at index 2: the third comparison matches. Nothing later is visited.

Result. Three comparisons return index 2.

Result: It returns 2 after 3 comparisons.

What happens when the input list is empty?

Goal. Determine what the taught function returns for an empty list.

Approach. Ask how many loop steps run when there are no entries.

Trace. The loop makes no comparison and immediately reaches the final return.

Result. No entry can match, so the sentinel is the correct answer.

Result: It returns the not-found sentinel.

The contact list threads through this section. Each saved id is checked in storage order until the wanted id appears. A miss reports a friendly message instead of a position.

Write down what this program should print before you read the expected output.

ids = ["c101", "c104", "c109", "c112", "c118"]
slots = ["bus-map", "drill-log", "echo-memo", "fence-plan", "harbour-map"]

def find_slot(ids, slots, wanted):
    for i in range(len(ids)):
        if ids[i] == wanted:
            return slots[i]
    return "not saved"

print(find_slot(ids, slots, "c109"))
print(find_slot(ids, slots, "c120"))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 and 2 store five ids with five matching slot labels. Position links each pair.
  2. Lines 4 to 8 define the search. It walks the ids in order and returns the paired slot at the first match.
  3. Line 10 looks for c109. It sits at index 2, so the paired slot echo-memo is returned.
  4. Line 11 looks for c120. No id matches, so the loop ends and the friendly message is returned.

Output
echo-memo
not saved

Search for c101 instead of c109. Predict the printed line.

The every-match contract needs a different loop shape. Instead of returning at the first match, the program collects each matching index and returns the whole collection. An empty collection then means absence.

Try to predict the printed result first. The trace below explains every line.

def all_of(values, target):
    found = []
    for index, value in enumerate(values):
        if value == target:
            found.append(index)
    return found

print(all_of([17, 8, 23, 8], 8))
print(all_of([17, 8, 23, 8], 99))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 2 starts an empty collection before the loop.
  2. Lines 3 to 5 inspect every entry, because a later duplicate may still appear. Both copies of 8 are recorded.
  3. Line 8 prints the two matching positions. No early stop is possible under this contract.
  4. Line 9 prints an empty collection. Absence is shown by emptiness, not by a sentinel.

Output
[1, 3]
[]

Collect matches for 17 instead of 8. Predict the printed list.

Position decides cost: earlier is cheaper, absence costs the full scan. A single index answers the first-match contract only.

Predict the result of linear_search on [17, 8, 23, 8] for target 23 and count the comparisons.

Goal. State the return value and the number of comparisons.

Approach. Walk the entries in order and count one comparison per entry.

Trace. Index 0 holds 17: no match. Index 1 holds 8: no match. Index 2 holds 23: match.

Result. Three comparisons are used and the scan stops.

Result: It returns 2 after 3 comparisons.

A caller uses the result directly as values[linear_search(values, 99)]. Explain the fault and give the repair.

Goal. Show what goes wrong when the sentinel is used as an index.

Approach. Ask what the function returned and what that value means as an index.

Trace. The function returns -1 for absence. As an index, -1 selects the last element, so the program reports a wrong record.

Result. The caller must test the result first and handle absence explicitly.

Result: Test for -1 before indexing. Report or handle the miss instead of indexing with it.

An early return is the found path, not a broken loop. The loop ends because its job is done.
Common mistake: Do not use a not-found sentinel as an index before checking it.

⚡ Quick Check Flashcards3 questions
Question 1
Can linear search handle an unsorted list?
Try answering before revealing!
Question 2
Which duplicate does the shown implementation return?
Try answering before revealing!
Question 3
How many comparisons does a miss need on n entries?
Try answering before revealing!

6.3 BINARY SEARCH

2,456 words · 11 min read

Binary search does more than pick a middle entry. Its useful step is proving that one side cannot contain the target. That proof depends on the entries being sorted by the same key you are comparing.

If the middle is too small, all earlier entries are too small too. If it is too large, all later entries are too large. Excluding the already tested middle makes the remaining interval strictly smaller.

  1. Mark the current low and high bounds.
  2. Compare the middle entry with the target.
  3. Keep only the side where a match is still possible, or stop when a match is found.
In simple words: Halving without a valid ordering argument is guessing, not binary search.

A guessing game narrows the range after every hint of too high or too low.

Maintain inclusive low and high bounds. Compare the middle value with the target.

A larger target can only lie to the right in an ascending list; a smaller target can only lie to the left. Exclude the already tested middle when moving a bound.

Sorting is the precondition that makes each half provable. Each entry to the left of the middle is less than or equal to it, and each entry to the right is greater than or equal to it.

That order is what lets one comparison rule out a whole side.

Binary search needs ascending order by the compared key. One middle comparison then discards half the candidates.

Binary search on unsorted data can miss a value that is present. The program below searches a shuffled list for 18.

The middle comparisons point the wrong way, and the search reports absence although 18 sits at the last position.

Before running the program, say the output in your own words.

def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([31, 11, 47, 18], 18))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 calls the taught function on an unsorted list. Bounds start at 0 and 3, so mid is 1.
  2. The middle holds 11, which is smaller than 18. The search keeps only the right side.
  3. The middle of the remaining range holds 47, which is larger. The search keeps only the left of it, which is empty.
  4. The print shows -1. The value 18 was present but the discarded halves hid it. Order is required, not optional.

Output
-1

Sort the list first, then predict the printed index.

Predict the output before running this complete example.

def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

values = [4, 9, 13, 18, 27, 35, 42]
print(binary_search(values, 35))
print(binary_search(values, 20))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Low and high describe the remaining inclusive search interval.
  2. Mid chooses an integer position inside it.
  3. A failed comparison rules out the middle and one side because the values are sorted.
  4. Eventually a value matches or the bounds describe an empty interval.

Output
5
-1

Use a missing target between two existing values and trace how the interval becomes empty.

The first call finds 35 at index 5. The second call searches for 20, which is absent, and returns the sentinel -1.

Read the trace row by row. Each row shows the bounds before one middle comparison.

Search for 35lowmidhighDecision
First comparison03618 is smaller; continue right.
Next comparison45635 matches at index 5.

Read the table. The first middle is index 3, because 6 divided by 2 is 3.

The value 18 is smaller than 35, so every index at or below 3 is impossible. The second middle is index 5, because 10 divided by 2 is 5.

It holds 35, so the search stops.

The invariant is that any remaining match must be inside the interval. When low becomes greater than high, that interval is empty. Updating a bound to mid instead of beyond mid can make an interval fail to shrink.

Compare middle with targetMatch, so return the indexToo small, so drop the leftToo large, so drop the rightEmpty range, so return -1
Binary search keeps only the half where a match is still possible.

Read the diagram. The first box compares the current middle.

The next two boxes each discard one side, excluding the tested middle. The last box runs only when the range is empty, which proves absence.

A match leaves through the second box at once.

The figure below shows the loop on eight ascending codes. Follow the low and high columns: the range always shrinks, and the tested middle never returns.

Target 47lowmidhighMiddle valueDecision
Step 103731Too small; low becomes 4.
Step 245747Match; return 5.

Read the table. Two middle comparisons find 47 at index 5. A linear scan would need six. The sorted order is what makes the skipped entries safe to skip.

A harder trace finds the first code. Each middle is too large, so the high bound keeps moving left until one entry remains.

Target 11lowmidhighMiddle valueDecision
Step 103731Too large; high becomes 2.
Step 201218Too large; high becomes 0.
Step 300011Match; return 0.

Read the table. Three comparisons reach index 0. Early positions are not cheap here: the middle-first order visits the centre before the edges.

The longest trace on eight codes finds the last entry. Four comparisons are needed, one per halving.

Target 63lowmidhighMiddle valueDecision
Step 103731Too small; low becomes 4.
Step 245747Too small; low becomes 6.
Step 366755Too small; low becomes 7.
Step 477763Match; return 7.

Read the table. Each step halves roughly: eight candidates, then four, then two, then one. Halving is why the worst cost grows slowly.

A missing target traces a similar path but ends with an empty range. The search for 30 compares 31, then 18, then 24. Each remaining middle is on the wrong side, and the bounds cross with no match found.

Target 30 (absent)lowmidhighMiddle valueDecision
Step 103731Too large; high becomes 2.
Step 201218Too small; low becomes 2.
Step 322224Too small; low becomes 3. Empty: return -1.

Read the table. Three comparisons prove absence. The final row leaves low above high, so the interval is empty and the sentinel is correct.

The guessing game is binary search in disguise. Numbers 1 to 100 are already sorted. Each guess is a middle, and each hint discards a half. Finding 37 needs only three guesses: 50, then 25, then 37.

Write down what this program should print before you read the expected output.

vals = list(range(1, 101))

def mids_of(values, target):
    low, high, out = 0, len(values) - 1, []
    while low <= high:
        mid = (low + high) // 2
        out.append(values[mid])
        if values[mid] == target:
            return out
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return out

print(mids_of(vals, 37))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 builds the sorted numbers 1 to 100.
  2. Lines 3 to 13 record each middle instead of returning an index. The update rules match the taught function exactly.
  3. Line 15 prints the three guesses. 50 is too high, so the top half goes. 25 is too low, so the bottom of the rest goes. 37 matches.
  4. Three comparisons pin down one value among one hundred. That is the power of halving.

Output
[50, 25, 37]

Find 75 instead of 37. Predict the printed list.

Comparison counts stay small while the list doubles. Each row below was verified by counting real runs. Linear search on a miss checks every entry. Binary search on the same miss halves again and again.

List lengthLinear missBinary worst
773
884
16165
32326
64647

Read the table. Doubling the length adds one binary comparison but doubles the linear count. Eight entries need at most four binary comparisons; sixty-four need at most seven.

Verified worst-case counts on misses. Binary search grows by one per doubling; linear search doubles.

Read the figure. The horizontal axis doubles at each step: 8, 16, 32, 64.

The linear curve climbs steeply through 8, 16, 32 and 64. The binary curve creeps through 4, 5, 6 and 7.

The gap between them is the visual meaning of halving against scanning.

A head-to-head race on sixteen codes makes the difference concrete. The target 30 is absent. Linear search inspects all sixteen entries. Binary search compares four mids: 63, 31, 18 and 24, then stops.

Try to predict the printed result first. The trace below explains every line.

codes16 = [11, 18, 24, 31, 40, 47, 55, 63, 71, 79, 86, 92, 99, 105, 112, 120]

def linear_count(values, target):
    comparisons = 0
    for index, value in enumerate(values):
        comparisons += 1
        if value == target:
            return index, comparisons
    return -1, comparisons

def binary_count(values, target):
    low, high = 0, len(values) - 1
    comparisons = 0
    while low <= high:
        mid = (low + high) // 2
        comparisons += 1
        if values[mid] == target:
            return mid, comparisons
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1, comparisons

print(linear_count(codes16, 30))
print(binary_count(codes16, 30))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 stores sixteen ascending codes. Lines 3 to 9 count linear comparisons; lines 11 to 24 count binary comparisons.
  2. Both functions return a pair: the index and the comparison count.
  3. The linear call checks all sixteen entries and reports the sentinel: sixteen comparisons.
  4. The binary call compares four mids and reports the sentinel: four comparisons. Same answer, a quarter of the work.

Output
(-1, 16)
(-1, 4)

Search for 120 instead of 30. Predict both printed pairs.

The contact list returns, now sorted. The same five ids in ascending order allow binary search. Finding c109 takes one middle: index 2 holds it at once.

Before running the program, say the output in your own words.

def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

ids = ["c101", "c104", "c109", "c112", "c118"]
print(binary_search(ids, "c109"))
print(binary_search(ids, "c120"))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 stores the five contact ids in ascending order. The sorted precondition holds.
  2. Line 2 searches for c109. The first middle is index 2, which matches at once.
  3. Line 3 searches for c120. Three mids are compared and the bounds cross with no match. The sentinel reports absence.

Output
2
-1

Search for c101 instead of c109. Predict the printed index.

With duplicates, this version returns an encountered match, not necessarily the first. On five values with three copies of 8, the first middle is index 2, which matches at once.

The earlier copy at index 1 is never visited. Finding a lower or upper boundary needs a modified contract.

Write down what this program should print before you read the expected output.

def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            return mid
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([5, 8, 8, 8, 12], 8))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 searches a sorted list with three copies of the target.
  2. The first middle is index 2. It holds 8, so the function returns at once.
  3. The print shows 2. The copies at index 1 and 3 are equally valid matches that this contract does not promise.

Output
2

Search for 5 instead of 8. Predict the printed index.

When the first copy is truly required, the contract changes and so does the code. The variant below records each match but keeps searching the left side for an earlier one.

It returns the leftmost position, or the sentinel when the target is absent.

Try to predict the printed result first. The trace below explains every line.

def leftmost(values, target):
    low, high = 0, len(values) - 1
    found = -1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            found = mid
            high = mid - 1
        elif values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return found

print(leftmost([5, 8, 8, 8, 12], 8))
print(leftmost([5, 8, 8, 8, 12], 7))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Lines 1 to 3 set the bounds and a found variable starting at the sentinel.
  2. Lines 4 to 12 repeat the taught loop with one change: a match is recorded, then the search continues left for an earlier copy.
  3. The first call records index 2, then finds index 1, then the bounds cross. The print shows 1.
  4. The second call never matches, so found keeps the sentinel. The print shows -1. Recording plus continuing left is the whole trick.

Output
1
-1

Search for 12 instead of 8. Predict the printed value.

Never run binary search on arrival order and hope the middle behaves. The discard step is a proof, and the proof cites sorted order.

Binary search has logarithmic worst-case comparison growth on a sorted random-access sequence. With duplicates, this version returns an encountered match, not necessarily the first.

Finding a lower or upper boundary needs a modified contract.

Applications include searching sorted identifiers and locating a boundary in a monotonic condition. The halve-the-candidate-range idea applies only when the comparison or condition justifies discarding the other half.

Halving needs order; order lets one comparison discard a whole side. Without order, the discarded half may contain the target.

Trace the mids when searching the eight codes for 40.

Goal. List every middle compared and the returned index.

Approach. Start with low 0 and high 7, then update bounds excluding each tested middle.

Trace. Mid 3 holds 31, too small, so low becomes 4. Mid 5 holds 47, too large, so high becomes 4. Mid 4 holds 40, a match.

Result. Three comparisons return index 4.

Result: Mids 31, 47, 40; returns 4.

A loop updates low to mid instead of mid + 1. Explain the failure.

Goal. Show why excluding the tested middle matters.

Approach. Ask what happens when the middle is too small but stays inside the range.

Trace. The same middle is recomputed because the range never shrinks past it. The loop repeats its bounds forever.

Result. The search hangs instead of finishing.

Result: Move to mid + 1 or mid - 1 so the tested position leaves the range.

State exactly when this binary search returns -1.

Goal. Name the condition that proves absence.

Approach. Follow the bounds until no candidate remains.

Trace. Each step excludes the tested middle and keeps only possible positions. The loop ends when low passes high.

Result. An empty interval means no position can hold the target.

Result: It returns -1 only when low becomes greater than high.

Mid uses integer division: (low + high) // 2 rounds down, so the middle of an even range is the left-centre entry.
Common mistake: A sorted-looking middle portion does not justify binary search on an unsorted whole sequence.

⚡ Quick Check Flashcards3 questions
Question 1
Why use mid + 1 or mid - 1?
Try answering before revealing!
Question 2
Does the shown algorithm guarantee the first duplicate?
Try answering before revealing!
Question 3
What does an empty interval prove?
Try answering before revealing!

6.4 SEARCH BY HASHING

1,257 words · 6 min read

Hashing turns a key into a candidate location. This can avoid checking every earlier record. However, the number of possible keys can exceed the number of locations, so different keys may share one location.

A collision is normal behaviour that the design must support. Chaining keeps several entries in a bucket. A lookup chooses the bucket, then compares actual keys inside it.

  1. Compute the candidate location using the agreed hash rule.
  2. Use the same collision policy for storing and finding entries.
  3. Check key equality before returning a match.
In simple words: Two keys sharing a location are not necessarily the same key.

A library catalogue turns a title into a shelf number without checking every shelf.

A hash function maps a key to a hash value or table position. A simple teaching example uses an integer remainder.

Different keys can map to the same position: that event is a collision. It must be handled, not treated as proof that the keys are equal.

A hash function computes a candidate bucket from the key. A collision means two keys share one bucket.

Use h(key) = key modulo 7 for keys 17 and 24.

Divide each key by the table size and keep the remainder.

Result: Both have remainder 3; the second key collides with the first.

Read the worked example. Dividing 17 by 7 leaves remainder 3, because 7 times 2 is 14 and 17 minus 14 is 3. Dividing 24 by 7 leaves remainder 3, because 7 times 3 is 21 and 24 minus 21 is 3. Same bucket, different keys.

The bucket table below shows where three keys land in seven buckets. Buckets hold lists because more than one key may arrive.

KeyBucket (key modulo 7)Bucket after all inserts
173[17, 24]
243[17, 24]
92[9]

Read the table. Keys 17 and 24 share bucket 3: that shared cell is the collision. Key 9 lands alone in bucket 2. Empty buckets hold empty lists, ready for future keys.

Collision methodWhat happens
ChainingA bucket stores several entries; compare actual keys within it.
Open addressingFollow a probing rule to another slot; insertion and lookup must use compatible rules.

Read the table. Chaining keeps neighbours together in one bucket and sorts them out by key comparison. Open addressing sends overflow to further slots, so storing and finding must follow the same probing path.

Watch open addressing place the same three keys. The table holds single entries, not lists. Key 17 takes slot 3. Key 24 also wants slot 3, finds it taken, and steps to slot 4. Key 9 takes slot 2 directly.

Before running the program, say the output in your own words.

table = [None] * 7
for key in [17, 24, 9]:
    slot = key % len(table)
    while table[slot] is not None:
        slot = (slot + 1) % len(table)
    table[slot] = key
print(table)

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 builds seven empty slots. None marks an empty slot.
  2. Lines 2 to 6 insert each key. The remainder gives the starting slot; the while loop steps right past taken slots.
  3. Key 17 claims slot 3. Key 24 probes from 3 to 4. Key 9 claims slot 2.
  4. The print shows each key in its final slot. A lookup for 24 must probe the same path: try 3, then 4.

Output
[None, None, 9, 17, 24, None, None]

Insert 31 afterwards. Predict the printed table.

Compute the bucket numberCompare keys in the bucketKey matches, so return itNo match, so report a miss
Hash lookup computes a bucket, then compares actual keys inside it.

Read the diagram. The first box computes where to look: bucket equals key modulo table size.

The second box does the real identification: compare stored keys with the wanted key. The last two boxes separate the two exits: a key match returns the entry, otherwise the lookup reports a miss.

Predict the output before running this complete example.

buckets = [[] for _ in range(7)]
for key in [17, 24, 9]:
    buckets[key % len(buckets)].append(key)
target = 24
print(buckets[target % len(buckets)])
print(target in buckets[target % len(buckets)])

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The initial list contains separate empty buckets.
  2. The remainder chooses the bucket for each incoming key.
  3. Colliding keys stay together in that bucket instead of overwriting each other.
  4. Lookup checks actual equality within the selected bucket.

Output
[17, 24]
True

Choose another key with the same remainder and observe the collision.

Line 1 builds seven empty buckets. Lines 2 and 3 insert each key into its remainder bucket.

Line 4 chooses the target 24. Line 5 prints bucket 3, holding both colliding keys.

Line 6 compares actual keys inside that bucket and confirms membership.

A shared bucket is not an identity proof. The key 31 lands in bucket 3 as well, because 31 modulo 7 is 3, yet 31 was never stored. Only a key comparison can tell 31 apart from 17 and 24.

Write down what this program should print before you read the expected output.

buckets = [[], [], [9], [17, 24], [], [], []]
print(31 % 7)
print(31 in buckets[31 % 7])
print(24 in buckets[24 % 7])

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 rebuilds the bucket state from the previous program: bucket 3 holds the colliding pair.
  2. Line 2 prints the bucket number for 31: remainder 3. Same bucket as the stored keys.
  3. Line 3 compares actual keys inside bucket 3. The key 31 is absent, so the answer is False despite the shared bucket.
  4. Line 4 compares again for 24. That key is stored, so the answer is True. Buckets propose; key comparison disposes.

Output
3
False
True

Test 17 instead of 24 in the last line. Predict the printed value.

Python dictionaries and sets provide general hash-based containers. Their performance and implementation details are more sophisticated than this remainder-bucket illustration.

Expected lookup can be very fast under suitable conditions, but collisions and adversarial cases mean hashing is not a universal worst-case constant-time guarantee.

Hash-table hashes are also different from cryptographic hashes used for integrity or password processing. The word hash alone does not establish a security property.

Buckets propose candidates; only key comparison confirms identity. Insertion and lookup must share the same hash rule and the same collision policy.

Insert keys 17, 24 and 9 into seven buckets, then state bucket 3.

Goal. Show the bucket contents after the three inserts.

Approach. Compute each remainder and append the key to that bucket list.

Trace. 17 gives remainder 3, 24 gives remainder 3, and 9 gives remainder 2. Bucket 3 collects two entries.

Result. Order of arrival is preserved inside the bucket.

Result: Bucket 3 holds [17, 24].

A lookup returns stored entry 17 for wanted key 24. Name the fault and the repair.

Goal. Explain how a shared bucket produced a wrong record.

Approach. Ask whether the lookup compared keys or stopped at the bucket.

Trace. Bucket 3 holds both 17 and 24. Returning the first entry without comparing keys confuses neighbours.

Result. The lookup must compare each key in the bucket and return only an equal one.

Result: Compare actual keys inside the bucket; return a match only on key equality.

A collision is normal sharing, not damage. A good design expects it and has a rule ready.
Common mistake: Equal hash locations do not imply equal keys.

⚡ Quick Check Flashcards3 questions
Question 1
Why do 17 and 24 share this bucket?
Try answering before revealing!
Question 2
What must a chaining lookup compare inside the bucket?
Try answering before revealing!
Question 3
Why must storing and finding share one rule?
Try answering before revealing!

Summary

224 words · 1 min read

Use these points to test what you can explain without looking back.

  • Search contracts differ: any match, first match, every match, or membership only.
  • Choose the method from the data layout, and quote preparation cost beside lookup cost.
  • Linear search needs no sorted order and stops at the first match in scan order.
  • Linear scan cost follows position: one comparison at the front, n for a miss.
  • A not-found sentinel must be tested before use; -1 as an index reads the last entry.
  • An every-match task must inspect all entries; an early return would drop duplicates.
  • Binary search needs ascending order by the compared key; halves are proofs, not guesses.
  • Exclude the tested middle with mid + 1 or mid - 1 so the interval always shrinks.
  • An empty interval, low above high, is the only proof of absence in binary search.
  • Binary worst-case comparisons grow by one per doubling: 4, 5, 6, 7 for 8, 16, 32, 64.
  • This binary version returns an encountered duplicate, not necessarily the first.
  • Hashing computes a bucket from the key; collisions are normal and expected.
  • Chaining compares actual keys inside the bucket before returning a match.
  • Hash-table speed claims are expected-case; adversarial cases break constant-time hopes.
For each algorithm or rule, give an input for which it works and a condition under which it needs extra care.

Exercise

992 words · 5 min read

Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.

6.1 Why is a zero index not a suitable not-found sentinel?

6.2 Explain why a linear scan can stop at its first match for a first-occurrence contract.

6.3 What is wrong with applying binary search directly to arrival order?

6.4 A binary-search loop repeats the same bounds. What should you inspect?

6.5 What change is needed to return every matching position?

6.6 Explain a collision without using the word error.

6.7 Why can deleting an open-addressed entry need special handling?

6.8 When might a dictionary be preferable to repeatedly scanning a list of records?

6.9 Predict the output, then name the contract this loop answers.

Try to predict the printed result first. The trace below explains every line.

def linear_search(values, target):
    for index, value in enumerate(values):
        if value == target:
            return index
    return -1

values = [17, 8, 23, 8]
print(linear_search(values, 8))
print(linear_search(values, 99))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Line 1 stores the list with a duplicated 8.
  2. The first call scans to index 1 and returns at once.
  3. The second call checks all four entries and returns the sentinel.

Output
1
-1

Change the target 8 to 23 and predict the printed value.

6.10 Trace the mids for target 47 in the eight codes, then state the index and count.

SteplowmidhighDecision
103731 is too small.
245747 matches.

6.11 Trace the mids for missing target 30 in the eight codes, then state the result.

SteplowmidhighDecision
103731 is too large.
201218 is too small.
322224 is too small; empty.

6.12 This counting scan is wrong. Name the faulty line and give the repair.

Python
def linear_count(values, target):
    comparisons = 0
    for index, value in enumerate(values):
        if value == target:
            comparisons += 1
            return index, comparisons
    return -1, comparisons

6.13 This binary update hangs on some inputs. Name the faulty lines and give the repair.

Python
while low <= high:
    mid = (low + high) // 2
    if values[mid] == target:
        return mid
    if values[mid] < target:
        low = mid
    else:
        high = mid

6.14 Write a linear search that returns every matching position. Show its result on [17, 8, 23, 8].

Before running the program, say the output in your own words.

def all_of(values, target):
    found = []
    for index, value in enumerate(values):
        if value == target:
            found.append(index)
    return found

print(all_of([17, 8, 23, 8], 8))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. The collection starts empty and every entry is inspected.
  2. Both copies of 8 are appended; nothing returns early.
  3. The print shows both positions in scan order.

Output
[1, 3]

Search for 99 and predict the printed list.

6.15 Write the contact-list lookup and show both exits.

Write down what this program should print before you read the expected output.

ids = ["c101", "c104", "c109", "c112", "c118"]
slots = ["bus-map", "drill-log", "echo-memo", "fence-plan", "harbour-map"]

def find_slot(ids, slots, wanted):
    for i in range(len(ids)):
        if ids[i] == wanted:
            return slots[i]
    return "not saved"

print(find_slot(ids, slots, "c109"))
print(find_slot(ids, slots, "c120"))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Parallel lists link each id to its slot by position.
  2. A match returns the paired slot at once.
  3. A full scan without a match returns the friendly message.

Output
echo-memo
not saved

Look up c118 and predict the printed slot.

6.16 Contrast linear and binary search on sixteen codes with a missing target.

Try to predict the printed result first. The trace below explains every line.

codes16 = [11, 18, 24, 31, 40, 47, 55, 63, 71, 79, 86, 92, 99, 105, 112, 120]

def linear_count(values, target):
    comparisons = 0
    for index, value in enumerate(values):
        comparisons += 1
        if value == target:
            return index, comparisons
    return -1, comparisons

def binary_count(values, target):
    low, high = 0, len(values) - 1
    comparisons = 0
    while low <= high:
        mid = (low + high) // 2
        comparisons += 1
        if values[mid] == target:
            return mid, comparisons
        if values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1, comparisons

print(linear_count(codes16, 30))
print(binary_count(codes16, 30))

Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.

  1. Both counters increment once per key comparison.
  2. Linear search inspects all sixteen entries for a miss.
  3. Binary search halves to the answer in four mids.

Output
(-1, 16)
(-1, 4)

Search for present 120 and predict both pairs.

6.17 Give the worst-case binary comparison counts for lengths 8, 16, 32 and 64.

6.18 Trace the mids for target 40 in the eight codes, then state the index and count.

SteplowmidhighDecision
103731 is too small.
245747 is too large.
344440 matches.

6.19 A sorted list of 1,000 ids is searched 500 times. Contrast repeated linear scans with sort-free binary search.

6.20 Keys 17 and 24 share a bucket over table size 7. Show the remainders.

Answers

6.1 Zero is the valid location of the first entry.

6.2 All earlier entries were already checked and did not match.

6.3 Arrival order is not necessarily sorted by the searched key, so the discarded half may contain the target.

6.4 Ensure a failed comparison excludes the middle and strictly shrinks the candidate interval.

6.5 Continue searching or scanning after a match and collect all matching positions; a single returned index is insufficient.

6.6 Two distinct keys map to the same hash-table location.

6.7 Clearing a slot carelessly can break a later lookup probing path; use the documented deletion rule.

6.8 When many lookups use hashable keys and the indexing and memory costs are justified.

6.9 1 and -1. It answers the first-match contract: one index, or the sentinel.

6.10 Index 5 after 2 comparisons. The first middle rules out the left half including itself.

6.11 -1 after 3 comparisons. The bounds cross, so the interval is empty.

6.12 The counter sits inside the match branch, so it counts at most one. Move comparisons += 1 before the if, so every inspected entry is counted.

6.13 low = mid and high = mid keep the tested middle in range, so the interval can stop shrinking. Use low = mid + 1 and high = mid - 1.

6.14 [1, 3]. A miss prints [], which is the every-match way of reporting absence.

6.15 echo-memo and not saved. The found exit returns a slot; the miss exit returns the message.

6.16 (-1, 16) and (-1, 4). Same sentinel answer; sixteen comparisons against four.

6.17 4, 5, 6 and 7. Each doubling adds exactly one comparison.

6.18 Index 4 after 3 comparisons. The trace visits the centre, then right, then the gap between.

6.19 Worst case, linear scans cost 500000 comparisons: 500 searches times 1,000 entries. Binary search costs at most 10 comparisons per search, so 500 searches cost at most 5000.

Sorting is already done, so no preparation remains.

6.20 17 modulo 7 is 3; 24 modulo 7 is 3. Same bucket, different keys.

Up next
Continue to the next chapter