
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































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
Quick-Reference: Big-O Time & Space Complexity (Python 3)
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
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
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)
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
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
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)
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(n^2 ); halving each step = O(log n); a dictionary or set lookup = O(1) on average.
Difficulty: Easy (20) Medium (20) Exam-Hard (10)
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.
Problem 3: Caesar Cipher: Encrypt and Decrypt Difficulty: Easy
Problem Statement: Implement shift_text(text, key) that shifts every letter by key positions in the alphabet, wrapping
from Z to A, preserving upper/lower case and leaving other characters unchanged. Show that decryption is the same
function with the negative key.
Sample Input: msg = "Attack at Dawn, 5 PM!" key = 3
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def shift_text(text, key): out = [] for ch in text: if ch.isupper(): out.append(chr((ord(ch) - ord("A") + key) % 26 + ord("A"))) elif ch.islower(): out.append(chr((ord(ch) - ord("a") + key) % 26 + ord("a"))) else: out.append(ch) # digits, spaces, punctuation return "".join(out)
msg = "Attack at Dawn, 5 PM!" enc = shift_text(msg, 3) dec = shift_text(enc, -3) print("Original :", msg) print("Encrypted:", enc) print("Decrypted:", dec)
Sample Output
Original : Attack at Dawn, 5 PM! Encrypted: Dwwdfn dw Gdzq, 5 SP! Decrypted: Attack at Dawn, 5 PM!
Step-by-Step Logic & Complexity
How It Works: Upper- and lower-case letters are shifted separately: subtract the base ('A' or 'a'), add the key, wrap
with % 26, then add the base back. 'A' with key 3 becomes 'D' and 'k' becomes 'n' (a letter such as 'x' would wrap round
to 'a'). Decryption simply applies a negative key, and digits, spaces and punctuation are copied unchanged.
Time Complexity: O(n) — each of the n characters is processed once.
Space Complexity: O(n) — the output list holds n characters.
Problem 5: Run-Length Encoding and Decoding Difficulty: Medium
Problem Statement: Implement rle_encode(s), which compresses runs of equal characters into character+count pairs
(e.g. 'aaab' becomes 'a3b1'), and rle_decode(enc), which restores the original string. Assume the original string
contains no digits. Verify that decoding the encoded text returns the input.
Sample Input: data = "aaabccddddde"
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def rle_encode(s): if not s: return "" parts = [] count = 1 for i in range(1, len(s)): if s[i] == s[i - 1]: count += 1 # run continues else: parts.append(s[i - 1] + str(count)) count = 1 # new run starts parts.append(s[-1] + str(count)) # flush the last run return "".join(parts)
def rle_decode(enc): out = [] i = 0 while i < len(enc): ch = enc[i] i += 1 num = "" while i < len(enc) and enc[i].isdigit(): num += enc[i] # counts may have several digits i += 1 out.append(ch * int(num)) return "".join(out)
data = "aaabccddddde" enc = rle_encode(data) print("Encoded:", enc) print("Decoded:", rle_decode(enc)) print("Round trip OK:", rle_decode(enc) == data)
Sample Output
Encoded: a3b1c2d5e Decoded: aaabccddddde Round trip OK: True
Step-by-Step Logic & Complexity
How It Works: Scan the string comparing each character with its predecessor: equal characters increase a counter,
while a different character flushes 'char+count' to the output and resets the counter; the final run is flushed after the
loop. Decoding reads one character, collects the digits that follow as the repeat count, and repeats the character that
many times, so 'a3b1c2d5e1' expands back to 'aaabccddddde'.
Time Complexity: O(n) — both functions make a single left-to-right pass.
Space Complexity: O(n) — the output list can be as long as the input.
Problem 6: Reverse Each Word and Reverse Word Order Difficulty: Easy
Problem Statement: Write two functions: reverse_each_word(sentence) reverses the letters of every word but keeps
the word order; reverse_word_order(sentence) reverses the order of the words but keeps each word intact. Test both
on the same sentence.
Sample Input: s = "Python makes coding fun"
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def reverse_each_word(sentence):
return " ".join(word[::-1] for word in sentence.split(" "))
def reverse_word_order(sentence):
return " ".join(sentence.split()[::-1])
s = "Python makes coding fun" print(reverse_each_word(s)) print(reverse_word_order(s))
Sample Output
nohtyP sekam gnidoc nuf fun coding makes Python
Step-by-Step Logic & Complexity
How It Works: Slicing with [::-1] reverses a string, so applying it to every word gives 'nohtyP sekam gnidoc nuf' while
the words stay in the same positions. For the second function split() builds the word list, [::-1] reverses that list, and
join() reconnects the words with single spaces.
Time Complexity: O(n) — every character is copied a constant number of times.
Space Complexity: O(n) — new strings/lists of total length n are created.
Problem 7: Rotate a List Right by k Positions In-Place Difficulty: Medium
Problem Statement: Rotate a list to the right by k places without creating a second list (O(1) extra space). Use the
three-reversal technique. k may be larger than the list length. Show the result for [1..7] with k = 3 and for [10, 20, 30,
40] with k = 6.
Sample Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3 | nums2 = [10, 20, 30, 40], k = 6
Expected Output: exactly as printed in the Sample Output below.
Problem 8: All Pairs with a Given Sum (Two-Pointer Technique) Difficulty: Medium
Problem Statement: Given an unsorted list of integers and a target, return every distinct pair of values (smaller value
first) whose sum equals the target. Use sorting plus two pointers; do not use nested loops. Each pair must appear only
once even if values repeat.
Sample Input: data = [8, 3, 5, 1, 7, 5, 2, 9, 4, 6], target = 10
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def find_pairs(arr, target): arr = sorted(arr) left, right = 0, len(arr) - 1 pairs = [] while left < right: s = arr[left] + arr[right] if s == target: pairs.append((arr[left], arr[right])) left += 1 right -= 1 while left < right and arr[left] == arr[left - 1]: # skip repeats left += 1 while left < right and arr[right] == arr[right + 1]: right -= 1 elif s < target: left += 1 # need a bigger sum else: right -= 1 # need a smaller sum return pairs
data = [8, 3, 5, 1, 7, 5, 2, 9, 4, 6] print("Sorted:", sorted(data)) print("Pairs summing to 10:", find_pairs(data, 10))
Sample Output
Sorted: [1, 2, 3, 4, 5, 5, 6, 7, 8, 9] Pairs summing to 10: [(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]
Step-by-Step Logic & Complexity
How It Works: After sorting, one pointer sits at the smallest value and one at the largest. A sum that is too small
moves the left pointer right, a sum that is too large moves the right pointer left, and on a match both move inward while
the inner loops skip repeated values so each pair is reported once. For [1,2,3,4,5,5,6,7,8,9] this finds 1+9, 2+8, 3+7,
4+6 and finally 5+5.
Time Complexity: O(n log n) — sorting dominates; the pointer scan is only O(n).
Space Complexity: O(n) — the sorted copy of the input.
Problem 9: Maximum Subarray Sum with Indices (Kadane's Algorithm)
Problem Statement: Given a list of integers (positive and negative), find the contiguous subarray with the largest sum.
Return the sum and the start and end indices, using a single pass.
Sample Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def max_subarray(nums): best_sum = cur_sum = nums[0] best_start = best_end = cur_start = 0 for i in range(1, len(nums)): if cur_sum < 0: # a negative prefix only hurts cur_sum = nums[i] cur_start = i else: cur_sum += nums[i] if cur_sum > best_sum: best_sum = cur_sum best_start, best_end = cur_start, i return best_sum, best_start, best_end
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] total, s, e = max_subarray(nums) print("Max sum:", total) print("Subarray:", nums[s:e + 1], "(indices", s, "to", str(e) + ")")
Sample Output
Max sum: 6 Subarray: [4, -1, 2, 1] (indices 3 to 6)
Step-by-Step Logic & Complexity
How It Works: cur_sum is the best sum of a subarray that ends at the current index: if it has become negative it can
only reduce any extension, so a fresh subarray starts at i; otherwise the element is added. Whenever cur_sum beats
best_sum the indices are saved. On the sample the sum restarts at index 3 with 4, then becomes 3, 5 and 6, so the
best subarray is [4, -1, 2, 1] with sum 6.
Time Complexity: O(n) — a single pass over the list.
Space Complexity: O(1) — only a handful of integer variables.
Step-by-Step Logic & Complexity
How It Works: A set remembers which values have already appeared. Because the list is scanned left to right and a
value is appended only the first time it is seen, the original order survives: [4, 2, 4, 7, 2, 9, 7, 1] becomes [4, 2, 7, 9, 1].
A membership test on a set is O(1) on average, unlike 'x in list' which is O(n).
Time Complexity: O(n) — one pass with O(1) average set lookups.
Space Complexity: O(n) — the set and the result list.
Problem 12: Spiral Order Traversal of a Matrix Difficulty: Exam-Hard
Problem Statement: Given an m x n matrix, return its elements in clockwise spiral order starting from the top-left
corner. The solution must work for non-square matrices and for matrices with a single row or column.
Sample Input: grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def spiral(matrix): result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: for c in range(left, right + 1): # top row, left -> right result.append(matrix[top][c]) top += 1 for r in range(top, bottom + 1): # right column, top -> bottom result.append(matrix[r][right]) right -= 1 if top <= bottom: # bottom row, right -> left for c in range(right, left - 1, -1): result.append(matrix[bottom][c]) bottom -= 1 if left <= right: # left column, bottom -> top for r in range(bottom, top - 1, -1): result.append(matrix[r][left]) left += 1 return result
grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for row in grid: print(row) print("Spiral:", spiral(grid))
Sample Output
[1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] Spiral: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Step-by-Step Logic & Complexity
How It Works: Four boundaries (top, bottom, left, right) shrink after each side is traversed: top row left to right, right
column downwards, bottom row right to left, left column upwards. The two 'if' guards stop the code from re-reading a
row or column once the remaining block is a single row or column. For the 3x4 grid the walk is 1,2,3,4 then 8,12 then
11,10,9 then 5, and finally the inner row 6,7.
Time Complexity: O(m * n) — each cell is visited exactly once.
Space Complexity: O(1) — extra space apart from the output list.
Module 2: Dictionaries, Sets & Hashing (Problems 13-22)
Problem 13: Word Frequency Counter with Top-K Words Difficulty: Easy
Problem Statement: Write top_words(text, k) that counts how often each word occurs (ignoring case and punctuation)
and returns the k most frequent words as (word, count) pairs. Words with equal counts must be listed alphabetically.
Sample Input: text = "The cat sat on the mat. The dog sat on the log, and the cat watched the dog." k = 4
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
import string
def top_words(text, k): freq = {} for w in text.lower().split(): w = w.strip(string.punctuation) if w: freq[w] = freq.get(w, 0) + 1 ranked = sorted(freq.items(), key=lambda pair: (-pair[1], pair[0])) return ranked[:k]
text = "The cat sat on the mat. The dog sat on the log, and the cat watched the dog." for word, cnt in top_words(text, 4): print(f"{word:<6} {cnt}")
Sample Output
the 6 cat 2 dog 2 on 2
Step-by-Step Logic & Complexity
How It Works: Words are lowercased, stripped of punctuation and counted in a dictionary using get(word, 0) + 1. The
items are sorted by count descending and, for ties, alphabetically through the key (-count, word), then cut to the first k.
'the' appears six times, and among the words that appear twice the alphabetical order is cat, dog, on, sat.
Time Complexity: O(n + u log u) — n words are counted, then u unique words are sorted.
Space Complexity: O(u) — one dictionary entry per unique word.
Step-by-Step Logic & Complexity
How It Works: The first pass builds a frequency table; the second pass walks the string in its original order and returns
the first character whose count is 1. In 'swiss' the letter 's' occurs three times, so 'w' at index 1 is the answer; in 'aabbcc'
every letter repeats, so (-1, None) is returned.
Time Complexity: O(n) — two linear passes over the string.
Space Complexity: O(k) — k distinct characters are stored (bounded by the alphabet size).
Problem 16: Two Sum Using a Hash Map Difficulty: Medium
Problem Statement: Given a list of integers and a target value, return the indices (i, j) with i < j of the two numbers that
add up to the target, in a single pass. Return None if no such pair exists. Assume at most one valid pair is needed.
Sample Input: [2, 7, 11, 15], target 9 | [3, 2, 4], target 6 | [1, 2, 3], target 10
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def two_sum(nums, target): seen = {} # value -> index where it was seen for i, x in enumerate(nums): need = target - x if need in seen: # O(1) lookup return seen[need], i seen[x] = i return None
print(two_sum([2, 7, 11, 15], 9)) print(two_sum([3, 2, 4], 6)) print(two_sum([1, 2, 3], 10))
Sample Output
(0, 1) (1, 2) None
Step-by-Step Logic & Complexity
How It Works: For each number x we ask whether target - x has already been seen. The dictionary maps every earlier
value to its index, so this lookup takes constant time. For [2, 7, 11, 15] and target 9 the answer appears at i = 1
because 9 - 7 = 2 was stored at index 0, giving (0, 1); for [3, 2, 4] the pair is found at i = 2 because 6 - 4 = 2 was stored
at index 1.
Time Complexity: O(n) — one pass; each dictionary lookup is O(1) on average.
Space Complexity: O(n) — the dictionary may store every element.
Problem 17: Student Marks Report Using a Dictionary Difficulty: Easy
Problem Statement: A dictionary stores each student's marks in three tests. Compute every student's average, assign
a grade (A: 90 and above, B: 75 and above, C: 60 and above, otherwise D), and print the report and the name of the
topper.
Sample Input: marks = {"Asha": [88, 92, 79], "Ravi": [67, 74, 81], "Meera": [95, 98, 91], "Kabir": [55, 62, 48]}
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
marks = { "Asha": [88, 92, 79], "Ravi": [67, 74, 81], "Meera": [95, 98, 91], "Kabir": [55, 62, 48], }
def grade(avg): if avg >= 90: return "A" if avg >= 75: return "B" if avg >= 60: return "C" return "D"
averages = {name: sum(m) / len(m) for name, m in marks.items()} for name, avg in averages.items(): print(f"{name:<6} average = {avg:6.2f} grade = {grade(avg)}") topper = max(averages, key=averages.get) print("Topper:", topper)
Sample Output
Asha average = 86.33 grade = B Ravi average = 74.00 grade = C Meera average = 94.67 grade = A Kabir average = 55.00 grade = D Topper: Meera
Step-by-Step Logic & Complexity
How It Works: A dictionary comprehension turns each list of marks into an average, and grade() maps the average to
a letter by testing the highest band first. max(averages, key=averages.get) returns the key with the largest value, which
is Meera (94.67). Ravi's 74.00 falls just below the 75 cut-off, so he receives a C.
Time Complexity: O(S * T) — S students with T marks each are summed once.
Space Complexity: O(S) — one average per student.
Sample Output
'abcabcbb' -> ('abc', 3) 'bbbbb' -> ('b', 1) 'pwwkew' -> ('wke', 3) 'dvdf' -> ('vdf', 3) '' -> ('', 0)
Step-by-Step Logic & Complexity
How It Works: A sliding window [start, i] always contains distinct characters. The dictionary remembers the most
recent index of every character; when the current character was already seen inside the window, start jumps to just
after that earlier position. In 'pwwkew' the second 'w' moves start to index 2, and the window then grows through 'wk' to
'wke' (length 3), which is the best found.
Time Complexity: O(n) — i moves forward once and start never moves backwards.
Space Complexity: O(k) — k distinct characters are stored (bounded by the alphabet).
Problem 20: Count Subarrays with Sum Equal to K (Prefix Sums)
Problem Statement: Given a list of integers (which may be negative) and an integer k, count the contiguous subarrays
whose elements sum to k. A brute-force O(n^2) answer scores half marks; the full-mark answer uses prefix sums and a
dictionary in O(n).
Sample Input: [1, 1, 1], k = 2 | [3, 4, 7, 2, -3, 1, 4, 2], k = 7
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def count_subarrays(nums, k): prefix_count = {0: 1} # the empty prefix has sum 0 running = 0 total = 0 for x in nums: running += x # sum of nums[0..i] total += prefix_count.get(running - k, 0) prefix_count[running] = prefix_count.get(running, 0) + 1 return total
print(count_subarrays([1, 1, 1], 2)) print(count_subarrays([3, 4, 7, 2, -3, 1, 4, 2], 7))
Sample Output
2 4
Step-by-Step Logic & Complexity
How It Works: Let running be the sum of the first i items. A subarray ending at i sums to k exactly when an earlier
prefix equals running - k, so prefix_count records how many times each prefix sum has occurred and is consulted
before the current prefix is stored. For [1, 1, 1] and k = 2 the prefix sums are 1, 2, 3: at 2 the earlier prefix 0 exists and
at 3 the earlier prefix 1 exists, giving two subarrays.
Time Complexity: O(n) — one pass with O(1) average dictionary operations.
Space Complexity: O(n) — up to n distinct prefix sums are stored.
Problem 21: Isomorphic Strings Difficulty: Medium
Problem Statement: Two strings are isomorphic if the characters of the first can be replaced to obtain the second, with
every occurrence replaced consistently and no two different characters mapping to the same character. Write
is_isomorphic(a, b) and test it on four pairs.
Sample Input: ("egg", "add") | ("foo", "bar") | ("paper", "title") | ("ab", "aa")
Expected Output: exactly as printed in the Sample Output below.
Clean Python Solution
def is_isomorphic(a, b): if len(a) != len(b): return False map_ab, map_ba = {}, {} # forward and backward mappings for x, y in zip(a, b):
if map_ab.setdefault(x, y) != y or map_ba.setdefault(y, x) != x: return False return True
pairs = [("egg", "add"), ("foo", "bar"), ("paper", "title"), ("ab", "aa")] for a, b in pairs: print(f"{a!r}, {b!r} -> {is_isomorphic(a, b)}")
Sample Output
'egg', 'add' -> True 'foo', 'bar' -> False 'paper', 'title' -> True 'ab', 'aa' -> False
Step-by-Step Logic & Complexity
How It Works: Two dictionaries enforce a one-to-one mapping in both directions: each character of a must always
map to the same character of b, and two different characters may never map to the same target. setdefault inserts the
pair the first time and otherwise returns the stored partner, which is compared with the current one. 'foo' and 'bar' fail
because 'o' would have to map to both 'a' and 'r'; 'ab' and 'aa' fail because 'a' and 'b' would both map to 'a'.
Time Complexity: O(n) — one pass with O(1) average dictionary operations.
Space Complexity: O(k) — k distinct characters in the two mappings.