Skip to content

Computer Science Practice Test — 30 Problems

Computer Science Practice Test — 30 Problems

Section titled “Computer Science Practice Test — 30 Problems”

This practice test covers 30 problems across four major domains of computer science: Algorithms, Data Structures, Theory of Computation, and Databases. Each problem tests conceptual understanding, analytical reasoning, and practical problem-solving. Work through all problems before checking the answer key.

  • Time limit: 90 minutes (3 minutes per problem)
  • Format: Multiple choice and coding — select the best answer or write pseudocode/code
  • Marking: 1 mark per problem, 30 marks total
  • Conditions: Attempt without notes. Write code on paper.
  • After the test: Check the answer key at the bottom. Study the explanations for any problems you got wrong.
DomainProblemsMarks
AlgorithmsP1–P88
Data StructuresP9–P168
Theory of ComputationP17–P237
DatabasesP24–P307
Total3030

What is the time complexity of the following function?

def mystery(n):
count = 0
i = 1
while i < n:
j = n
while j > 0:
count += 1
j = j // 2
i = i * 2
return count
#Option
AO(n)O(n)
BO(nlogn)O(n \log n)
CO(log2n)O(\log^2 n)
DO(n2)O(n^2)
EO(n)O(\sqrt{n})

Correct: B (index 1)

The outer loop runs O(logn)O(\log n) times (doubling ii each time). The inner loop runs O(logn)O(\log n) times (halving jj each time). Total: O(logn)×O(logn)=O(log2n)O(\log n) \times O(\log n) = O(\log^2 n). Wait — the inner loop resets j=nj = n each time, so it runs O(logn)O(\log n) iterations. But nn is constant within the inner loop. So total iterations: k=0lognlogn=O(log2n)\sum_{k=0}^{\log n} \log n = O(\log^2 n).

medium — 1 mark


In a merge sort, what is the recurrence relation for the number of comparisons in the worst case?

#Option
AT(n)=2T(n/2)+nT(n) = 2T(n/2) + n
BT(n)=2T(n/2)+1T(n) = 2T(n/2) + 1
CT(n)=T(n1)+nT(n) = T(n-1) + n
DT(n)=2T(n/2)+n2T(n) = 2T(n/2) + n^2
ET(n)=T(n/2)+1T(n) = T(n/2) + 1

Correct: A (index 0)

Merge sort divides the array into two halves (2T(n/2)2T(n/2)) and merges them in O(n)O(n) comparisons. The recurrence T(n)=2T(n/2)+nT(n) = 2T(n/2) + n solves to O(nlogn)O(n \log n) by the Master Theorem.

easy — 1 mark


Which algorithm finds the shortest path from a single source to all vertices in a graph with non-negative edge weights?

#Option
AKruskal’s algorithm
BPrim’s algorithm
CDijkstra’s algorithm
DBellman-Ford algorithm
EFloyd-Warshall algorithm

Correct: C (index 2)

Dijkstra’s algorithm efficiently computes single-source shortest paths for non-negative weights in O((V+E)logV)O((V+E)\log V) using a priority queue. Bellman-Ford handles negative weights but is slower. Floyd-Warshall computes all-pairs shortest paths.

easy — 1 mark


The Fibonacci sequence can be computed in O(n)O(n) time using dynamic programming. What is the space complexity if only the last two values are stored?

#Option
AO(1)O(1)
BO(logn)O(\log n)
CO(n)O(n)
DO(nlogn)O(n \log n)
EO(n2)O(n^2)

Correct: A (index 0)

By storing only the two most recent Fibonacci numbers (previous and current), we use constant space O(1)O(1) regardless of nn. We iterate from 2 to nn, updating these two values at each step.

medium — 1 mark


The activity selection problem (selecting the maximum number of non-overlapping activities) can be solved greedily by:

#Option
ASelecting the longest activity first
BSelecting the activity with the earliest start time
CSelecting the activity with the earliest finish time
DSelecting the activity with the shortest duration
ERandomly selecting activities and removing conflicts

Correct: C (index 2)

The greedy strategy of always choosing the next activity with the earliest finish time yields an optimal solution. This maximises the remaining time for subsequent activities. The algorithm runs in O(nlogn)O(n \log n) after sorting by finish time.

medium — 1 mark


Which of the following problems is NP-complete?

#Option
AShortest path in a graph
BSorting an array
CThe travelling salesman problem (decision version)
DFinding the minimum spanning tree
EBinary search

Correct: C (index 2)

