↗ RankSenseAll coursesPlacement prep

Home / Data Structures and Algorithms Tutorials

FREE ENGINEERING LEARNING RESOURCES

Data Structures and Algorithms Tutorials

Learn DSA with examples of arrays, recursion, sorting, graphs, trees and dynamic programming.

Month 2 Complexity analysis

Concept & theory

Big-O describes how resource use grows with input size. O(1) constant; O(log n) halves the search space; O(n) scans; O(n²) nested scans. Distinguish worst and average cases.

Example code

def contains(nums, target):
    for x in nums:
        if x == target:
            return True
    return False

Code explained

The loop may inspect n elements, so worst-case time is O(n). Only a few variables are used, so extra space is O(1).

Try it yourself

Compare linear search with binary search on sorted inputs; explain why sorting matters.

Month 2 Arrays and two pointers

Concept & theory

An array offers indexed access. Two pointers exploit order to reduce nested pair searches to a linear scan when input is sorted.

Example code

def pair_sum(a, target):
    left, right = 0, len(a)-1
    while left < right:
        total = a[left] + a[right]
        if total == target: return (left, right)
        if total < target: left += 1
        else: right -= 1
    return None

Code explained

Pointers start at both ends. If sum is small, advance left; if large, retreat right. Each pointer moves at most n times: O(n) time.

Try it yourself

Find whether a sorted array contains a pair totaling 15; handle duplicates.

Month 2 Strings and sliding window

Concept & theory

A sliding window maintains a contiguous range and updates it incrementally instead of recomputing every substring.

Example code

def longest_unique(s):
    seen = {}
    start = best = 0
    for end, ch in enumerate(s):
        if ch in seen and seen[ch] >= start:
            start = seen[ch] + 1
        seen[ch] = end
        best = max(best, end-start+1)
    return best

Code explained

seen tracks last positions. start skips past a repeated character; best stores maximum window length. Each character is processed once: O(n) time.

Try it yourself

Try abcabcbb, bbbbb, and an empty string; explain outputs.

Month 3 Recursion and backtracking

Concept & theory

A recursive function solves a smaller instance and needs a base case. Backtracking explores choices, then undoes them to explore alternatives.

Example code

def subsets(a):
    out = []
    def dfs(i, path):
        if i == len(a):
            out.append(path.copy()); return
        dfs(i+1, path)
        path.append(a[i]); dfs(i+1, path)
        path.pop()
    dfs(0, [])
    return out

Code explained

At each index, choose exclude or include. copy saves a snapshot; pop undoes inclusion. There are 2^n subsets and output size is O(n·2^n).

Try it yourself

Generate all subsets of [1,2,3] and trace the call tree.

Month 3 Linked lists

Concept & theory

Nodes hold a value and a pointer to the next node. Insertions at the head are O(1); random indexing is O(n).

Example code

class Node:
    def __init__(self, value, next=None):
        self.value, self.next = value, next
def reverse(head):
    prev = None
    while head:
        nxt = head.next
        head.next = prev
        prev, head = head, nxt
    return prev

Code explained

nxt preserves the remainder; head.next reverses one link; prev advances. O(n) time and O(1) extra space.

Try it yourself

Build 1→2→3, reverse it, and check the new head is 3.

Month 3 Stacks and queues

Concept & theory

A stack uses LIFO; a queue uses FIFO. Stacks help parse nested syntax; queues support breadth-first traversal.

Example code

def balanced(text):
    stack = []
    pairs = {')':'(', ']':'[', '}':'{'}
    for c in text:
        if c in '([{': stack.append(c)
        elif c in pairs:
            if not stack or stack.pop() != pairs[c]: return False
    return not stack

Code explained

Opening brackets push. Closing brackets must match the most recent opening bracket. Empty stack at end means balanced.

Try it yourself

Check {[]}, ([)], and ((); explain each.

Month 3 Binary search

Concept & theory

Binary search requires a sorted search space or a monotonic condition. Each step discards half the candidates.

Example code

def binary_search(a, x):
    lo, hi = 0, len(a)-1
    while lo <= hi:
        mid = lo + (hi-lo)//2
        if a[mid] == x: return mid
        if a[mid] < x: lo = mid+1
        else: hi = mid-1
    return -1

Code explained

mid selects the center. Comparison removes one half; O(log n) time, O(1) space.

Try it yourself

Find the first occurrence in [1,2,2,2,5].

Month 3 Sorting

Concept & theory

Insertion sort is easy to implement and good for small/nearly sorted inputs; merge sort gives O(n log n) worst-case time with O(n) auxiliary memory.

Example code

def merge_sort(a):
    if len(a) <= 1: return a
    m = len(a)//2
    left = merge_sort(a[:m]); right = merge_sort(a[m:])
    i = j = 0; out = []
    while i < len(left) and j < len(right):
        if left[i] <= right[j]: out.append(left[i]); i += 1
        else: out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

Code explained

Recursively divide into halves, then merge two sorted lists. The <= comparison keeps equal elements in original relative order.

Try it yourself

Trace [5,1,4,2] through split and merge stages.

Month 4 Trees and traversals

Concept & theory

Trees model hierarchy. Binary-tree DFS traversals: preorder root-left-right, inorder left-root-right, postorder left-right-root.

Example code

def inorder(root):
    if root is None: return []
    return inorder(root.left) + [root.val] + inorder(root.right)

Code explained

Base case returns empty list. Recursion visits left subtree, current node, then right. In a BST this yields sorted keys.

Try it yourself

Construct a 3-node BST and show all three traversal orders.

Month 4 Graphs: BFS and DFS

Concept & theory

Graphs consist of vertices and edges. BFS uses a queue and finds shortest paths in unweighted graphs; DFS explores deeply using recursion or a stack.

Example code

from collections import deque
def bfs(graph, source):
    q = deque([source]); seen = {source}; order = []
    while q:
        u = q.popleft(); order.append(u)
        for v in graph.get(u, []):
            if v not in seen:
                seen.add(v); q.append(v)
    return order

Code explained

Queue processes nodes in discovery order. seen prevents cycles and repeated work. O(V+E) time with adjacency lists.

Try it yourself

Find shortest number of edges from A to D by tracking parent nodes.

Month 4 Dynamic programming

Concept & theory

DP solves overlapping subproblems by caching results. Define state, transition, base cases, and iteration order before coding.

Example code

def climb(n):
    if n < 0: return 0
    a, b = 1, 1
    for _ in range(2, n+1):
        a, b = b, a+b
    return b

Code explained

Ways(n)=Ways(n−1)+Ways(n−2) because the last step is 1 or 2. Two variables store previous states: O(n) time, O(1) space.

Try it yourself

Compute ways for 0, 1, 2, 5 stairs and explain base cases.

Explore more topics

C++ Tutorials for Beginners
Python Tutorials for Beginners
Java Tutorials and OOP
Core Computer Science Tutorials
Web Development Tutorials
Engineering Placement Preparation
Beginner Programming Projects
SEO Tutorials and Technical SEO