Choosing how to search

Brute force or using the order · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Linear search

Search algorithms fall into 2 families. Brute-force search walks the structure element by element: linear search, BFS and DFS. It's simple, always works and needs no preparation, but costs O(n). Adaptive search takes advantage of something about the data: binary search uses order, hashing uses a table, and trees use their shape. It can be O(log n) or O(1), but the data needs preparing first.

Linear search works in many cases and needs no preparation. For a single search, the other methods take longer to prepare the data than linear search takes to walk it. It's fine with little data, where complexity barely shows. And it's fine with data that changes all the time, because there's no structure to maintain.

No search method always wins. The choice depends on how much data there is, how fast you need to answer, how often you search and how often you change it, and whether you need order or ranges. Little data or a single search: linear. Lots of data that barely changes: binary. Instant answers with no order: hash. Lots of changes and ranges: balanced tree.

Binary search

Binary search performs steadily with lots of data: the worst case is O(log n). But it needs the data in an array, that is in a contiguous block of memory, and sorted. That's why it isn't a good fit if you insert and delete often: keeping the array sorted costs O(n) per change.

Hash table

Hash search is O(1) on average, ideal when you need to answer very fast. But it keeps no order, so it's no good for range searches, like "every price between 100 and 200". Its performance depends on the hash function and collision handling, and it can degrade badly if there are many. And it uses extra memory to keep collisions low.

Binary search tree

Tree search handles huge amounts of data, because nodes can be scattered across memory, with no need for a contiguous block. It keeps data sorted, so it works for ranges. Its problem is that with many insertions and deletions it can lean and become O(n); an AVL or red-black tree prevents that, at the cost of the rebalancing work.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Brute force or using the order