The decision version of TSP (“Is there a tour of length ≤ k?”) is NP-complete. It is in NP (a certificate is a tour, verifiable in polynomial time) and NP-hard (by reduction from Hamiltonian cycle). The other problems are all solvable in polynomial time.

medium — 1 mark


The Knuth-Morris-Pratt (KMP) algorithm achieves string matching in O(n+m)O(n + m) time by:

#Option
AUsing a hash table to store pattern prefixes
BUsing a failure function to avoid redundant comparisons
CBuilding a suffix tree of the text
DUsing dynamic programming to find the longest common substring
EComparing characters from right to left

Correct: B (index 1)

KMP preprocesses the pattern to build a failure (prefix) function that tells us the longest proper prefix of the pattern that is also a suffix. When a mismatch occurs, the algorithm uses this function to skip ahead rather than backtracking, achieving linear time.

medium — 1 mark


What is the amortised cost per operation for dynamic array insertion (amortised via doubling)?

#Option
AO(1)O(1)
BO(logn)O(\log n)
CO(n)O(n)
DO(nlogn)O(n \log n)
EO(1)O(1) worst case

Correct: A (index 0)

Although a single resize costs O(n)O(n), it happens only when the array doubles in size. Over nn insertions, the total cost is n+2+4++n=O(n)n + 2 + 4 + \cdots + n = O(n), giving an amortised cost of O(1)O(1) per insertion (via the accounting or potential method).

medium — 1 mark


What is the worst-case time complexity for searching in a binary search tree?

#Option
AO(1)O(1)
BO(logn)O(\log n)
CO(n)O(n)
DO(nlogn)O(n \log n)
EO(log2n)O(\log^2 n)

Correct: C (index 2)

A degenerate (skewed) BST can have height nn, making search O(n)O(n). Balanced BSTs (AVL, Red-Black) guarantee O(logn)O(\log n). The worst case occurs when elements are inserted in sorted order.

easy — 1 mark


The expected time complexity of search in a hash table with chaining and a good hash function is:

#Option
AO(1)O(1) worst case
BO(1)O(1) expected, O(n)O(n) worst case
CO(logn)O(\log n)
DO(n)O(n) always
EO(n)O(n) expected

Correct: B (index 1)

With a good hash function and load factor α=n/m\alpha = n/m, expected search time is O(1+α)=O(1)O(1 + \alpha) = O(1) when the load factor is bounded. However, the worst case (all keys hash to the same bucket) is O(n)O(n).

medium — 1 mark


In a min-heap with nn elements, what is the time complexity of extracting the minimum element?

#Option
AO(1)O(1)
BO(logn)O(\log n)
CO(n)O(n)
DO(nlogn)O(n \log n)
EO(n)O(\sqrt{n})

Correct: B (index 1)

Extracting the minimum removes the root (O(1)O(1) to find it) and then restores the heap property by sifting down, which takes O(logn)O(\log n) — the height of the heap.

easy — 1 mark


For a sparse graph with VV vertices and EE edges where EV2E \ll V^2, which representation is most space-efficient?

#Option
AAdjacency matrix
BAdjacency list
CIncidence matrix
DEdge list only
EFull V×VV \times V matrix

Correct: B (index 1)

An adjacency list uses O(V+E)O(V + E) space, while an adjacency matrix uses O(V2)O(V^2). For sparse graphs where E=O(V)E = O(V), the adjacency list is significantly more space-efficient.

easy — 1 mark


An AVL tree maintains balance by ensuring that the height difference between left and right subtrees of any node is at most:

#Option
A0
B1
C2
Dlogn\log n
En\sqrt{n}

Correct: B (index 1)

The AVL balance condition requires that for every node, h(left)h(right)1|h(\text{left}) - h(\text{right})| \leq 1. Violations trigger rotations (single or double) to restore balance, guaranteeing O(logn)O(\log n) operations.

easy — 1 mark


A Bloom filter is a probabilistic data structure that:

#Option
ANever produces false negatives or false positives
BMay produce false positives but never false negatives
CMay produce false negatives but never false positives
DMay produce both false positives and false negatives
ERequires O(n)O(n) space per element

Correct: B (index 1)

A Bloom filter can definitively say an element is not in the set (no false negatives), but may incorrectly report an element as present (false positives). It uses a bit array with multiple hash functions, requiring sub-linear space.

medium — 1 mark


The union-find (disjoint set) data structure with union by rank and path compression has an amortised time complexity of approximately:

