Data structures and algorithms, or DSA, are ways to store data and solve problems with it. A data structure decides how values are arranged. An algorithm is a clear list of steps that uses those values to reach an answer.
A list of phone numbers is a data structure. Searching it for one number is an algorithm. A better arrangement can make the search much faster. This guide shows the main ideas, code in three languages and a study order for beginners.
Data structures and algorithms: the main types
| Data structure | Main idea | Common use |
|---|---|---|
| Array | Values by position | Marks, lists of items |
| Linked list | Each node points to another | Frequent changes at a known node |
| Stack | Last in, first out | Undo, matching brackets |
| Queue | First in, first out | Jobs waiting in order |
| Hash table | Find a value by its key | Counts, lookups |
| Tree | Parent and child values | Folders, ordered data |
| Heap | Quickly get smallest or largest | Task priority |
| Graph | Points joined by links | Maps, networks |
| Algorithm type | What it does | Example |
|---|---|---|
| Searching | Finds a value | Binary search |
| Sorting | Puts values in order | Merge sort |
| Traversal | Visits every part | Tree or graph search |
| Greedy | Takes a good choice now | Some scheduling problems |
| Dynamic programming | Reuses answers to small parts | Fewest coins |
| Backtracking | Tries, then goes back | Solving a maze |
An algorithm should handle all valid inputs, stop and give the correct answer. Fast but wrong is not useful.
Understand time and space with Big O
Big O describes how work grows when input grows. It is not the exact number of seconds. Suppose n is the number of values.
| Big O | Growth | Example |
|---|---|---|
| O(1) | Stays about the same | Read array[3] |
| O(log n) | Adds a little when n doubles | Binary search |
| O(n) | Doubles when n doubles | Check each value |
| O(n log n) | A bit more than doubles | Merge sort |
| O(n²) | About four times when n doubles | Compare all pairs |
If you must look at all 1,000 values once, that is linear work, O(n). If you compare each value with every other value, the work grows as O(n²).
Space complexity describes extra memory. Two variables use O(1) extra space. A new list with n values uses O(n).
Interview note: Say what
nmeans. Then state worst-case time and extra space. If you mention average time for a hash table, also say that its worst case can be slower.
Arrays, hash tables, stacks and queues
Reading an array by index is O(1). Searching an unsorted array can take O(n), because the value may be last or missing. Inserting at the front also takes O(n) because other values must move.
A hash table stores values by key. Average lookup is O(1), which is useful when you need to remember what you have seen. Try it in find a pair with a given sum.
A stack uses push and pop at one end:
push A, push B, push C
pop -> C
pop -> B
A queue removes the oldest item first:
add A, add B, add C
remove -> A
remove -> B
Use a stack when the newest item must be handled first. Use a queue when the oldest item must be handled first.
Data structures and algorithms in Java
Java has ready classes for most common structures. Use ArrayList for a list, HashMap for keys, ArrayDeque for a stack or queue and PriorityQueue for a heap.
This program checks whether brackets match:
import java.util.ArrayDeque;
import java.util.Deque;
public class BracketCheck {
static boolean valid(String text) {
Deque<Character> stack = new ArrayDeque<>();
for (char ch : text.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else if (ch == ')' || ch == ']' || ch == '}') {
if (stack.isEmpty()) return false;
char open = stack.pop();
if (ch == ')' && open != '(') return false;
if (ch == ']' && open != '[') return false;
if (ch == '}' && open != '{') return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(valid("{[()]}"));
System.out.println(valid("([)]"));
System.out.println(valid("(("));
}
}
Output:
true
false
false
Each character is pushed or popped at most once, so time is O(n). The stack can hold n opening brackets, so extra space is O(n). Read more about Java lists in ArrayList vs LinkedList.
Data structures and algorithms in Python
Python's list is a dynamic array. dict is a hash table, set stores unique values, and deque is good for a queue.
This breadth-first search finds the fewest steps between two places. It uses a graph and a queue:
from collections import deque
def shortest_steps(graph, start, goal):
queue = deque([(start, 0)])
seen = {start}
while queue:
place, steps = queue.popleft()
if place == goal:
return steps
for next_place in graph.get(place, []):
if next_place not in seen:
seen.add(next_place)
queue.append((next_place, steps + 1))
return -1
roads = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": ["E"],
}
print(shortest_steps(roads, "A", "E"))
print(shortest_steps(roads, "E", "A"))
Output:
3
-1
Every link is one step, so this search visits nearer places first. From A to E takes three steps. Links here go one way, so E cannot reach A. If there are V places and E links, time is O(V + E).
Common mistake: Using
list.pop(0)as a queue makes Python move the remaining values. Usedeque.popleft()instead.
Data structures and algorithms in C++
C++ gives you the Standard Template Library, or STL. Common choices are vector, stack, queue, unordered_map and priority_queue.
Binary search works on sorted data. It checks the middle and removes half of the remaining values:
#include <iostream>
#include <vector>
int findIndex(const std::vector<int>& nums, int target) {
int left = 0;
int right = static_cast<int>(nums.size()) - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
std::vector<int> nums = {3, 7, 10, 14, 20, 25};
std::cout << findIndex(nums, 14) << '\n';
std::cout << findIndex(nums, 8) << '\n';
}
The result for 14 is index 3. The result for 8 is -1 because it is missing. In the search for 14, the code checks 10, then 20, then 14. Time is O(log n) and extra space is O(1). For a Java walk-through, see binary search in Java.
| Your goal | Suitable language |
|---|---|
| Java developer jobs | Java |
| Data or Python work | Python |
| Competitive programming | C++, if you like it |
| Campus interview | The allowed language you know best |
The ideas stay the same. Pick one language and do not switch each week.
Data structures and algorithms for GATE
GATE Computer Science tests both ideas and careful calculation. The official GATE 2027 CS syllabus from IIT Madras lists programming in C and recursion. Its data structure topics include arrays, stacks, queues, linked lists, trees, binary search trees, binary heaps and graphs. The separate Algorithms section should be checked in the same official PDF.
Use a different practice method from an interview:
- Trace C code, pointers and recursive calls by hand.
- Solve recurrence relations and compare growth rates.
- Draw a tree or heap after each change.
- Practise graph, sorting and shortest-path questions.
- Solve past questions with a timer and review every error.
GATE questions may have no code to write. Still, short programs help you test an idea. Check the official syllabus and paper pattern for your exam year.
A 12-week plan for beginners
| Weeks | Topics | Result to aim for |
|---|---|---|
| 1 to 2 | Loops, arrays, strings, Big O | Explain each loop |
| 3 | Hash tables and sets | Count and find values fast |
| 4 | Stacks and queues | Solve bracket and queue tasks |
| 5 | Searching and sorting | Write and trace binary search |
| 6 | Linked lists | Draw links before coding |
| 7 | Recursion and backtracking | State the stopping case |
| 8 to 9 | Trees, search trees and heaps | Traverse and insert values |
| 10 | Graphs | Write BFS and DFS |
| 11 | Dynamic programming | Define a small subproblem |
| 12 | Mixed timed practice | Choose a method yourself |
Adjust the weeks if you have classes or work. For each topic, do two easy problems together with notes, three easy ones alone and then two medium ones.
Pro tip: Try a problem for about 25 minutes. If you are stuck, read one hint. After reading a full answer, close it and write the code again. Retry it three days later.
When you solve a problem, use this order:
- Repeat the question in your own words.
- Write one normal and two edge cases.
- Explain a simple answer and its time.
- Find repeated work and improve it.
- Trace your code before running it.
- Test empty, single and repeated values where valid.
Start with finding the largest array element and checking anagrams. Then compare arrays and linked lists. When you can explain time and space without reading, try the DSA interview questions.
Frequently Asked Questions
Which language is best for learning DSA?
Can I learn DSA without strong maths?
Is DSA needed for every software job?
How many DSA problems should I solve?
Should I learn data structures before algorithms?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — See the Java Full Stack course in Hyderabad

