Python Data Structures, Algorithms & OOP: 50 Solved Coding
Problems with Clean Code, Outputs & Step-by-Step Logic
Exam-Ready Lab Exercises, Tracing Walkthroughs & Complexity Analysis for CS Students
50 problems | 5 modules | every program run and verified | real console output | Big-O for every solution
Quick-Reference: Big-O Time & Space Complexity (Python 3)
Lists (dynamic array) - space O(n)
Operation Average Worst Note
a[i], len(a) O(1) O(1) direct index
a.append(x), a.pop() O(1) O(1) amortised at the end
a.insert(i, x), a.pop(i), del a[i] O(n) O(n) items shift
x in a, a.index(x), a.remove(x) O(n) O(n) linear scan
a[i:j] (slice) O(k) O(k) k = slice length
a.sort() / sorted(a) O(n log n) O(n log n) Timsort; O(n) if nearly sorted
Dictionaries (hash table) - space O(n)
Operation Average Worst Note
d[k], d[k] = v, del d[k] O(1) O(n) worst case = many collisions
k in d, d.get(k) O(1) O(n)
Iterate keys / values / items O(n) O(n) insertion order kept
Sets (hash table, unique items) - space O(n)
Operation Average Worst Note
s.add(x), s.remove(x), x in s O(1) O(n)
a | b (union) O(a + b) O(a + b)
a & b (intersection) O(min(a, b)) O(a * b)
a - b (difference) O(a) O(a)
Tuples (immutable, hashable if all items are) - space O(n)
Operation Average Worst Note
t[i], len(t) O(1) O(1) cannot be changed
x in t, t.count(x), t.index(x) O(n) O(n) linear scan
t1 + t2 (new tuple) O(a + b) O(a + b) copies both
Binary Search (sorted data only)
Version Time Space Note
Iterative O(log n) O(1) halves the range each step
Recursive O(log n) O(log n) one stack frame per halving
Sorting Algorithms
Algorithm Best Average Worst Extra space
Bubble (early exit) O(n) O(n^2) O(n^2) O(1)
Insertion O(n) O(n^2) O(n^2) O(1)
Selection O(n^2) O(n^2) O(n^2) O(1)
Merge sort O(n log n) O(n log n) O(n log n) O(n)
Quick sort O(n log n) O(n log n) O(n^2) O(log n)
Heap sort O(n log n) O(n log n) O(n log n) O(1)
Python sorted() / .sort() O(n) O(n log n) O(n log n) O(n)
Recursion Patterns
Pattern Time Stack / extra space
Factorial, sum of list (one call per level) O(n) O(n)
Fibonacci, plain recursion (two calls) O(2^n) O(n)
Fibonacci with memoization O(n) O(n)
Halving the input (binary search) O(log n) O(log n)
Tower of Hanoi / all subsets O(2^n) O(n) stack
All permutations / N-Queens style O(n!) O(n)
Python's default recursion limit is 1000 frames (sys.getrecursionlimit()). Rule of thumb: nested loops over n items = O(n2); halving each step =
O(log n); a dictionary or set lookup = O(1) on average.
,Table of Contents & Problem Index
Difficulty: Easy (20) Medium (20) Exam-Hard (10)
Module 1: Strings & Arrays/Lists (Problems 1-12)
1 Palindrome Checker Ignoring Case and Punctuation Easy 3
2 Vowel, Consonant and Letter Frequency Counter Easy 4
3 Caesar Cipher: Encrypt and Decrypt Easy 5
4 Longest Word and Word-Length Report Easy 6
5 Run-Length Encoding and Decoding Medium 7
6 Reverse Each Word and Reverse Word Order Easy 8
7 Rotate a List Right by k Positions In-Place Medium 8
8 All Pairs with a Given Sum (Two-Pointer Technique) Medium 10
9 Maximum Subarray Sum with Indices (Kadane's Algorithm) Medium 11
10 Merge Two Sorted Lists Easy 12
11 Remove Duplicates While Preserving Order Easy 12
12 Spiral Order Traversal of a Matrix Exam-Hard 13
Module 2: Dictionaries, Sets & Hashing (Problems 13-22)
13 Word Frequency Counter with Top-K Words Easy 14
14 Group Words That Are Anagrams Medium 15
15 First Non-Repeating Character Easy 15
16 Two Sum Using a Hash Map Medium 16
17 Student Marks Report Using a Dictionary Easy 17
18 Course Enrolment Analysis Using Set Operations Easy 18
19 Longest Substring Without Repeating Characters Exam-Hard 18
20 Count Subarrays with Sum Equal to K (Prefix Sums) Exam-Hard 19
21 Isomorphic Strings Medium 20
22 Hash Table with Separate Chaining Exam-Hard 21
Module 3: Recursion, Searching & Sorting (Problems 23-32)
23 Factorial and Fibonacci: Plain Recursion vs Memoization Easy 22
24 Tower of Hanoi: Listing Every Move Medium 23
25 Generate All Subsets (Power Set) Recursively Medium 23
26 Iterative Binary Search with Comparison Count Easy 24
27 Recursive Binary Search for the First Occurrence Medium 25
28 Bubble Sort with Early Exit and Swap Count Easy 26
29 Insertion Sort with Step-by-Step Trace Easy 27
30 Merge Sort with Inversion Count Exam-Hard 28
31 Quick Sort with Lomuto Partition Medium 29
32 N-Queens Using Backtracking Exam-Hard 30
Module 4: Stacks, Queues & Linked Lists (Problems 33-41)
33 Balanced Brackets Checker Using a Stack Easy 31
34 Evaluate a Postfix Expression Medium 32
35 Convert Infix to Postfix (Shunting-Yard Algorithm) Exam-Hard 33
36 Implement a Queue Using Two Stacks Medium 34
37 Circular Queue with Fixed Capacity Medium 35
38 Singly Linked List: Insert, Delete and Display Easy 36
39 Reverse a Linked List (Iterative and Recursive) Medium 37
40 Detect a Cycle and Find Its Length and Start (Floyd) Exam-Hard 38
41 Merge Two Sorted Linked Lists Medium 39
Module 5: OOP - Classes, Inheritance & Polymorphism (Problems 42-50)
42 BankAccount Class with Custom Exception and History Easy 40
43 Student Class: Class Variable, Static Method and Class Method Easy 41
44 Inheritance and Method Overriding: Employee and Manager Medium 42
45 Polymorphism with an Abstract Base Class (Shapes) Medium 43
46 Operator Overloading: A 2D Vector Class Medium 45
47 Fraction Class with Arithmetic, Comparison and Sorting Exam-Hard 46
48 Encapsulation with Properties: A Temperature Class Easy 47
49 Stack Class with Custom Exception, __len__ and __iter__ Medium 48
50 Multiple Inheritance and Method Resolution Order (Diamond) Exam-Hard 50
Python Data Structures, Algorithms & OOP | 50 Solved Coding Problems Page 2
, Module 1: Strings & Arrays/Lists (Problems 1-12)
Problem 1: Palindrome Checker Ignoring Case and Punctuation Difficulty: Easy
Problem Statement: Write a function is_palindrome(text) that returns True if text reads the same forwards and
backwards after ignoring case, spaces and punctuation. Use two pointers (no slicing shortcut such as text[::-1]). Test it
on four strings, including an empty string.
Sample Input: "A man, a plan, a canal: Panama" | "Hello, World!" | "No lemon, no melon" | ""
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def is_palindrome(text):
# keep only letters/digits, converted to lowercase
cleaned = [ch.lower() for ch in text if ch.isalnum()]
left, right = 0, len(cleaned) - 1
while left < right: # walk towards the centre
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
tests = ["A man, a plan, a canal: Panama", "Hello, World!", "No lemon, no melon", ""]
for s in tests:
print(f'"{s}" -> {is_palindrome(s)}')
Sample Output
"A man, a plan, a canal: Panama" -> True
"Hello, World!" -> False
"No lemon, no melon" -> True
"" -> True
Step-by-Step Logic & Complexity
How It Works: The function first keeps only letters and digits in lowercase, so the first test becomes
amanaplanacanalpanama. Two indices start at opposite ends and move towards the centre; the first mismatch returns
False, and meeting in the middle proves every mirrored pair matched. An empty string has nothing to compare, so it
counts as a palindrome.
Time Complexity: O(n) — one pass to clean the text plus at most n/2 comparisons.
Space Complexity: O(n) — the list of cleaned characters.
Python Data Structures, Algorithms & OOP | 50 Solved Coding Problems Page 3
, Problem 2: Vowel, Consonant and Letter Frequency Counter Difficulty: Easy
Problem Statement: Write count_letters(text) that returns the number of vowels, the number of consonants and a
dictionary of letter frequencies (ignore case, digits, spaces and punctuation). Print the vowel count, the consonant
count and the three most frequent letters; break ties alphabetically.
Sample Input: text = "Data Structures in Python"
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def count_letters(text):
vowels = set("aeiou")
v = c = 0
freq = {}
for ch in text.lower():
if ch.isalpha(): # skip spaces, digits, punctuation
freq[ch] = freq.get(ch, 0) + 1
if ch in vowels:
v += 1
else:
c += 1
return v, c, freq
v, c, freq = count_letters("Data Structures in Python")
print("Vowels:", v)
print("Consonants:", c)
top3 = sorted(freq.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
print("Top 3 letters:", top3)
Sample Output
Vowels: 7
Consonants: 15
Top 3 letters: [('t', 4), ('a', 2), ('n', 2)]
Step-by-Step Logic & Complexity
How It Works: Each character is lowercased, skipped if it is not a letter, and tallied in a dictionary; letters found in the
vowel set also raise the vowel counter, all others the consonant counter. The 22 letters of the sample split into 7 vowels
and 15 consonants, and 't' occurs four times so it ranks first. Sorting by (-count, letter) makes ties alphabetical, so the
output is always the same.
Time Complexity: O(n) — one pass over n characters; sorting at most 26 letters is constant work.
Space Complexity: O(1) — the dictionary never holds more than 26 letters.
Python Data Structures, Algorithms & OOP | 50 Solved Coding Problems Page 4