#Option
AO(logn)O(\log n) per operation
BO(α(n))O(\alpha(n)) per operation, where α\alpha is the inverse Ackermann function
CO(n)O(n) per operation
DO(1)O(1) worst case per operation
EO(logn)O(\log^* n) per operation

Correct: B (index 1)

With both optimisations, the amortised cost per operation is O(α(n))O(\alpha(n)), where α(n)\alpha(n) is the extremely slowly growing inverse Ackermann function (effectively ≤ 5 for all practical values of nn).

hard — 1 mark


In a trie (prefix tree), what is the worst-case time complexity for searching a string of length mm?

#Option
AO(1)O(1)
BO(m)O(m)
CO(n)O(n) where nn is the number of strings
DO(mlogn)O(m \log n)
EO(mn)O(mn)

Correct: B (index 1)

A trie searches character by character along a path of length mm, giving O(m)O(m) time regardless of how many strings are stored. This is independent of nn, making it ideal for prefix-based searches.

medium — 1 mark


Which of the following languages is NOT regular?

#Option
A{anbnn0}\{a^n b^n \mid n \geq 0\}
B{w{a,b}w has an even number of as}\{w \in \{a,b\}^* \mid w \text{ has an even number of } a\text{s}\}
C{anbmn,m0}\{a^n b^m \mid n, m \geq 0\}
D{ann is prime}\{a^n \mid n \text{ is prime}\}^*
EThe set of all strings over {a,b}\{a, b\}

Correct: A (index 0)

{anbnn0}\{a^n b^n \mid n \geq 0\} is the classic non-regular language, proved by the pumping lemma. A finite automaton cannot count arbitrarily many aas and then match them against bbs. All other options describe regular languages.

easy — 1 mark


Which of the following is a context-free language but not regular?

#Option
A{anbnn0}\{a^n b^n \mid n \geq 0\}
B{anbncnn0}\{a^n b^n c^n \mid n \geq 0\}
C{wwRw{a,b}}\{ww^R \mid w \in \{a,b\}^*\}
DBoth A and C
EBoth A and B

Correct: D (index 3)

{anbn}\{a^n b^n\} and {wwR}\{ww^R\} (palindromes) are both context-free (generated by context-free grammars) but not regular. {anbncn}\{a^n b^n c^n\} is not context-free (proved by the pumping lemma for CFLs).

medium — 1 mark


The Church-Turing thesis states that:

#Option
AEvery computable function can be computed by a Turing machine
BTuring machines can solve the halting problem
CEvery language is decidable
DTuring machines are equivalent to finite automata
EQuantum computers are more powerful than Turing machines

Correct: A (index 0)

The Church-Turing thesis posits that any function that is “effectively computable” (by any intuitive means) is computable by a Turing machine. It is a thesis (not a theorem) because it equates an informal notion of computability with a formal one.

medium — 1 mark


Which of the following problems is decidable?

#Option
ADoes a given Turing machine halt on the empty input?
BAre two context-free grammars equivalent?
CIs a given string in a regular language?
DDoes a given context-free grammar generate all strings?
EIs a given Turing machine deterministic?

Correct: C (index 2)

Membership in a regular language is decidable: construct the corresponding DFA and simulate it on the input string. The halting problem (A) and CFL equivalence (B) are undecidable.

medium — 1 mark


If P = NP, which of the following would be true?

#Option
AEvery problem in NP could be solved in polynomial time
BCryptography would become easier
CNP-complete problems would not exist
DTuring machines would become more powerful
ERegular languages would no longer be decidable

Correct: A (index 0)

If P = NP, every language in NP (including NP-complete problems) would have a polynomial-time algorithm. This would break most modern cryptography (which relies on the hardness of problems like factoring). NP-complete problems would still exist — they’d just be solvable in polynomial time.

medium — 1 mark


How many states are needed in the minimal DFA for the language {w{0,1}w represents a number divisible by 3 in binary}\{w \in \{0,1\}^* \mid w \text{ represents a number divisible by 3 in binary}\}?

#Option
A2
B3
C4
D6
E9

Correct: B (index 1)

The remainders modulo 3 partition the set of binary strings into 3 equivalence classes: remainder 0, 1, and 2. The minimal DFA has 3 states, one for each remainder. Transitions update the remainder based on the current bit.

medium — 1 mark


Which complexity class contains all problems solvable by a deterministic Turing machine in O(2n)O(2^n) time?

#Option
AP
BNP
CEXPTIME
DPSPACE
ER (Recursive)

Correct: C (index 2)

EXPTIME is the class of problems solvable in O(2p(n))O(2^{p(n)}) time for some polynomial p(n)p(n). The class R (recursive) is the class of all decidable languages, which is broader. P and PSPACE are subsets of EXPTIME.

