DS SampleProblems
DS SampleProblems
Data Structures
[Algorithm analysis.]
1. [15 points] What is the order of complexity of the following block(s) of code? Show
detailed steps to prove your answer.
C ODE B LOCK -1(n)
1. count ← 0
2. for i ← n; i > 0; i ← i/4 do
3. for j ← 0; j < i; j ← j + 1 do
4. count ← count + 1
Solution:
Time for C ODE B LOCK -1:
P n oP
= n n n n j∈{0,1,2,...,i} 1
i∈ 0 , 41 , 42 ,..., ⌊log4 n⌋
P n4 4
= n n n
o (i + 1)
i∈ , , ,..., ⌊logn n⌋
40 41 42 4 4
P n oi+P n
= n n n
o1
i∈ , , ,..., ⌊logn n⌋ i∈ n n n
, , ,..., ⌊logn n⌋
40 41 42 4 4 40 41 43 4 4
= 4n0 + 4n1 + 4n2 + · · · + n
4⌊log4 n⌋
+ log4 n
= Θ (n) + Θ (log n) (using geometric series sum)
= Θ (n)
Time for C ODE B LOCK -2:
P P n
= i∈{20 ,21 ,22 ,...,2⌊log n⌋ } n
o1
j∈ , n , n ,..., ⌊logn n⌋
30 31 32 3 3
1× (independent sums)
P P n
= i∈{20 ,21 ,22 ,...,2⌊log n⌋ } n n n
o1
j∈ , , ,..., ⌊logn n⌋
30 31 32 3 3
= (⌊log2 n⌋ + 1) × (⌊log3 n⌋ + 1)
= Θ (log
n) × Θ (log n)
2
= Θ log n
2. [10 points] Write the following functions f (n) in the form f (n) ∈√Θ (g(n)), where
g(n) is the simplified function. (i) f (n) = n1/ log n , (ii) f (n) = log 4n , (iii) f (n) =
2log4 n , (iv) f (n) = 7log49×49 n , and (v) f (n) = (log log n)1/ log log log n
Solution:
Please add the reasoning for individual steps
1. f (n) = n1/ log n = (2n )1/ log n = 2 (because n = 2log2 n )
= Θ (1) √
n n
2. f (n) = log 4n = log 4 2 = log(22 ) 2 = log 2n
= Θ (n)
log4 n
log n log n
log n 1/2 1/2
√
3. f (n) =
√ 2 = 2 log 4 = 2 2 = (2 ) = n = n
= Θ ( n)
log7 7 log7 7 1
4. f (n) = 7log49×49 n = 7log74 n = nlog74 7 = n log7 74 = n 4 log7 7 = n 4
= Θ n1/4
1/ log log log n
5. f (n) = (log log n)1/ log log log n = 2log log log n =2
= Θ (1)
3. [10 points] Rank the following functions by order of growth. That is, arrange the
functions in asymptotically nondecreasing order using ≺ and ≍ relations. Give
reasons for your answers. Assume that the log function has base 2 unless explic-
itly mentioned otherwise.
√
2 2 log n
, (log n)!, log2 n, (log n)log n , log(n!)
4. [20 points] Assume that you want to implement the following ADT using sev-
eral different data structures. Simply mention the worst-case time complexity
for different methods using different data structures given in an empty table.
Provide the complexities using Θ () notation wherever feasible and use O nota-
tion in the remaining places. Give the amortized complexity for dynamic array
implementations and average case complexity for hash table implementations
assuming that the load factor is small and the hash function distributes keys
uniformly. The symbols ⋆ represents amortized case complexity and † represents
average/expected case complexity.
Solution: See Tables 1 and 2.
Page 2
Data Structure Operation 1 Operation 2 Operation 3 Operation 4
Basic Data Structures AddFirst AddLast RemoveFirst RemoveLast
DynamicArray Θ (n) Θ (1)⋆ Θ (n) Θ (1)⋆
SinglyLinkedList Θ (1) Θ (1) Θ (1) Θ (n)
CircularlySinglyLinkedList Θ (1) Θ (1) Θ (1) Θ (n)
DoublyLinkedList Θ (1) Θ (1) Θ (1) Θ (1)
Stack ADT Push Pop Top
DynamicArray Θ (1)⋆ Θ (1)⋆ Θ (1)
SinglyLinkedList Θ (1) Θ (1) Θ (1)
CircularlySinglyLinkedList Θ (1) Θ (1) Θ (1)
DoublyLinkedList Θ (1) Θ (1) Θ (1)
Queue ADT Enqueue Dequeue Front
CircularDynamicArray Θ (1)⋆ Θ (1)⋆ Θ (1)
SinglyLinkedList Θ (1) Θ (1) Θ (1)
CircularlySinglyLinkedList Θ (1) Θ (1) Θ (1)
DoublyLinkedList Θ (1) Θ (1) Θ (1)
Deque ADT AddFirst AddLast RemoveFirst RemoveLast
CircularDynamicArray Θ (1)⋆ Θ (1)⋆ Θ (1)⋆ Θ (1)⋆
SinglyLinkedList Θ (1) Θ (1) Θ (1) Θ (n)
CircularlySinglyLinkedList Θ (1) Θ (1) Θ (1) Θ (n)
DoublyLinkedList Θ (1) Θ (1) Θ (1) Θ (1)
Sorted Set ADT Add Remove Search SortedOrder
DynamicArray O (n) O (n) O (n) Θ (n log n)
SortedDynamicArray O (n) O (n) O (log n) Θ (n)
BinarySearchTree O (n) O (n) O (n) Θ (n)
(2-4)-Tree O (log n) O (log n) O (log n) Θ (n)
B-Tree O (log n) O (log n) O (log n) Θ (n)
RedBlack-Tree O (log n) O (log n) O (log n) Θ (n)
AVL-Tree O (log n) O (log n) O (log n) Θ (n)
Set ADT Add Remove Search
DynamicArray O (n) O (n) O (n)
SortedDynamicArray O (n) O (n) O (log n)
HashTable-Chaining-List Θ (1)† Θ (1)† Θ (1)†
HashTable-LinearProbing Θ (1)† Θ (1)† Θ (1)†
HashTable-QuadraticProbing Θ (1)† Θ (1)† Θ (1)†
PriorityQueue ADT Add RemoveMin Minimum
SinglyLinkedList Θ (1) O (n) O (n)
SortedSinglyLinkedList O (n) Θ (1) Θ (1)
MinHeap-DynamicArray O (log n)⋆ O (log n)⋆ Θ (1)
MinHeap-LinkedTree O (log n) O (log n) Θ (1)
Table 2: Time complexities for different operations on various data structures.
Page 3
[Summarizing data structures.]
1. [0 points] Write a beautiful poem on data structures
Solution: ChatGPT: Here it is.
Introduction
To hold and shape the thoughts we code,
We need smart ways to share the load.
Data structures show the way—
To store, to search, to build, to play.
From lines and trees to queues that wait,
They help machines communicate.
Array
In rows, each item knows its place,
Fixed in size, in tight embrace.
Fast to find by numbered call,
But shifting things can stall it all.
(Used in: images, matrices, and storing fixed lists.)
Stack
Last in, first out—it’s how it goes,
Page 4
Like plates in piles or nested shows.
You push it in, then pop it out,
A helpful friend in code, no doubt.
(Used in: undo features, parsing code, call stacks.)
Queue
One joins the line, one leaves from start,
It moves like people in a mart.
First come, first served—it’s fair and clear,
The queue stays calm, both far and near.
(Used in: printer tasks, customer service lines, CPUs.)
Deque
Like queue and stack, but more than both,
It adds and pulls from either growth.
From front or end, you’re free to choose,
It gives more ways, so less you lose.
(Used in: sliding window problems, task scheduling.)
Priority queue
Not first in line, but most in need,
The biggest task gets done with speed.
It sorts by weight, not time alone—
The urgent ones are quickly shown.
(Used in: emergency systems, CPU scheduling.)
Hash table
No rows, no chains, just keys that map,
A clever trick, a fast-hand clap.
Jump to data using codes,
No need to walk through all the loads.
(Used in: dictionaries, password storage, caches.)
Page 5
Graph
With nodes and edges all around,
It models maps and friends we’ve found.
No single path, just many ways,
It shapes the web in modern days.
(Used in: GPS, social networks, internet links.)
Closing
Each form has logic, clean and smart,
A vital piece of coding art.
From simple lists to complex graphs,
They build the world in code and math.
So learn their ways, and you will see—
They hold the key to mastery.
Page 6
[Arrays and lists.]
1. [10 points] Given a string S[1 . . . n], write an algorithm code to check whether the
given string is a palindrome or not. A palindrome is a string that reads the same
backward as forward. E.g. madam, malayalam, and racecar. Give the algorithm’s
time and space complexity.
I S PALINDROME(S[1 . . . n])
1. Write the pseudocode
Solution:
I S PALINDROME(S[1 . . . n])
1. for i ← 1 to ⌊n/2⌋ do
2. if S[i] ̸= S[n − i + 1] then
3. return false
4. return true
This algorithm compares the characters at the beginning and end of the string,
moving towards the center. If any characters don’t match, it returns false. If it
completes the loop, the string is a palindrome.
Time = O (n), Space = O (1)
Solution:
GCD(a[1 . . . n])
1. if n = 1 then return a[1]
2. else return gcd(a[n], GCD(a[1 . . . (n − 1)]))
The recursive algorithm computes the GCD of the last element and the GCD of
the rest of the array. The base case is when there’s only one element, in which
case the GCD is the element itself. The time complexity is O (n · log M ), where
M is the maximum value in the array, due to the recursive nature of the GCD
function.
Time = O (n log M ), Space = O (n)
Page 7
[Stacks, queues, and deques.]
1. [10 points] Fill Table 3 with the contents of the data structures after executing
different operations starting from the initial configuration. Note that when you
remove an element from a data structure, you return the removed element to the
caller. You do not need to worry about the data overflow problem. The top element
in the stack, the first element in the queue, and the first element in the deque are
highlighted using a box.
Solution: See Table 4.
Page 8
[Trees and priority queues.]
1. [10 points] Traverse the following binary tree using the four traversal algorithms:
Preorder traversal, inorder traversal, postorder traversal, and level-order (or
breadth-first) traversal.
Solution
Inorder: 9, 12, 14, 17, 19, 23, 50, 54, 67, 72, 76
Preorder: 50, 17, 9, 14, 12, 23, 19, 76, 54, 72, 67
Postorder: 12, 14, 9, 19, 23, 17, 67, 72, 54, 76, 50
Level order: 50, 17, 76, 9, 23, 54, 14, 19, 72, 12, 67
2. Draw each of the following evolving data structures twice that result from the
following operations in that order into an initially empty data structure.
(a) [10 points] binary search tree
insert [100, 10, 30, 50, 70, 40, 90, 60], draw tree, delete [30], insert [20, 30],
delete [70], insert [80, 70], draw tree.
(b) [10 points] (2,4) tree
insert [100, 10, 30, 50, 70, 40], draw tree, insert [90, 60, 20, 80], draw tree.
(c) [10 points] min heap (tree representation)
insert [100, 10, 30, 50, 70, 40, 90, 60], draw tree, deletemin, deletemin, insert
[20, 80], deletemin, draw tree.
Solution: Please refer to Figures 1, 2, and 3.
3. [5 points] Check if the following array is a BST. Draw the tree and explain the
reasoning.
10, 5, 20, -, -, 9, 25
Solution:
Draw a tree diagram
No. Because 9 is smaller than 10 yet it is on the right subtree of 10.
Page 9
Figure 1: Binary search tree (BST).
Figure 3: Min-heap.
4. [5 points] Check if the following array is a min-heap. Draw the tree and explain
the reasoning.
2, 4, 5, 7, 6, 4
Solution:
Draw a tree diagram
No. Because 5 (at index 3) is bigger than its left child 4 (at index 6).
Page 10
[Hash tables.]
1. Use the hash function H ASH C ODE(key) = (2 × key + 5) to fill a 11-entry hash ta-
ble. Insert [5, 16, 20, 39, 11, 94, 23, 88, 13, 44, 12], draw table, delete [20, 44, 39], insert
[98, 14], draw table. Assume collisions are handled by:
(a) [5 points] Separate chaining → linked list
(b) [5 points] Open addressing → linear probing
(c) [5 points] Open addressing → quadratic probing
Solution:
Separate chaining → linked list:
Bucket 0 1 2 3 4 5 6 7 8 9 10
Keys − 20 − − 5, 16 11, 88, 44 39, 94 23, 12 − 13 −
Bucket 0 1 2 3 4 5 6 7 8 9 10
Keys 14 − − 98 5, 16 11, 88 94 23, 12 − 13 −
Open addressing → linear probing:
Bucket 0 1 2 3 4 5 6 7 8 9 10
Keys 13 20 44 12 5 16 39 11 94 23 88
Bucket 0 1 2 3 4 5 6 7 8 9 10
Keys 13 14 × 12 5 16 98 11 94 23 88
Open addressing → quadratic probing:
(44 will never be inserted. So stop at this point)
Bucket 0 1 2 3 4 5 6 7 8 9 10
Keys 20 88 5 16 39 94 23 11 13
Bucket 0 1 2 3 4 5 6 7 8 9 10
Keys
Page 11
[Graphs.]
Page 12
Figure 5: Adjacency matrix and adjacency list
Page 13
[Sorting.]
Figure 7: Quicksort
Page 14
2. [10 points] Show step-by-step details of how to partition the array
A = [3, 7, 5, 4, 2, 8, 1, 5, 6, 4, 2, 8] using the first element of the array as the pivot
element using Hoare partition
Solution: Refer to Figure 8.
Page 15
[Algorithm codes.]
1. Learn how to write algorithm codes using 1-indexed arrays for the following
algorithms. Learn also to write time and space complexities.
Recursion
– Nonrecursive and recursive binary search
– Recursive product (log complexity)
– Recursive power function or exponentiation (log complexity)
– Recursive divide-and-conquer array sum
– Recursive towers of hanoi
Trees
– Binary tree → Recursive preorder traversal
– Binary tree → Recursive inorder traversal
– Binary tree → Recursive postorder traversal
– Binary tree → Nonrecursive level-order traversal
– BST → Nonrecursive and recursive search
– BST → Nonrecursive and recursive add
– BST → Recursive remove
Priority queues
– Nonrecursive add using upheap
– Nonrecursive removemin using downheap
Graphs
– Nonrecursive and recursive DFS
– Nonrecursive BFS optimized
Sorting
– Nonrecursive selection sort
– Nonrecursive insertion sort
– Nonrecursive heap sort (using maxheap)
– Recursive merge sort
– Recursive quick sort
Page 16
[Applications.]
1. Consider the following ADTs (implemented in the best possible way): stack
ADT, queue ADT, deque ADT, set ADT (implemented using hash tables),
sorted set ADT (implemented using balanced search trees such as 2-4 trees),
priority queue ADT (implemented as an array-based min-heap), and graph
ADT (implemented as an adjacency list). For each of the scenarios below,
mention the most suitable ADT (implemented in the best possible way).
(a) [1 point] Create a database designed to efficiently retrieve a specific ID
and its associated information without the need for sorting.
(b) [1 point] Store browser history (i.e., a sequence of recently visited web
URLs) and quickly find the most recently visited web URL.
(c) [1 point] Create a task scheduler, where each task is given a priority (i.e.,
a natural number in the range [1, r] and r is known), and the highest-
priority task is always selected first for execution.
(d) [1 point] Create a real-time leaderboard for a gaming application that
allows update and display of the top players.
(e) [1 point] Design a music playlist system that enables users to add songs,
remove songs, and play the next track with the closest longer duration.
(f) [1 point] Design an online library catalog where users can add new books,
search for books by title, and print a sorted list of all the books available.
(g) [1 point] Create a social network application where users can make friends,
and the application can quickly suggest potential new friends based on
friends-of-friends connections.
(h) [1 point] Create a call center system that can effectively manage incom-
ing calls and route them to available operators based on order of arrival.
(i) [1 point] Design a pathfinding service that helps users find the shortest
route through a network of roads between two locations.
(j) [1 point] Develop a system so that students in a university can give
printing jobs to printers in a fair manner.
Solution:
(a) Set ADT (implemented using hash tables)
(b) Stack ADT
(c) Priority Queue ADT (key = 1 ÷ priority)
(d) Sorted Set ADT (using balanced search trees such as 2-4 trees)
(e) Sorted Set ADT (using balanced search trees such as 2-4 trees)
(f) Sorted Set ADT (using balanced search trees such as 2-4 trees)
(g) Graph ADT (implemented as an adjacency list)
(h) Queue ADT
(i) Graph ADT (implemented as an adjacency list)
(j) Queue ADT
Page 17