You're looking for your roll number on a printed results list of 600 students, sorted by roll number. You don't start at the top and read every line. You open somewhere in the middle, see whether your number is before or after, and jump again. In about ten looks you've found it. Without thinking about it, you've used an algorithm: a clear set of steps that solves a problem.
What is an algorithm? It's a recipe for solving a problem: a list of exact steps that, followed in order, always gets you the answer. Algorithms aren't only for computers. Long division, the way you check change at a shop, and the route your cab app picks are all algorithms. In programming, an algorithm is the plan; code is that plan written in a language a computer can run.
What you need first: what is programming?
Key terms
- Algorithm: a finite list of clear steps that solves a problem.
- Input: the data the algorithm starts with, such as a list of numbers.
- Output: the result it produces, such as the largest number.
- Efficiency: how much time and memory an algorithm needs as the input grows.
- Linear search: checking items one by one until you find what you want.
- Binary search: repeatedly halving a sorted list to find an item quickly.
Everyday algorithms
| Problem | Algorithm (in short) |
|---|---|
| Making a cup of tea | Boil water, add tea, add milk and sugar, boil, strain |
| Finding a word in a dictionary | Open in the middle, go left or right by alphabet, repeat |
| Getting to college | Walk to the bus stop, take bus 45, get off at the third stop |
| Giving change of ₹63 | Use the biggest note or coin that fits, subtract, repeat |
| Checking if a number is even | Divide by 2; if there's no remainder, it's even |
None of these needs a computer. What makes them algorithms is that the steps are clear and always lead to an answer.
What makes a good algorithm
A proper algorithm has these properties:
| Property | Means | Bad example |
|---|---|---|
| Clear (unambiguous) | Each step has one meaning | "Add some sugar" |
| Has input and output | Takes data in, gives a result | |
| Finite | It stops after a limited number of steps | "Keep stirring" with no end |
| Correct | Gives the right answer for every valid input | Works for 5 but not for 0 |
| Efficient | Doesn't waste time or memory | Reading every page of a dictionary to find one word |
"Add some sugar" is fine for a person, but a computer needs "add 2 teaspoons of sugar". Turning vague steps into exact ones is a big part of programming.
Writing an algorithm: the largest number
Problem: find the largest number in a list of marks.
Algorithm in plain steps:
- Take the first number and call it the largest so far.
- Look at each of the other numbers in turn.
- If a number is bigger than the largest so far, it becomes the new largest so far.
- When every number has been checked, the largest so far is the answer.
Follow it by hand on [72, 88, 64, 95, 81]:
| Step | Number checked | Largest so far |
|---|---|---|
| Start | 72 | 72 |
| 1 | 88 | 88 |
| 2 | 64 | 88 |
| 3 | 95 | 95 |
| 4 | 81 | 95 |
The answer is 95. Now the same algorithm in Python. Each plain step becomes a line or two:
def largest(numbers):
biggest = numbers[0] # step 1
for n in numbers[1:]: # step 2
if n > biggest: # step 3
biggest = n
return biggest # step 4
print(largest([72, 88, 64, 95, 81]))
95
Python's built-in max() does the same job, and in real code you'd use it. But someone wrote max() using an algorithm very like this one.
Is it correct? Test the edge cases
An algorithm must work for every valid input, not just the example. Good testers try the awkward cases, called edge cases:
def largest(numbers):
biggest = numbers[0]
for n in numbers[1:]:
if n > biggest:
biggest = n
return biggest
print(largest([5])) # only one number
print(largest([-3, -9, -1])) # all negative
print(largest([7, 7, 7])) # all the same
5
-1
7
All correct. But what about an empty list? numbers[0] fails with IndexError, because there's no first item. The algorithm needs a rule for that case, such as "if the list is empty, say so". Thinking about edge cases is what separates an algorithm that usually works from one that always works.
A common wrong version starts with biggest = 0 instead of the first item. It works for marks, but gives 0 for [-3, -9, -1], which is wrong. Edge cases catch this.
Two algorithms for the same problem
Most problems can be solved in several ways, and some are far faster. Back to finding your roll number in a sorted list.
Linear search: check one by one
Start at the beginning and check each item until you find it.
def linear_search(items, target):
checks = 0
for i, item in enumerate(items):
checks += 1
if item == target:
return i, checks
return -1, checks
roll_numbers = list(range(1001, 1601)) # 600 students, sorted
print(linear_search(roll_numbers, 1550))
(549, 550)
It found roll number 1550 at position 549, after 550 checks.
Binary search: halve the list each time
This only works if the list is sorted. Look at the middle item. If it's the target, stop. If the target is bigger, throw away the left half; if smaller, throw away the right half. Repeat on what's left.
def binary_search(items, target):
low, high = 0, len(items) - 1
checks = 0
while low <= high:
checks += 1
mid = (low + high) // 2
if items[mid] == target:
return mid, checks
elif items[mid] < target:
low = mid + 1 # target is in the right half
else:
high = mid - 1 # target is in the left half
return -1, checks
roll_numbers = list(range(1001, 1601))
print(binary_search(roll_numbers, 1550))
(549, 8)
Same answer, in 8 checks instead of 550. The gap grows with the list. For 10 lakh sorted items, linear search may need 10 lakh checks; binary search needs at most 20, because 2²⁰ is just over 10 lakh. That's the difference between a search that feels instant and one that makes users wait.
| Items in sorted list | Linear search (worst case) | Binary search (worst case) |
|---|---|---|
| 100 | 100 checks | 7 checks |
| 10,000 | 10,000 checks | 14 checks |
| 10,00,000 | 10,00,000 checks | 20 checks |
Why efficiency matters
For 10 items, any algorithm is fast. For the millions of records real apps handle, the choice of algorithm decides whether a page loads in 0.1 seconds or 10 minutes. Programmers describe how an algorithm's work grows with the input using Big-O notation: linear search is O(n), meaning the work grows in step with the number of items; binary search is O(log n), which grows extremely slowly. Big-O notation explains it.
This is why companies ask about algorithms in interviews: they want to see that you can find a solution, check it's correct, and judge whether it's fast enough.
Algorithms you use every day without noticing
- Google Maps uses shortest-path algorithms to find your route.
- Instagram and YouTube use recommendation algorithms to choose what you see next.
- UPI and banks use encryption algorithms to keep payments secret.
- Spell check uses algorithms that measure how different two words are.
- Photo filters use algorithms that change every pixel's colour values.
Common mistakes
- Starting to code before you have the steps. Write the algorithm in plain words first.
- Vague steps like "find the answer" or "sort it out".
- Not testing edge cases: empty input, one item, negative numbers, duplicates.
- Using binary search on an unsorted list, which gives wrong answers.
- Assuming the first working solution is good enough for large data.
Practice
- Write an algorithm, in numbered plain steps, to count how many students passed (40 or more) in a list of marks.
Show the answer
- Set a counter to 0. 2. Look at each mark in turn. 3. If the mark is 40 or more, add 1 to the counter. 4. When all marks are checked, the counter is the answer.
marks = [72, 35, 88, 40, 12]
count = 0
for m in marks:
if m >= 40:
count += 1
print(count)
3
- What's wrong with this algorithm for making tea: "1. Boil water. 2. Add tea. 3. Keep boiling."?
Show the answer
Step 3 never ends, so it isn't finite. It also isn't clear: how much water, how much tea, how long? A fixed version: "3. Boil for 2 minutes. 4. Strain into a cup."
- Follow binary search by hand to find 23 in
[4, 8, 15, 16, 23, 42, 50]. Which positions does it check?
Show the answer
low = 0, high = 6, mid = 3: item 16 is less than 23, so low = 4. low = 4, high = 6, mid = 5: item 42 is greater, so high = 4. low = 4, high = 4, mid = 4: item 23, found. It checks positions 3, 5 and 4: three checks.
- Write a Python function
smallest(numbers)using the same idea aslargest, and test it on[34, -2, 17].
Show the answer
def smallest(numbers):
lowest = numbers[0]
for n in numbers[1:]:
if n < lowest:
lowest = n
return lowest
print(smallest([34, -2, 17]))
-2
- About how many checks does binary search need, at most, for a sorted list of 1,000 items? Explain.
Show the answer
About 10. Each check halves the list: 1,000, 500, 250, 125, 63, 32, 16, 8, 4, 2, 1. Since 2¹⁰ = 1,024 is just over 1,000, at most 10 halvings are needed.
Interview questions
What is an algorithm?
A finite, well-defined sequence of steps that takes some input and produces the correct output for a problem. Good algorithms are unambiguous, correct for all valid inputs, and efficient in time and memory.
What is the difference between linear search and binary search?
Linear search checks items one by one and works on any list, taking O(n) time. Binary search repeatedly halves a sorted list, taking O(log n) time, but only works if the list is sorted.
What is the difference between an algorithm and a program?
An algorithm is the method, independent of any language. A program is an algorithm (usually several) written in a specific programming language so a computer can run it.
Key takeaways
- An algorithm is a clear, finite list of steps that solves a problem; code is an algorithm written for a computer.
- Good algorithms are unambiguous, correct for every valid input, finite and efficient.
- Write the steps in plain words first, then turn each step into code.
- Test edge cases: empty input, one item, negatives, duplicates.
- Different algorithms for the same problem can differ hugely in speed, like linear vs binary search.
Frequently asked questions
Is an algorithm the same as code?
No. An algorithm is the idea, the steps. Code is one way of writing those steps for a computer. The same algorithm can be written in Python, Java or everyday English.
Do I need to learn algorithms to get a job?
For most product companies and many service companies in India, yes: coding interviews test data structures and algorithms. Start after you're comfortable with one language; see what is DSA?.
Are algorithms hard to learn?
The basic ones, like searching and counting, are not. Harder ones take practice, but they're built from the same small ideas you've seen here: loops, conditions, and breaking problems into steps.
What to learn next
- Learn to break problems into steps in think like a programmer.
- Write algorithms before code with pseudocode and flowcharts.
- Measure algorithm speed with Big-O notation.