Sub topic 1
What It Means to Search a Collection
Searching is one of the most common things a program does. You might be checking whether a username is taken, finding a product by its ID, or locating where a new value belongs in a sorted list. This chapter defines the search problem before any algorithm appears, so later chapters can measure every search method against the same definition.
Prerequisites
This tutorial assumes you can already:
- Write basic programs in Python or Java.
- Work with arrays or lists and zero-based indexing, where the first element is at index 0.
- Use loops, conditionals, and functions.
- Read Big-O notation such as O(n) and O(1) at a basic level.
The examples use Python. The ideas carry over directly to Java and other languages.
The search problem, stated precisely
A search takes two inputs:
- A collection, such as a list or array of elements.
- A target, which is the value you are looking for.
It produces one output: the position of an element that matches the target, or a signal that no element matches.
That sounds simple, but a precise version has to answer several questions:
| Question | Common answer in this tutorial |
|---|---|
| What counts as a match? | The element equals the target (`==`), or its key equals the target key |
| Which match is returned if there are several? | The first one, unless stated otherwise |
| How is "not found" reported? | Return `-1`, an index that can never be valid |
| Is the collection ordered? | Sometimes. This decides which algorithms you can use |
Each later chapter states its own choices. For example, lower-bound search returns an insertion point instead of -1.
Membership versus position
There are two related questions you can ask:
- Membership: is the target in the collection? The answer is yes or no.
- Position: where is the target? The answer is an index.
If you know the position, you also know membership, so position is the more general question. Python's built-ins offer both, and they report "not found" in different ways:
items = [4, 2, 7, 1, 7]
print(7 in items) # True (membership)
print(items.index(7)) # 2 (position of the first match)
try:
items.index(5)
except ValueError:
print("5 not found") # list.index raises instead of returning -1Both operations scan the list from the start. The next chapter writes that scan by hand.
Searching by key
Real collections usually hold records, not bare numbers. In that case you match on a key, which is one field that identifies the record:
users = [
{"id": 17, "name": "Ana"},
{"id": 42, "name": "Ben"},
{"id": 8, "name": "Chen"},
]
def find_by_id(records, target_id):
for i, record in enumerate(records):
if record["id"] == target_id:
return i
return -1
print(find_by_id(users, 42)) # 1
print(find_by_id(users, 99)) # -1The algorithm stays the same. Only the comparison changes.
Common mistakes in defining a search
- Using a valid index as "not found." If you return
0for a miss, a caller can't tell it apart from a match at index 0. Use-1,None, or an exception. - Assuming a unique match. With duplicates, you need to decide whether you want the first, the last, or a count of all matches.
- Ignoring order. An unordered collection can only be searched by checking elements one at a time. A sorted collection lets you skip most of the elements. That difference is the topic of the rest of this tutorial.
Exercise
A function returns 0 when the target is not found and the index otherwise. Called on [9, 5, 3] with target 9, it returns 0. What is wrong with this design, and how would you fix it?
Show answer
Index 0 is a valid position, so the caller cannot tell "found at index 0" from "not found." Return a value that can never be a valid index, such as -1, or return None, or raise an exception for a miss.
Exercise
The list [3, 8, 3, 1] is searched for 3. Name two different answers a search function could reasonably return, and say what contract each one follows.
Show answer
It could return 0, following a "first match" contract, or 2, following a "last match" contract. A third valid design returns the count 2 under a "count all matches" contract.