medium — 1 mark


In the relational model, a relation (table) is formally defined as a:

#Option
ASet of tuples
BBag (multiset) of tuples
COrdered list of tuples
DTree of tuples
EGraph of tuples

Correct: A (index 0)

In the formal relational model (based on set theory), a relation is a set of tuples. Sets do not contain duplicates. SQL uses bags (multisets), but the theoretical model uses sets.

medium — 1 mark


A relation is in Third Normal Form (3NF) if:

#Option
AIt is in 1NF and all attributes are atomic
BIt is in 2NF and all non-key attributes are non-transitively dependent on the primary key
CIt is in BCNF and every functional dependency is trivial
DIt has no multi-valued dependencies
EIt is in 4NF

Correct: B (index 1)

3NF requires: (1) the relation is in 2NF (no partial dependencies), and (2) no non-key attribute is transitively dependent on the primary key. BCNF is stricter: every determinant must be a candidate key.

medium — 1 mark


What is the result of the following SQL query?

SELECT department, COUNT(*) as cnt
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
#Option
AAll departments with their employee counts
BOnly departments with more than 5 employees
CThe total number of employees
DThe department with the most employees
EAn error — GROUP BY and HAVING cannot be used together

Correct: B (index 1)

The GROUP BY groups rows by department. COUNT(*) counts employees per group. HAVING COUNT(*) > 5 filters to only include groups (departments) with more than 5 employees. The WHERE clause filters rows before grouping; HAVING filters groups after.

easy — 1 mark


Which ACID property ensures that a transaction is treated as a single, indivisible unit?

#Option
AAtomicity
BConsistency
CIsolation
DDurability
EAvailability

Correct: A (index 0)

Atomicity ensures that all operations in a transaction complete successfully, or none are applied (“all or nothing”). Consistency ensures the database moves from one valid state to another. Isolation ensures concurrent transactions don’t interfere. Durability ensures committed data persists.

easy — 1 mark


A B-tree index is particularly efficient for:

#Option
AExact match lookups only
BRange queries and ordered retrieval
CFull-text search
DSpatial queries
EAggregate queries on unindexed columns

Correct: B (index 1)

B-trees maintain sorted order and support efficient range queries (>>, <<, BETWEEN) because leaf nodes are linked. Hash indexes are faster for exact matches but cannot handle range queries. B-trees are the standard index for relational databases.

medium — 1 mark


In a database system, a “dirty read” occurs when:

#Option
AA transaction reads data that has been committed
BA transaction reads uncommitted data from another transaction
CA transaction reads the same data twice and gets different values
DA transaction fails and must be rolled back
ETwo transactions try to write to the same row simultaneously

Correct: B (index 1)

A dirty read happens when Transaction A reads data modified by Transaction B, but Transaction B has not yet committed. If B rolls back, A has read data that never officially existed. The READ COMMITTED isolation level prevents dirty reads.

medium — 1 mark


In a LEFT JOIN between tables A and B, which of the following is true?

#Option
AAll rows from B are returned, with NULLs for unmatched A rows
BOnly matching rows from both tables are returned
CAll rows from A are returned, with NULLs for unmatched B rows
DOnly rows that appear in both A and B are returned
EThe result is identical to an INNER JOIN

Correct: C (index 2)

A LEFT JOIN returns all rows from the left table (A) and matched rows from the right table (B). Where there is no match in B, NULL values are returned for B’s columns. An INNER JOIN returns only matching rows.

easy — 1 mark


Click to reveal the answer key
QuestionAnswerQuestionAnswerQuestionAnswer
P1BP11BP21A
P2AP12BP22B
P3CP13BP23C
P4AP14BP24A
P5CP15BP25B
P6CP16BP26B
P7BP17AP27A
P8AP18DP28B
P9CP19AP29B
P10BP20CP30C

DifficultyCount
Easy10
Medium19
Hard1


  1. Work through the code. For algorithm questions, trace through the code with small inputs rather than guessing the complexity.
  2. Draw diagrams. For data structures, sketch the tree, heap, or graph to visualise the problem.
  3. Know the definitions. Theory questions test precise definitions — study the formal statements.
  4. Practise SQL by hand. Write out the result sets for query questions rather than relying on intuition.
  5. Retake after one week. Computer science concepts build on each other — spaced repetition ensures strong foundations.

Last updated: 24 July 2026

Written by Wyatt. For questions or feedback, visit wyattau.com.