DSA Introduction
Data structures store data in useful ways, and algorithms are the steps that work on that data.
What is a Data Structure?
A data structure is a way of organising data so it can be used well. You already use them in daily life:
| Real life | Data structure |
|---|---|
| A row of lockers with numbers | Array |
| A pile of plates | Stack |
| A line at a bank counter | Queue |
| A phone contact list (name to number) | Hash table |
| A family tree | Tree |
| A map of roads between cities | Graph |
What is an Algorithm?
An algorithm is a clear set of steps to solve a problem. A recipe for making chai is an algorithm: boil water, add tea, add milk, add sugar, boil again, pour.
In programming, algorithms do jobs like searching for an item, sorting a list, or finding the shortest path between two places.
A good algorithm is:
- Correct: it always gives the right answer
- Clear: each step is exact, with no guessing
- Finite: it finishes after some steps
- Efficient: it does not waste time or memory
Why Does It Matter?
Imagine a shop in Karachi with 1,000,000 products. Two ways to find a product by its code:
- Check every product one by one. In the worst case that is 1,000,000 checks.
- Keep the codes sorted and use binary search. That needs only about 20 checks.
Both are correct, but the second is enormously faster. Choosing the right method is what DSA teaches you.
A Simple Algorithm in Python
This algorithm counts how many students passed:
Example
marks = [72, 45, 88, 39, 91, 60]
passed = 0
for m in marks:
if m >= 50:
passed += 1
print("Passed:", passed, "out of", len(marks))Passed: 4 out of 6
The steps are simple: start a counter at zero, look at each mark, and add one when the mark is 50 or more.
Choosing a Data Structure
The same data can be stored in different ways. Here a list and a dictionary both hold phone numbers, but finding a number is easier with the dictionary:
Example
contacts_list = [("Ali", "0300-1111111"), ("Sara", "0321-2222222")]
for name, phone in contacts_list:
if name == "Sara":
print("From list:", phone)
contacts_dict = {"Ali": "0300-1111111", "Sara": "0321-2222222"}
print("From dict:", contacts_dict["Sara"])From list: 0321-2222222 From dict: 0321-2222222
The list has to be checked item by item. The dictionary jumps straight to the answer. You will see why in the hash tables lesson.
To follow this tutorial you need basic Python: variables, lists, loops, functions and classes. If you are new to Python, learn those first.
Linear and Non-linear Structures
- Linear: items are in a sequence, one after another. Arrays, linked lists, stacks and queues.
- Non-linear: items connect in branches or networks. Trees and graphs.
Exercise
Exercise
A line of customers waiting at a bank counter is most like which data structure?
