Data Structures Fundamentals
- 150Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Which description best captures the purpose of a data structure?
Which description best captures the purpose of a data structure?
150 questions
- 1
Which description best captures the purpose of a data structure?
- A
It specifies the exact programming language an algorithm must use
- B
It converts every kind of data into a sorted sequence
- C
It guarantees that every algorithm uses the least possible memory
- D
It organizes data so the data can be accessed, queried, or updated efficiently
Correct answer
DIt organizes data so the data can be accessed, queried, or updated efficiently
Explanation
A data structure organizes data to make operations such as access, querying, and updating efficient.
- A
- 2
Why can choosing an appropriate data structure improve a software product?
- A
It allows every operation to run in constant time
- B
It eliminates the need to analyze an algorithm's time and space use
- C
It can support faster algorithms, natural data management, and clearer code
- D
It guarantees that a program will never encounter invalid input
Correct answer
CIt can support faster algorithms, natural data management, and clearer code
Explanation
Appropriate data structures can make algorithms faster, data easier to manage, and code cleaner and easier to understand.
- A
- 3
What does an abstract data type specify, compared with a data structure?
- A
The fastest possible algorithm for each supported operation
- B
The behavior and interface that an implementation must provide
- C
The particular values that must be stored in the structure
- D
The memory layout and programming language of every implementation
Correct answer
BThe behavior and interface that an implementation must provide
Explanation
An abstract data type defines the operations and behavior exposed to users, not the details of how those operations are implemented.
- A
- 4
A list can be implemented by either a dynamic array or a linked list. What does this illustrate?
- A
One abstract data type can have multiple underlying data structures
- B
Different implementations must expose different list behavior
- C
A list is itself always implemented as a linked list
- D
An abstract data type determines the memory layout of its implementation
Correct answer
AOne abstract data type can have multiple underlying data structures
Explanation
A list is an abstract data type; a dynamic array and a linked list are possible implementations that provide list operations.
- A
- 5
Why can a queue implemented using stacks still qualify as a queue?
- A
Any structure implemented with stacks automatically runs in constant time
- B
A queue's abstract interface requires it to use two stacks
- C
Stacks and queues have identical insertion and removal behavior
- D
It can provide queue behavior even if its internal implementation is different
Correct answer
DIt can provide queue behavior even if its internal implementation is different
Explanation
An abstract data type specifies behavior, not implementation. A stack-based implementation can provide queue operations, even if it is not the most efficient choice.
- A
- 6
What does Big O notation describe in this material?
- A
The exact runtime of an algorithm on every computer
- B
The number of lines of code used to implement an algorithm
- C
The average runtime for inputs of a fixed, small size
- D
An algorithm's asymptotic worst-case growth in time or space
Correct answer
DAn algorithm's asymptotic worst-case growth in time or space
Explanation
Big O is used to describe worst-case growth, particularly as input size becomes arbitrarily large.
- A
- 7
For a search through an unordered list, which input arrangement gives the worst case?
- A
The desired item is found after checking only a constant number of elements
- B
The desired item is the final element, or is absent and every element must be checked
- C
The list contains repeated values near its beginning
- D
The desired item is the first element
Correct answer
BThe desired item is the final element, or is absent and every element must be checked
Explanation
In the worst case, a linear search must traverse every element before finding the target at the end, or determine that the target is absent.
- A
- 8
Why are constant factors and lower-order terms usually omitted in Big O analysis?
- A
They do not determine the dominant growth as input size becomes arbitrarily large
- B
They are always zero for sufficiently large inputs
- C
They can be removed from the algorithm without changing its output
- D
They have no effect on real program runtimes
Correct answer
AThey do not determine the dominant growth as input size becomes arbitrarily large
Explanation
Asymptotic analysis focuses on dominant growth for large inputs. Constants may still matter substantially in real-world runtimes.
- A
- 9
What is the Big O class of 7log(n3)+15n2+2n3+8?
- A
O(n2)
- B
O(2n)
- C
O(n3)
- D
O(logn)
Correct answer
CO(n3)
Explanation
The cubic term grows faster than the other terms, so it determines the asymptotic class: O(n3).
- A
- 10
A loop runs a fixed number of times regardless of the input size n. What is its time complexity?
- A
O(logn)
- B
O(1)
- C
O(n2)
- D
O(n)
Correct answer
BO(1)
Explanation
Because the loop's work does not depend on n, its asymptotic running time is constant.
- A
- 11
A loop processes every input element, but advances its counter by three each time. What is its Big O complexity?
- A
O(n)
- B
O(n2)
- C
O(logn)
- D
O(n/3) as a distinct asymptotic class
Correct answer
AO(n)
Explanation
The loop performs about n/3 iterations, which is linear growth. Big O ignores the constant factor, so the result is O(n).
- A
- 12
An algorithm's inner loop performs n−i operations for each outer-loop index i from 0 to n−1. Why is the total work quadratic?
- A
The total work is proportional only to the final value of i
- B
The outer loop is ignored whenever an inner loop is present
- C
The inner loop executes exactly once for the entire algorithm
- D
The work sums to n+(n−1)+⋯+1=2n(n+1)
Correct answer
DThe work sums to n+(n−1)+⋯+1=2n(n+1)
Explanation
Summing the decreasing inner-loop lengths gives 2n(n+1), whose dominant growth is quadratic.
- A
- 13
Why does binary search take logarithmic time in the worst case?
- A
Each iteration discards half of the remaining search range
- B
The algorithm performs a fixed number of comparisons for every input size
- C
The array is sorted again after each comparison
- D
Each iteration checks every element in the array
Correct answer
AEach iteration discards half of the remaining search range
Explanation
Repeatedly halving the search range leaves only a logarithmic number of iterations, giving O(logn) time.
- A
- 14
An outer loop performs n iterations, and each iteration runs two separate inner loops of 3n and 2n operations. What is the total Big O complexity?
- A
O(n)
- B
O(5n) as a distinct asymptotic class
- C
O(n3)
- D
O(n2)
Correct answer
DO(n2)
Explanation
The inner loops contribute 3n+2n=5n work per outer iteration. Multiplying by n gives 5n2, or O(n2).
- A
- 15
A set of n items has how many possible subsets, and what time complexity does explicitly finding all of them imply?
- A
n! subsets, implying factorial work
- B
n2 subsets, implying quadratic work
- C
2n subsets, implying exponential work
- D
nlogn subsets, implying linearithmic work
Correct answer
C2n subsets, implying exponential work
Explanation
Each of the n items is either included or excluded, giving 2n subsets and exponential work to enumerate them.
- A
- 16
Which pairing of tasks and time complexities is correct?
- A
All string permutations: O(logn); merge sort: O(n!)
- B
All string permutations: O(n2); merge sort: O(1)
- C
All string permutations: O(n!); merge sort: O(nlogn)
- D
All string permutations: O(nlogn); merge sort: O(2n)
Correct answer
CAll string permutations: O(n!); merge sort: O(nlogn)
Explanation
There are n! permutations of n distinct items, while merge sort has O(nlogn) time complexity.
- A
- 17
What is a defining property of a static array?
- A
It grows automatically whenever an element is appended
- B
It has fixed length and stores indexable elements in contiguous memory
- C
Its memory locations are deliberately separated by gaps
- D
Its elements are accessed only by traversing pointers
Correct answer
BIt has fixed length and stores indexable elements in contiguous memory
Explanation
A static array is a fixed-length, indexable container stored as a contiguous chunk of memory.
- A
- 18
In a zero-based array of length n, which index range is valid?
- A
From 0 through n, inclusive
- B
From 1 through n, inclusive
- C
From 1 through n−1, inclusive
- D
From 0 through n−1, inclusive
Correct answer
DFrom 0 through n−1, inclusive
Explanation
Zero-based indexing gives an array of length n valid indices from 0 to n−1.
- A
- 19
Why can an array retrieve an element at a specified index in constant time?
- A
Its contiguous layout and indexability allow direct access to the requested slot
- B
It scans from the first element until it reaches the requested index
- C
It stores a separate linked list for every possible index
- D
It sorts its elements before every retrieval
Correct answer
AIts contiguous layout and indexability allow direct access to the requested slot
Explanation
Array indexing directly identifies a slot in the contiguous memory block, so access takes O(1) time.
- A
- 20
Why can searching an array for an arbitrary value take linear time?
- A
Every array access requires shifting the remaining elements
- B
A search must resize the array before checking its contents
- C
Arrays cannot compare the values they contain
- D
The value may be absent or near the end, requiring a scan of all elements
Correct answer
DThe value may be absent or near the end, requiring a scan of all elements
Explanation
Without an assumed search-organizing property, a search may need to inspect every element, giving O(n) worst-case time.
- A
- 21
Which example illustrates using an array as a buffer?
- A
Reading a large file in small chunks that fit in memory
- B
Keeping only the highest-priority item at the top
- C
Merging disjoint groups after checking their representatives
- D
Storing each item in a node that points to the next item
Correct answer
AReading a large file in small chunks that fit in memory
Explanation
A buffer array can temporarily hold a small chunk of a large input or output stream at a time.
- A
- 22
Why are arrays useful as lookup tables?
- A
They keep all values sorted without requiring an ordering
- B
They automatically identify the key associated with every value
- C
They make every search for an unknown position constant time
- D
A known index or offset can be used to retrieve a stored value directly
Correct answer
DA known index or offset can be used to retrieve a stored value directly
Explanation
If the location associated with an item is known, array indexing retrieves it directly.
- A
- 23
How can an array help a function return several results in a language that allows only one return value?
- A
Return each result in a separate function call automatically
- B
Convert the results into different array indices without returning the array
- C
Return a reference or pointer to an array containing the results
- D
Use a static array to bypass the language's return-value rule
Correct answer
CReturn a reference or pointer to an array containing the results
Explanation
A function can return a pointer or reference to an array that holds all the desired results.
- A
- 24
Why can appending to a dynamic array be constant time on average even though some appends trigger resizing?
- A
Resizing never copies existing elements
- B
Resizing happens infrequently, so its cost is spread across many inexpensive appends
- C
Every append reserves a new array exactly one slot larger
- D
The dynamic array stores elements outside of memory
Correct answer
BResizing happens infrequently, so its cost is spread across many inexpensive appends
Explanation
When capacity is increased geometrically, costly copies occur infrequently, yielding amortized constant-time append.
- A
- 25
What typically happens when a dynamic array's internal capacity is exceeded?
- A
The array becomes a linked list without moving any elements
- B
A larger array is allocated, existing elements are copied, and the new element is added
- C
All elements are shifted within the same fixed-size memory block
- D
The last element is discarded to make room
Correct answer
BA larger array is allocated, existing elements are copied, and the new element is added
Explanation
A common dynamic-array implementation allocates a larger backing array, copies the old elements, and then adds the new element.
- A
- 26
Why are insertion or deletion at an arbitrary position in an array-based list typically linear time?
- A
Other elements may need to shift, and resizing may require copying
- B
The array must be searched even when the target index is already known
- C
Every insertion or deletion requires sorting the entire array
- D
The array has to convert from zero-based to one-based indexing
Correct answer
AOther elements may need to shift, and resizing may require copying
Explanation
Making room or closing a gap can require shifting elements; resizing may also require copying them.
- A
- 27
What is a singly linked list?
- A
A fixed-length sequence of contiguous memory slots
- B
A sequence in which each node points both forward and backward
- C
A sequence of data-containing nodes in which each node points to the next
- D
A tree in which each node has exactly two children
Correct answer
CA sequence of data-containing nodes in which each node points to the next
Explanation
A linked list consists of nodes holding data and pointers to other nodes; in a singly linked list, each node points to the next.
- A
- 28
What does the head reference provide in a linked list?
- A
A guarantee that the last node has a previous pointer
- B
A direct reference to every node in the list
- C
A starting point from which the list can be traversed
- D
A fixed index for every element
Correct answer
CA starting point from which the list can be traversed
Explanation
The head identifies the first node, providing a place to begin traversing the list.
- A
- 29
Which statement correctly contrasts singly and doubly linked lists?
- A
Singly linked nodes point backward; doubly linked nodes point only forward
- B
Singly linked nodes point to the next node; doubly linked nodes also point to the previous node
- C
Singly linked lists have contiguous storage; doubly linked lists do not
- D
Doubly linked lists cannot be traversed from the head
Correct answer
BSingly linked nodes point to the next node; doubly linked nodes also point to the previous node
Explanation
A doubly linked list stores both next and previous references, while a singly linked list stores only a next reference.
- A
- 30
What is a trade-off of using a doubly linked list instead of a singly linked list?
- A
It uses more memory for an extra pointer per node but supports backward traversal
- B
It guarantees constant-time searching but requires contiguous memory
- C
It uses the same memory and supports fewer traversal directions
- D
It uses less memory but cannot remove a known middle node
Correct answer
AIt uses more memory for an extra pointer per node but supports backward traversal
Explanation
The previous pointer adds memory overhead, while allowing traversal backward and easier removal when a node reference is available.
- A
- 31
Why does removing a known node from the middle of a doubly linked list take constant time?
- A
The list automatically sorts its nodes after each deletion
- B
The list can locate the node by its array index
- C
The node's previous and next references can be connected directly to each other
- D
The node is copied to the end of the list before removal
Correct answer
CThe node's previous and next references can be connected directly to each other
Explanation
Given the node reference, its neighboring nodes can be linked to each other directly, bypassing the removed node.
- A
- 32
Why does removing the tail of a singly linked list take linear time, even if a tail reference is maintained?
- A
Every node must be copied into a new contiguous array
- B
The new tail must be found by traversing from the head because backward links are absent
- C
The tail cannot be accessed directly
- D
The list must locate the previous node using binary search
Correct answer
BThe new tail must be found by traversing from the head because backward links are absent
Explanation
A singly linked tail has no pointer to its predecessor, so the list must traverse from the head to find the new tail.
- A
- 33
What is the worst-case search time in a linked list?
- A
O(nlogn), because each node must be sorted
- B
O(logn), because linked nodes form a balanced search tree
- C
O(1), because each node stores its index
- D
O(n), because the target may be absent or at the final node
Correct answer
DO(n), because the target may be absent or at the final node
Explanation
A linked-list search may have to visit all n nodes.
- A
- 34
What is the defining behavior of a stack?
- A
It adds and removes elements at one end using last-in, first-out order
- B
It removes the smallest element before all others
- C
It adds at the back and removes from the front using first-in, first-out order
- D
It allows direct access to any element by index
Correct answer
AIt adds and removes elements at one end using last-in, first-out order
Explanation
A stack's push and pop operations occur at the top, producing last-in, first-out (LIFO) behavior.
- A
- 35
A stack initially has an item at its top. If two items are pushed and then one is popped, which item is removed?
- A
The second item pushed
- B
The first item pushed
- C
The item with the smallest value
- D
The item that was initially at the top
Correct answer
AThe second item pushed
Explanation
A pop removes the most recently pushed item, which is the second item pushed in this sequence.
- A
- 36
How does a stack help a program support recursive function calls?
- A
It sorts function calls by the length of their execution time
- B
It stores active call frames so returning can resume the previous call
- C
It stores all function results in an indexed array
- D
It guarantees that recursive calls execute in parallel
Correct answer
BIt stores active call frames so returning can resume the previous call
Explanation
The call stack tracks function frames; returning pops the current frame and resumes the preceding call.
- A
- 37
How can a stack determine whether brackets in a string are properly matched?
- A
Push opening brackets; for each closing bracket, match and pop the top, then require the stack to be empty
- B
Push closing brackets; for each opening bracket, remove the oldest item
- C
Count all bracket characters and accept strings with equal opening and closing totals
- D
Sort the brackets by type and compare the two halves
Correct answer
APush opening brackets; for each closing bracket, match and pop the top, then require the stack to be empty
Explanation
The stack tracks unmatched opening brackets in nested order. Each closing bracket must match the top, and no unmatched openings may remain.
- A
- 38
Why is checking only whether a bracket string has equal numbers of opening and closing brackets insufficient?
- A
Stacks cannot store more than one kind of bracket
- B
Bracket matching depends only on the string's final character
- C
A valid string must contain more opening brackets than closing brackets
- D
Equal counts do not ensure that brackets are correctly nested or ordered
Correct answer
DEqual counts do not ensure that brackets are correctly nested or ordered
Explanation
A sequence can have equal counts but still contain mismatched types or an invalid closing order.
- A
- 39
How can the Tower of Hanoi pegs be modeled using stacks?
- A
Each peg is a queue, since disks leave in the order they arrived
- B
All disks are stored in a single array and accessed by arbitrary index
- C
Each peg is a priority queue ordered by disk color
- D
Each peg is a stack, since only the top disk is moved on or off a peg
Correct answer
DEach peg is a stack, since only the top disk is moved on or off a peg
Explanation
A move removes the top disk from one peg and places it on another, matching stack operations.
- A
- 40
What is the time complexity of push, pop, and peek when a stack is implemented with a linked list and a top reference?
- A
O(1) for each operation
- B
O(logn) for each operation
- C
O(n) for each operation
- D
O(n2) for each operation
Correct answer
AO(1) for each operation
Explanation
The top is directly accessible, so adding, removing, or inspecting it takes constant time.
- A
- 41
What is a queue's standard removal and insertion order?
- A
Insert and remove only at the back
- B
Insert at the front and remove from the front
- C
Insert at the back and remove from the front
- D
Insert at the back and remove the highest-priority item
Correct answer
CInsert at the back and remove from the front
Explanation
A queue enqueues at the back and dequeues from the front, giving first-in, first-out behavior.
- A
- 42
A queue contains 55,−1,33 in that order. What remains at the front after two dequeue operations?
- A
−1
- B
The queue is empty
- C
33
- D
55
Correct answer
C33
Explanation
The first dequeue removes 55, and the second removes −1, leaving 33 at the front.
- A
- 43
Why are enqueue, dequeue, and peek constant-time operations in a linked-list queue that maintains front and back references?
- A
Each operation can access or update the relevant endpoint directly
- B
Linked lists store every element at a fixed numerical index
- C
The queue sorts its elements after every operation
- D
The queue searches all nodes to find the front and back
Correct answer
AEach operation can access or update the relevant endpoint directly
Explanation
Maintaining endpoint references allows insertion at the back, removal at the front, and inspection of the front without scanning the list.
- A
- 44
Why does checking whether an arbitrary value is contained in a queue generally take linear time?
- A
The value may require scanning the queue's elements to find
- B
The queue must remove each element before checking it
- C
A queue can only compare its front and back elements
- D
The queue must sort itself before performing containment checks
Correct answer
AThe value may require scanning the queue's elements to find
Explanation
A containment check may need to inspect every element, so its worst-case time is O(n).
- A
- 45
What is the core traversal order of breadth-first search?
- A
Follow one path as deeply as possible before considering other neighbors
- B
Visit nodes in increasing numerical order, regardless of edges
- C
Visit a starting node's neighbors before expanding to more distant layers
- D
Visit the largest-priority node before all its neighbors
Correct answer
CVisit a starting node's neighbors before expanding to more distant layers
Explanation
Breadth-first search expands outward by layers, visiting the current frontier's neighbors before moving farther away.
- A
- 46
Why does breadth-first search use a queue?
- A
It processes discovered nodes in the order they enter the frontier
- B
It always processes the most recently discovered node first
- C
It selects the smallest-valued node in the graph
- D
It provides direct access to every unvisited node
Correct answer
AIt processes discovered nodes in the order they enter the frontier
Explanation
A FIFO queue processes earlier-discovered frontier nodes first, supporting breadth-first layer order.
- A
- 47
In breadth-first search, when should a newly discovered neighbor be marked visited?
- A
Only if it has no neighbors of its own
- B
After every node in the graph has been explored
- C
Only after it has been removed from the queue twice
- D
When it is first discovered and added to the queue
Correct answer
DWhen it is first discovered and added to the queue
Explanation
Marking a node visited when it is discovered prevents it from being repeatedly added to the queue.
- A
- 48
What does it mean if breadth-first search finishes without visiting a node in the graph?
- A
The unvisited node must be the graph's root
- B
That node is unreachable from the chosen starting node
- C
The graph necessarily contains a cycle
- D
The queue processed nodes in the wrong order
Correct answer
BThat node is unreachable from the chosen starting node
Explanation
A traversal from one start reaches only nodes connected to that start by paths; an isolated or disconnected node remains unvisited.
- A
- 49
What property distinguishes a priority queue from an ordinary FIFO queue?
- A
The oldest element always has the highest priority
- B
Elements cannot be compared with one another
- C
Elements can be inserted only at the front
- D
Elements are removed according to priority rather than arrival order
Correct answer
DElements are removed according to priority rather than arrival order
Explanation
A priority queue removes the element with the highest priority under its chosen ordering, not necessarily the one inserted first.
- A
- 50
What must be true of elements placed in a priority queue?
- A
They must be comparable under an ordering used to determine priority
- B
They must be inserted in sorted order
- C
They must all be distinct integers
- D
They must all have the same priority
Correct answer
AThey must be comparable under an ordering used to determine priority
Explanation
The priority queue needs an ordering to determine which element has priority over another.
- A
- 51
In a min-priority queue, what does a poll operation return?
- A
The smallest element currently in the queue
- B
An arbitrary element from the queue
- C
The most recently inserted element
- D
The largest element currently in the queue
Correct answer
AThe smallest element currently in the queue
Explanation
In a min-priority queue, smaller elements have higher priority and are removed first.
- A
- 52
Why does repeatedly polling a min-priority queue not always amount to sorting all values at the time of each poll?
- A
A heap maintains enough ordering to find the current minimum without fully sorting all elements
- B
A poll operation returns values in insertion order
- C
A heap stores only the smallest value and discards the rest
- D
A priority queue ignores the ordering of its elements
Correct answer
AA heap maintains enough ordering to find the current minimum without fully sorting all elements
Explanation
A heap's invariant makes its root the current minimum, avoiding a full sort before every poll.
- A
- 53
What is the heap invariant for a min heap?
- A
Every node is smaller than every node in the next level
- B
Every parent value is greater than or equal to its children's values
- C
Every parent value is less than or equal to its children's values
- D
All leaf values are equal
Correct answer
CEvery parent value is less than or equal to its children's values
Explanation
In a min heap, each parent is no greater than its children, placing a minimum value at the root.
- A
- 54
What is the heap invariant for a max heap?
- A
Every parent value is greater than or equal to its children's values
- B
All leaf values are greater than the root
- C
Every parent value is less than or equal to its children's values
- D
Every node is larger than every node at the same level
Correct answer
AEvery parent value is greater than or equal to its children's values
Explanation
In a max heap, each parent is no smaller than its children, placing a maximum value at the root.
- A
- 55
Why is a priority queue not technically the same thing as a heap?
- A
A heap defines queue behavior but cannot store priorities
- B
A priority queue cannot be implemented with a tree
- C
A heap is an interface, while a priority queue is always an array
- D
A priority queue is an abstract data type, while a heap is one possible implementation
Correct answer
DA priority queue is an abstract data type, while a heap is one possible implementation
Explanation
The priority queue specifies behavior; heaps are a common implementation, but other structures can also provide that behavior.
- A
- 56
Which condition would make a tree-shaped structure invalid as a heap even if its parent-child values appear correctly ordered?
- A
It contains duplicate values
- B
Its nodes are drawn at unusual horizontal positions
- C
It contains a cycle and is therefore not a tree
- D
Some leaf nodes have no children
Correct answer
CIt contains a cycle and is therefore not a tree
Explanation
A heap must be a tree as well as satisfy the heap invariant. A cyclic structure is not a tree.
- A
- 57
Which is a use of priority queues described in the material?
- A
Guaranteeing that every graph has a unique minimum spanning tree
- B
Selecting the next promising node in algorithms such as Dijkstra's or best-first search
- C
Storing only the visited nodes of a breadth-first search
- D
Replacing the need for any graph representation
Correct answer
BSelecting the next promising node in algorithms such as Dijkstra's or best-first search
Explanation
Priority queues are used to choose the next node to explore in Dijkstra's algorithm and many best-first search algorithms.
- A
- 58
What are the typical complexities of peek, add, and poll in a binary-heap priority queue?
- A
Peek: O(logn); add: O(n); poll: O(1)
- B
Peek: O(n); add: O(1); poll: O(n)
- C
All three operations: O(1)
- D
Peek: O(1); add: O(logn); poll: O(logn)
Correct answer
DPeek: O(1); add: O(logn); poll: O(logn)
Explanation
The root can be inspected directly, while insertion and root removal may require a logarithmic-height swim or sink.
- A
- 59
What is the usual complexity of building a binary heap from an unordered array using heapify?
- A
O(n2)
- B
O(logn)
- C
O(n)
- D
O(nlogn)
Correct answer
CO(n)
Explanation
The bottom-up heapify procedure constructs a heap in linear time, unlike inserting the elements individually, which takes O(nlogn).
- A
- 60
How can a min-priority queue be made to behave like a max-priority queue for numeric values?
- A
Replace the heap with a FIFO queue
- B
Negate values before insertion and negate them again when they are removed
- C
Sort values in ascending order before every operation
- D
Insert every value twice
Correct answer
BNegate values before insertion and negate them again when they are removed
Explanation
Negating numeric values reverses their order, so a min queue of negated values returns the original largest value first.
- A
- 61
What does the complete binary tree property require?
- A
Every node has exactly two nonempty children
- B
Every level except possibly the last is full, and the last level is filled from the left
- C
Every level is filled from right to left
- D
All leaves occur at exactly the same depth
Correct answer
BEvery level except possibly the last is full, and the last level is filled from the left
Explanation
A complete binary tree fills all earlier levels and places the final level's nodes as far left as possible.
- A
- 62
For a zero-based array representation of a binary heap, where are the children of index i?
- A
At indices ⌊i/2⌋ and ⌊i/2⌋+1
- B
At indices 2i+1 and 2i+2
- C
At indices 2i and 2i+1
- D
At indices i+1 and i+2
Correct answer
BAt indices 2i+1 and 2i+2
Explanation
In a zero-based heap array, the left and right child indices are 2i+1 and 2i+2.
- A
- 63
Where is a newly inserted value placed in a complete binary heap before restoring the heap invariant?
- A
At an arbitrary leaf chosen by the insertion value
- B
At the leftmost leaf, even if that position is occupied
- C
At the next open position at the bottom, as far left as possible
- D
At the root, replacing the current root
Correct answer
CAt the next open position at the bottom, as far left as possible
Explanation
The complete-tree property determines the insertion position: the next available bottom-level position, filled from the left.
- A
- 64
After inserting an element into a min heap, how is a heap-invariant violation typically repaired?
- A
Remove the root and rebuild the heap
- B
Sort all values in the heap
- C
Swap the new value upward with larger parents until its position is valid
- D
Swap the new value downward with smaller children
Correct answer
CSwap the new value upward with larger parents until its position is valid
Explanation
The inserted value may be smaller than its parent, so it swims or bubbles upward until the min-heap invariant holds.
- A
- 65
Why does removing the root of a heap usually involve moving the last array element to the root and sinking it?
- A
The last element is always the next highest-priority value
- B
Moving the last element automatically restores both heap properties
- C
The root cannot be removed unless the whole array is sorted
- D
The last element fills the root's position while preserving completeness, then must be repositioned to restore heap order
Correct answer
DThe last element fills the root's position while preserving completeness, then must be repositioned to restore heap order
Explanation
Replacing the root with the final array element preserves the complete-tree shape; sinking may be needed to restore the heap invariant.
- A
- 66
Why does removing an arbitrary non-root element from a basic binary heap take linear time?
- A
The heap generally must be scanned to find that element's position
- B
The heap invariant forbids removal of non-root elements
- C
The element's position is stored automatically in the root
- D
Every non-root removal requires copying all nodes to a linked list
Correct answer
AThe heap generally must be scanned to find that element's position
Explanation
Without an auxiliary index, finding an arbitrary value may require scanning all heap elements, taking O(n) time.
- A
- 67
How can a heap support faster lookup and removal of repeated values?
- A
Sort the heap after each insertion and removal
- B
Store each value only in the hash table and remove the heap
- C
Assume every heap value is unique and store only one index
- D
Maintain a hash table mapping each value to a set of heap indices and update it during swaps
Correct answer
DMaintain a hash table mapping each value to a set of heap indices and update it during swaps
Explanation
A value-to-indices map handles duplicates and avoids a linear scan; swaps must update the mapped indices.
- A
- 68
What is the main cost of adding an index map to a heap?
- A
The heap can no longer support polling
- B
The heap invariant stops applying to duplicate values
- C
Additional linear space and overhead from maintaining the map during operations
- D
Every lookup becomes slower than a linear scan
Correct answer
CAdditional linear space and overhead from maintaining the map during operations
Explanation
The map can improve lookup and removal, but it uses extra space and requires additional work during swaps.
- A
- 69
What additional capability distinguishes an indexed priority queue from a traditional priority queue?
- A
It removes the need for comparable values
- B
It can efficiently update or delete a key-value pair identified by its key
- C
It can store only values that are already sorted
- D
It returns elements in their insertion order
Correct answer
BIt can efficiently update or delete a key-value pair identified by its key
Explanation
An indexed priority queue tracks key identities and positions so particular entries can be updated or deleted efficiently.
- A
- 70
Why does an indexed priority queue maintain both a position map and an inverse map?
- A
One maps key indices to heap positions; the other maps heap positions to key indices
- B
They replace the need to store values in the queue
- C
Both maps store the priority value, but in different formats
- D
One identifies the root and the other identifies the last inserted value
Correct answer
AOne maps key indices to heap positions; the other maps heap positions to key indices
Explanation
The position map supports locating a key in the heap, while the inverse map identifies which key occupies a heap position.
- A
- 71
In an indexed heap, why do swaps update the position and inverse maps rather than rearranging values by heap position?
- A
Values are stored by key index, while the maps track where each key is positioned in the heap
- B
Values are not stored in the indexed priority queue
- C
The maps store the heap invariant directly
- D
Heap positions cannot be changed after insertion
Correct answer
AValues are stored by key index, while the maps track where each key is positioned in the heap
Explanation
The values array is indexed by key index; swaps move keys between heap positions, so the maps must be updated to reflect the movement.
- A
- 72
Why can updating a specific key in an indexed binary heap take O(logn) time?
- A
An update always sorts all key-value pairs
- B
The key's position is found directly, then the changed value may swim or sink along the heap
- C
The queue must scan all keys and rebuild the entire heap
- D
The key's value is copied into every node
Correct answer
BThe key's position is found directly, then the changed value may swim or sink along the heap
Explanation
The maps locate the key efficiently; restoring heap order may require moving the node along a tree of logarithmic height.
- A
- 73
What is the purpose of decrease-key and increase-key operations?
- A
They remove the minimum and maximum values simultaneously
- B
They restrict an update to lowering or raising a key's value, respectively
- C
They change the number of children each heap node has
- D
They change the key's identity without changing its value
Correct answer
BThey restrict an update to lowering or raising a key's value, respectively
Explanation
These convenience operations update a value only if it becomes smaller or larger, as specified.
- A
- 74
What does a union-find data structure track?
- A
The prefix sums of an array
- B
The sorted order of elements in a binary search tree
- C
The priority of every item in a queue
- D
Elements partitioned into disjoint sets, supporting set lookup and set merging
Correct answer
DElements partitioned into disjoint sets, supporting set lookup and set merging
Explanation
Union-find tracks disjoint groups and supports finding an element's group and merging groups.
- A
- 75
What does the find operation return in a union-find structure?
- A
The next element to be merged
- B
The shortest path between two elements
- C
A representative identifying the set containing the given element
- D
The size of the largest set
Correct answer
CA representative identifying the set containing the given element
Explanation
Find identifies which component or set contains an element, typically by returning its root representative.
- A
- 76
What does union do in a union-find structure?
- A
Splits one set into two equally sized sets
- B
Sorts every element within a set
- C
Merges the sets containing two specified elements
- D
Finds the shortest path between two vertices
Correct answer
CMerges the sets containing two specified elements
Explanation
Union combines the components containing its two input elements.
- A
- 77
How does path compression improve union-find operations?
- A
It stores all elements in a sorted array
- B
It prevents the union operation from changing component structure
- C
It redirects nodes on a find path closer to the component root, shortening later lookups
- D
It splits long paths into separate components
Correct answer
CIt redirects nodes on a find path closer to the component root, shortening later lookups
Explanation
Path compression makes nodes encountered during find point directly or more closely to the root, greatly improving subsequent lookups.
- A
- 78
When union-by-size is used, which component's root is typically attached to the other?
- A
The root with the smaller element value is deleted
- B
The smaller component's root is attached to the larger component's root
- C
The larger component's root is always attached to the smaller one
- D
Both roots are replaced by new nodes
Correct answer
BThe smaller component's root is attached to the larger component's root
Explanation
Merging the smaller tree into the larger one helps keep the resulting tree shallower.
- A
- 79
In a parent-array representation of union-find, what does a self-parenting entry indicate?
- A
The element has been removed from the structure
- B
The element has no associated index
- C
The element is a root representative of its component
- D
The element belongs to every component
Correct answer
CThe element is a root representative of its component
Explanation
If an element's parent is itself, it is the root of its component.
- A
- 80
Why does Kruskal's minimum spanning tree algorithm use union-find?
- A
To test whether an edge connects different components and would avoid creating a cycle
- B
To select the largest-weight edge first
- C
To ensure the graph has a unique minimum spanning tree
- D
To sort each vertex's neighbors by distance
Correct answer
ATo test whether an edge connects different components and would avoid creating a cycle
Explanation
Union-find checks whether an edge's endpoints are already connected; if so, adding the edge would create a cycle.
- A
- 81
Which sequence describes Kruskal's algorithm?
- A
Sort vertices by degree and add every edge incident to the first vertex
- B
Visit vertices breadth-first and add every edge encountered
- C
Sort edges by weight, consider them in order, and add an edge only when its endpoints are in different components
- D
Start with the heaviest edge and repeatedly remove the lightest cycle
Correct answer
CSort edges by weight, consider them in order, and add an edge only when its endpoints are in different components
Explanation
Kruskal's algorithm processes edges in ascending weight order and uses component checks to avoid cycles.
- A
- 82
Which statement correctly defines a tree?
- A
A directed graph in which every node has exactly two children
- B
A connected, acyclic undirected graph
- C
Any graph with at least one cycle
- D
A graph in which every pair of vertices has multiple paths
Correct answer
BA connected, acyclic undirected graph
Explanation
A tree is a connected, acyclic undirected graph; equivalently, between any two vertices there is exactly one path.
- A
- 83
How many edges does a tree with n nodes have?
- A
2n
- B
n+1
- C
n−1
- D
n
Correct answer
Cn−1
Explanation
A tree with n nodes has exactly n−1 edges.
- A
- 84
Which description defines a binary tree?
- A
A tree whose values must be binary numbers
- B
A tree in which each node has exactly two nonempty children
- C
A tree in which each node has at most two children
- D
A tree in which every node has at least two children
Correct answer
CA tree in which each node has at most two children
Explanation
A binary tree limits each node to at most two children; a node may have zero or one child.
- A
- 85
What additional property makes a binary tree a binary search tree?
- A
Every node has exactly two children
- B
Every level of the tree is completely filled
- C
Each node's value is smaller than every value in the entire tree
- D
Values in a node's left subtree are smaller and values in its right subtree are larger
Correct answer
DValues in a node's left subtree are smaller and values in its right subtree are larger
Explanation
A binary search tree maintains an ordering in which the left subtree contains smaller values and the right subtree contains larger values.
- A
- 86
Why must values inserted into a binary search tree be comparable?
- A
Comparability guarantees the tree remains balanced
- B
The tree stores values only as strings
- C
Comparable values ensure the tree has no leaf nodes
- D
The insertion procedure must decide whether each value belongs in the left or right subtree
Correct answer
DThe insertion procedure must decide whether each value belongs in the left or right subtree
Explanation
Comparisons determine which branch to follow when inserting or searching for a value.
- A
- 87
What is the average-case search time in a reasonably shaped binary search tree, and what can happen in the worst case?
- A
Average linear time; worst-case constant time
- B
Average and worst-case quadratic time
- C
Average constant time; worst-case logarithmic time
- D
Average logarithmic time; worst-case linear time if the tree degenerates into a chain
Correct answer
DAverage logarithmic time; worst-case linear time if the tree degenerates into a chain
Explanation
A reasonably balanced tree has logarithmic height, but an unbalanced tree can become a chain and require linear work.
- A
- 88
When inserting a value into a binary search tree, where does the search for its insertion position begin?
- A
At the most recently inserted node
- B
At an arbitrary node chosen from the tree
- C
At the root, followed by comparisons down the tree
- D
At the leftmost leaf, followed by a scan of all nodes
Correct answer
CAt the root, followed by comparisons down the tree
Explanation
Insertion begins at the root and follows left or right branches according to comparisons until reaching an empty position.
- A
- 89
If duplicates are disallowed in a binary search tree, what should insertion do when the value already exists?
- A
Leave the tree unchanged and report that no new value was inserted
- B
Insert the duplicate at the root
- C
Convert the tree into a heap
- D
Replace every value in the left subtree
Correct answer
ALeave the tree unchanged and report that no new value was inserted
Explanation
An implementation that requires unique values can reject or ignore an insertion when that value is already present.
- A
- 90
When deleting a leaf node from a binary search tree, what is the simplest correct action?
- A
Remove it and leave no replacement child
- B
Replace it with the root node
- C
Move it to the opposite subtree
- D
Replace it with the largest value in the tree
Correct answer
ARemove it and leave no replacement child
Explanation
A leaf has no children, so it can be removed without needing a successor replacement.
- A
- 91
When deleting a node with exactly one child in a binary search tree, what should replace it?
- A
Its sole child
- B
The root of the entire tree
- C
The smallest value in the entire tree
- D
A new empty node
Correct answer
AIts sole child
Explanation
The node's only child takes its place, preserving the search-tree ordering.
- A
- 92
For a binary search tree node with two children, which value can serve as its successor replacement?
- A
The largest value in its left subtree or the smallest value in its right subtree
- B
The smallest value in its left subtree or the largest value in its right subtree
- C
Only the root value of the entire tree
- D
Any leaf value in the tree
Correct answer
AThe largest value in its left subtree or the smallest value in its right subtree
Explanation
Either the predecessor from the left subtree or the successor from the right subtree preserves the binary search tree invariant.
- A
- 93
After copying a successor's value into a node being deleted, why must the successor node also be removed?
- A
The root would lose its parent
- B
The copied value would no longer be comparable
- C
The left and right subtrees would become identical
- D
Otherwise the successor's value would appear twice in the tree
Correct answer
DOtherwise the successor's value would appear twice in the tree
Explanation
Copying the successor value creates a duplicate until the original successor node is removed.
- A
- 94
What does an inorder traversal of a binary search tree produce?
- A
The values in increasing order
- B
The values in insertion order
- C
The values in level-by-level order
- D
The values in decreasing order
Correct answer
AThe values in increasing order
Explanation
Inorder traversal visits the left subtree, the node, then the right subtree; the search-tree invariant makes this increasing order.
- A
- 95
How do preorder, inorder, and postorder traversals differ?
- A
They differ only in whether they use a queue or a heap
- B
They visit the right subtree first in every case
- C
They print the current node before, between, or after the recursive subtree visits
- D
They all print nodes in increasing order
Correct answer
CThey print the current node before, between, or after the recursive subtree visits
Explanation
Preorder processes the node before its subtrees, inorder between them, and postorder after them.
- A
- 96
Which data structure is used to perform a level-order traversal?
- A
A priority queue ordered by node depth
- B
A stack
- C
A queue
- D
A hash set only
Correct answer
CA queue
Explanation
A queue processes nodes in discovery order, allowing a level-order traversal to visit nodes layer by layer.
- A
- 97
What does a tree rotation preserve when used in a binary search tree?
- A
The order in which nodes were inserted
- B
The binary search tree ordering, while changing the tree's shape
- C
The exact depth of every node
- D
The requirement that every node have two children
Correct answer
BThe binary search tree ordering, while changing the tree's shape
Explanation
A correctly performed rotation changes the structure but preserves the relative ordering required by the binary search tree invariant.
- A
- 98
What is the purpose of balancing a binary search tree?
- A
To make every node have exactly two children
- B
To ensure each subtree has the same number of nodes
- C
To keep its height logarithmic so operations avoid degrading to linear time
- D
To store values in a contiguous array
Correct answer
CTo keep its height logarithmic so operations avoid degrading to linear time
Explanation
A balanced tree limits its height, keeping search, insertion, and deletion logarithmic in the worst case.
- A
- 99
What is the AVL balance factor convention used in the material?
- A
Left-subtree height minus right-subtree height
- B
The total number of nodes in the right subtree
- C
The difference between the root value and the node value
- D
Right-subtree height minus left-subtree height
Correct answer
DRight-subtree height minus left-subtree height
Explanation
The described convention defines balance factor as right-subtree height minus left-subtree height.
- A
- 100
Which balance-factor values are allowed for each node in an AVL tree?
- A
−1, 0, or 1
- B
Only 0
- C
−2, 0, or 2
- D
Any integer, provided the root is balanced
Correct answer
A−1, 0, or 1
Explanation
An AVL tree requires every node's balance factor to be −1, 0, or 1; a value of −2 or 2 requires rebalancing.
- A
- 101
With the convention right-subtree height minus left-subtree height, what does a balance factor of −2 indicate?
- A
The node is perfectly balanced
- B
The node is left-heavy
- C
The node is right-heavy
- D
The node has no children
Correct answer
BThe node is left-heavy
Explanation
A balance factor of −2 means the left subtree is taller than the right subtree by two.
- A
- 102
Which rotation repairs a left-left imbalance in an AVL tree?
- A
A left rotation about the unbalanced node
- B
A left rotation followed by a right rotation about the same node
- C
No rotation; the imbalance is ignored
- D
A right rotation about the unbalanced node
Correct answer
DA right rotation about the unbalanced node
Explanation
A left-left imbalance is repaired with a single right rotation about the unbalanced node.
- A
- 103
How is a left-right AVL imbalance repaired?
- A
Rotate left at the left child, then rotate right at the unbalanced node
- B
Rotate right at the left child, then rotate left at the unbalanced node
- C
Rotate left twice at the unbalanced node
- D
Rotate right once at the unbalanced node
Correct answer
ARotate left at the left child, then rotate right at the unbalanced node
Explanation
The first left rotation converts the left-right case into a left-left case; a right rotation then resolves it.
- A
- 104
How is a right-left AVL imbalance repaired?
- A
Rotate left at the right child, then rotate right at the unbalanced node
- B
Rotate right once at the unbalanced node
- C
Rotate left twice at the unbalanced node
- D
Rotate right at the right child, then rotate left at the unbalanced node
Correct answer
DRotate right at the right child, then rotate left at the unbalanced node
Explanation
A right rotation at the right child transforms the case into right-right; a left rotation then restores balance.
- A
- 105
Why must an AVL implementation update height and balance-factor information after a rotation?
- A
The tree's ordering becomes invalid after every rotation
- B
The rotation changes subtree relationships, so stored values may no longer be correct
- C
Rotations change the values stored in every node
- D
Heights are needed only when the tree is initially constructed
Correct answer
BThe rotation changes subtree relationships, so stored values may no longer be correct
Explanation
Rotations change subtree shapes, so affected nodes' heights and balance factors must be recomputed, typically from lower nodes upward.
- A
- 106
What is a hash table designed to do?
- A
Map unique keys to associated values using hashing
- B
Guarantee that every key maps to a unique hash value
- C
Represent a graph as a tree
- D
Store only values in sorted order
Correct answer
AMap unique keys to associated values using hashing
Explanation
A hash table stores key-value associations and uses hashing to determine where keys are placed.
- A
- 107
What does a hash function do?
- A
Sorts keys by their associated values
- B
Identifies whether two objects are equal without comparing them
- C
Maps a key to an integer in a fixed range
- D
Guarantees a different result for every possible key
Correct answer
CMaps a key to an integer in a fixed range
Explanation
A hash function maps keys to integer values or table positions within a defined range.
- A
- 108
What is a hash collision?
- A
A key is inserted into an empty table
- B
A hash function returns a negative number
- C
Two values associated with one key are equal
- D
Two different keys produce the same hash value
Correct answer
DTwo different keys produce the same hash value
Explanation
A collision occurs when distinct keys hash to the same value.
- A
- 109
If two keys have different hash values, what can be concluded?
- A
The keys are not equal
- B
The hash function is not deterministic
- C
The keys must have the same value
- D
The keys are guaranteed to be stored in adjacent slots
Correct answer
AThe keys are not equal
Explanation
Equal objects must have compatible hash values; different hash values therefore establish that the objects are not equal.
- A
- 110
Why must a hash function be deterministic?
- A
The table must remain sorted after every insertion
- B
The hash function must return a random value each time
- C
Every key must map to a different integer
- D
The same key must map consistently so it can be found in the table
Correct answer
DThe same key must map consistently so it can be found in the table
Explanation
If a key's hash changed between operations, the table might look in the wrong location and fail to find the key.
- A
- 111
Why are hash functions designed to distribute keys uniformly?
- A
To ensure all keys have different values
- B
To make hash computations depend on random numbers
- C
To reduce collisions and avoid overloading a small number of table positions
- D
To eliminate the need for collision resolution
Correct answer
CTo reduce collisions and avoid overloading a small number of table positions
Explanation
A uniform distribution reduces clustering and collisions, supporting efficient table operations.
- A
- 112
Why do keys used in a hash table generally need to be immutable?
- A
Changing a key automatically deletes every colliding entry
- B
Immutable keys are the only values that can be compared
- C
Hash tables cannot store integer keys
- D
Changing a key can change its hash and make its stored entry difficult to locate
Correct answer
DChanging a key can change its hash and make its stored entry difficult to locate
Explanation
A key's hash should remain stable while it is stored; mutating the key could make its entry inaccessible.
- A
- 113
What is the purpose of a hash table's load factor?
- A
It counts the number of distinct hash functions
- B
It measures how full the table is relative to its capacity
- C
It measures the average length of every key
- D
It determines whether a key is immutable
Correct answer
BIt measures how full the table is relative to its capacity
Explanation
The load factor is the number of stored items relative to the table's capacity and helps determine when resizing is needed.
- A
- 114
How can a hash table preserve efficient operations as it becomes too full?
- A
Delete every key that shares a hash value
- B
Convert all keys to array indices without checking them
- C
Allocate a larger table and reinsert entries using their hash positions in the new table
- D
Keep the same capacity and allow unlimited collisions
Correct answer
CAllocate a larger table and reinsert entries using their hash positions in the new table
Explanation
Resizing and rehashing entries reduces congestion and helps maintain efficient operations.
- A
- 115
How does separate chaining resolve a collision?
- A
It stores colliding key-value entries together in a bucket data structure
- B
It changes the hash function each time a collision occurs
- C
It replaces the earlier key with the new key
- D
It searches for an empty slot elsewhere in the array
Correct answer
AIt stores colliding key-value entries together in a bucket data structure
Explanation
Separate chaining places entries with the same hash position in an auxiliary bucket, often a linked list.
- A
- 116
Which structures can be used as separate-chaining buckets?
- A
Only queues with no search operation
- B
Only static arrays
- C
Only binary heaps
- D
Linked lists, arrays, or trees
Correct answer
DLinked lists, arrays, or trees
Explanation
Buckets can use linked lists, arrays, binary trees, balanced trees, or other suitable structures.
- A
- 117
How does open addressing differ from separate chaining?
- A
Open addressing stores entries only in linked lists, while chaining stores them only in one array
- B
Open addressing probes for another slot in the table itself, while chaining stores collisions in bucket structures
- C
Open addressing sorts entries, while chaining hashes values
- D
Open addressing forbids collisions, while chaining changes the keys
Correct answer
BOpen addressing probes for another slot in the table itself, while chaining stores collisions in bucket structures
Explanation
Open addressing keeps entries in the table and probes for available positions; separate chaining uses auxiliary bucket structures.
- A
- 118
What is the average-case time complexity of hash-table insertion, lookup, and removal with good hashing and collision handling?
- A
O(n2) for each operation
- B
O(logn) for each operation
- C
O(n) for each operation
- D
O(1) for each operation
Correct answer
DO(1) for each operation
Explanation
With a well-distributed hash function and controlled load, these operations are constant time on average.
- A
- 119
What can happen to hash-table operation times if the hash function distributes keys poorly?
- A
They become logarithmic regardless of the table's structure
- B
They stop depending on the number of stored keys
- C
They become guaranteed constant time
- D
They can degrade to linear time because many keys collide
Correct answer
DThey can degrade to linear time because many keys collide
Explanation
Many collisions can force operations to examine a long chain or probe through many occupied slots.
- A
- 120
In open addressing, what is a probing sequence used for?
- A
Finding the value associated with a key without computing its hash
- B
Determining the table's load factor
- C
Sorting keys before they are hashed
- D
Choosing successive table positions to try after a collision
Correct answer
DChoosing successive table positions to try after a collision
Explanation
A probing sequence determines which alternative positions to inspect when the original hash position is occupied.
- A
- 121
What can go wrong if an open-addressing probing sequence cycles through only some table slots?
- A
All keys are automatically rehashed into separate chains
- B
The hash function becomes nondeterministic
- C
Every lookup returns the first key in the table
- D
Insertion can loop indefinitely even though other table slots are empty
Correct answer
DInsertion can loop indefinitely even though other table slots are empty
Explanation
A short cycle may never reach an available position, so insertion can fail or loop even when the table has empty slots.
- A
- 122
For linear probing with step size a, what condition ensures the probe can cycle through every slot in a table of size n?
- A
a and n are both even
- B
a is a multiple of n
- C
a and n are relatively prime
- D
a equals n
Correct answer
Ca and n are relatively prime
Explanation
The step and table size must have greatest common divisor one so the linear probe visits every position before repeating.
- A
- 123
What is quadratic probing?
- A
A method that probes only neighboring positions
- B
A method that stores each collision in a binary tree
- C
A collision-resolution method that offsets positions according to a quadratic function of the probe number
- D
A hash function that squares the key and never produces collisions
Correct answer
CA collision-resolution method that offsets positions according to a quadratic function of the probe number
Explanation
Quadratic probing uses offsets based on a quadratic expression, such as a function involving x2.
- A
- 124
Why must quadratic probing use carefully chosen parameters and table sizes?
- A
Quadratic expressions cannot be evaluated for integer inputs
- B
Quadratic probing works only when keys are strings
- C
Some choices produce short cycles that fail to visit every table position
- D
The table must contain no empty positions
Correct answer
CSome choices produce short cycles that fail to visit every table position
Explanation
Many quadratic probing functions do not visit all slots for arbitrary table sizes, so specific combinations are needed to avoid cycles.
- A
- 125
What makes double hashing different from ordinary linear probing?
- A
Its step size is derived from a second hash function applied to the key
- B
It uses two separate hash tables for every key
- C
It changes the key after each collision
- D
It stores each key in two different buckets
Correct answer
AIts step size is derived from a second hash function applied to the key
Explanation
Double hashing uses a secondary hash function to determine the probe step for each key.
- A
- 126
Why does open-addressing deletion commonly use a tombstone rather than replacing the deleted slot with empty?
- A
An empty slot would prevent new values from being inserted
- B
A tombstone stores the deleted key's new value
- C
A tombstone lets later searches continue through the probe sequence
- D
A tombstone keeps the table permanently at the same load factor
Correct answer
CA tombstone lets later searches continue through the probe sequence
Explanation
Marking the slot empty could make a search stop before reaching a key placed later in the same probe sequence; a tombstone signals that probing should continue.
- A
- 127
How can an insertion reuse a tombstone encountered during its probe sequence?
- A
Convert every tombstone in the table into an empty slot
- B
Stop immediately and overwrite the tombstone without checking for an existing key
- C
Remember the first tombstone, continue searching for an existing key, then insert at the tombstone if appropriate
- D
Move the tombstone to the root of the table
Correct answer
CRemember the first tombstone, continue searching for an existing key, then insert at the tombstone if appropriate
Explanation
Continuing the search avoids creating a duplicate key; if no existing key is found, the remembered tombstone can be reused.
- A
- 128
What happens to tombstones when an open-addressing table is resized and its entries are reinserted?
- A
They must be copied into the same numerical positions
- B
They can be discarded because only live key-value entries are reinserted
- C
They become keys in the new table
- D
They prevent the new table from accepting insertions
Correct answer
BThey can be discarded because only live key-value entries are reinserted
Explanation
Reinserting only live entries into the new table removes the old tombstones.
- A
- 129
What does a Fenwick tree support efficiently?
- A
Range-sum queries and point updates on an array
- B
Priority-based removal and key updates
- C
Finding connected components in a graph
- D
Arbitrary substring search and suffix sorting
Correct answer
ARange-sum queries and point updates on an array
Explanation
A Fenwick tree supports efficient prefix or range sums and updates to individual array positions.
- A
- 130
Why are ordinary prefix sums inconvenient when array values are frequently updated?
- A
Changing one value can require recomputing many later prefix sums
- B
Prefix sums cannot answer range-sum queries
- C
They require every array value to be negative
- D
They take linear time to read any single stored prefix sum
Correct answer
AChanging one value can require recomputing many later prefix sums
Explanation
A point change affects every later prefix sum, so maintaining all prefix sums can require linear work.
- A
- 131
What range of indices is conventionally used by a Fenwick tree in the material?
- A
Zero-based indices only
- B
One-based indices
- C
Indices beginning at the array's midpoint
- D
Negative indices
Correct answer
BOne-based indices
Explanation
Fenwick-tree operations are described using one-based indices, which are important for the least-significant-bit calculations.
- A
- 132
What determines the range of entries represented by a Fenwick-tree cell?
- A
The number of children in the original array
- B
The value stored in the cell
- C
The index's most significant set bit only
- D
The value of the index's least significant set bit
Correct answer
DThe value of the index's least significant set bit
Explanation
A cell covers a range whose size is determined by the least significant set bit of its index.
- A
- 133
How is a Fenwick-tree prefix sum typically computed?
- A
Start at the requested index and repeatedly subtract its least significant set bit until reaching zero
- B
Follow child pointers from a root node
- C
Start at the last index and repeatedly double the index
- D
Start at zero and scan every array position up to the requested index
Correct answer
AStart at the requested index and repeatedly subtract its least significant set bit until reaching zero
Explanation
The prefix-sum procedure accumulates the relevant cells while cascading downward by subtracting the least significant set bit.
- A
- 134
How can a Fenwick tree obtain the sum over indices from i through j using prefix sums?
- A
Add the prefix sum through i to the prefix sum through j
- B
Multiply the two prefix sums
- C
Subtract the prefix sum through i−1 from the prefix sum through j
- D
Subtract the prefix sum through j from the prefix sum through i
Correct answer
CSubtract the prefix sum through i−1 from the prefix sum through j
Explanation
The range sum is the cumulative sum through j minus the cumulative sum before the range, through i−1.
- A
- 135
During a Fenwick-tree point update at index i, which positions must be updated?
- A
Every index smaller than i
- B
The cells responsible for i, reached by repeatedly adding the least significant set bit
- C
Every index whose value equals the updated value
- D
Only the cell at index i
Correct answer
BThe cells responsible for i, reached by repeatedly adding the least significant set bit
Explanation
A point update changes the target cell and its responsible ancestors by repeatedly adding the least significant set bit to the index.
- A
- 136
What is the time complexity of constructing a Fenwick tree using the described linear-time propagation method?
- A
O(nlogn)
- B
O(n)
- C
O(logn)
- D
O(n2)
Correct answer
BO(n)
Explanation
The linear construction propagates each value to its responsible parent in a single pass, taking O(n) time.
- A
- 137
What is a suffix of a string in this material?
- A
A prefix that ends before the middle of the string
- B
A sequence of characters sorted in reverse order
- C
Any substring that begins at the first character
- D
A nonempty substring that reaches the end of the string
Correct answer
DA nonempty substring that reaches the end of the string
Explanation
A suffix is a nonempty substring ending at the final character of the original string.
- A
- 138
What does a suffix array store?
- A
Every suffix as a separate copied string in insertion order
- B
The number of repeated characters in each suffix
- C
The starting indices of a string's suffixes in lexicographic order
- D
The ending indices of all prefixes in numerical order
Correct answer
CThe starting indices of a string's suffixes in lexicographic order
Explanation
A suffix array stores indices ordered according to the lexicographic order of the suffixes starting at those positions.
- A
- 139
Why can a suffix array store indices rather than storing every suffix explicitly?
- A
Suffixes do not share characters with the original string
- B
An index contains all characters of its suffix
- C
Each index identifies a suffix within the original string, providing a compact representation
- D
Indices automatically sort themselves without comparisons
Correct answer
CEach index identifies a suffix within the original string, providing a compact representation
Explanation
The original string and each suffix's starting index are enough to represent the suffix, avoiding copies of all suffix strings.
- A
- 140
What does an LCP-array entry represent?
- A
The number of distinct characters in the original string
- B
The length of the longest suffix in the string
- C
The number of initial characters shared by two adjacent sorted suffixes
- D
The number of suffixes beginning with a particular character
Correct answer
CThe number of initial characters shared by two adjacent sorted suffixes
Explanation
Each LCP entry records the length of the longest common prefix shared by neighboring suffixes in suffix-array order.
- A
- 141
Why is the first LCP-array entry conventionally set to zero?
- A
The first suffix always has length zero
- B
The first two suffixes are always identical
- C
A zero marks the end of the original string
- D
It has no preceding suffix in the sorted array to compare against
Correct answer
DIt has no preceding suffix in the sorted array to compare against
Explanation
The first suffix has no previous suffix with which to form an adjacent pair, so its LCP value is undefined and conventionally stored as zero.
- A
- 142
How can a suffix array and LCP array help count distinct substrings?
- A
Subtract the number of suffixes from n!
- B
Count the suffixes and multiply by the maximum LCP value
- C
Start with 2n(n+1) substrings and subtract the sum of the LCP values
- D
Add all LCP values to the number of characters
Correct answer
CStart with 2n(n+1) substrings and subtract the sum of the LCP values
Explanation
There are 2n(n+1) total substrings, and the LCP values account for repeated substrings that should not be counted again.
- A
- 143
How can the longest repeated substring be found from an LCP array?
- A
Find the minimum LCP value and read the entire string
- B
Find the maximum LCP value and read that many characters from its corresponding suffix
- C
Sort the LCP values and use their sum as the substring length
- D
Choose the suffix with the greatest starting index
Correct answer
BFind the maximum LCP value and read that many characters from its corresponding suffix
Explanation
The largest LCP value gives the longest shared prefix between two distinct suffixes, which is a repeated substring.
- A
- 144
How can the longest common substring shared by at least k of several strings be approached with suffix and LCP arrays?
- A
Find the maximum single character frequency in each string
- B
Sort the original strings by length and compare only the shortest and longest
- C
Concatenate the strings with distinct sentinels, then find a window containing enough source-string colors with a large minimum LCP
- D
Concatenate the strings without separators and select the longest suffix
Correct answer
CConcatenate the strings with distinct sentinels, then find a window containing enough source-string colors with a large minimum LCP
Explanation
Distinct sentinels separate the strings; a window of suffixes from enough different source strings can be evaluated using its minimum LCP.
- A
- 145
Why should distinct sentinel symbols be placed between concatenated strings for the suffix-array method?
- A
They guarantee that all suffixes have the same length
- B
They remove the need to construct an LCP array
- C
They make the original strings identical
- D
They prevent suffixes from improperly continuing across string boundaries
Correct answer
DThey prevent suffixes from improperly continuing across string boundaries
Explanation
Distinct sentinels prevent a suffix from treating the end of one source string and the beginning of another as a continuous substring.
- A
- 146
Why should sentinel values sort before the ordinary characters in the concatenated text?
- A
They ensure the longest common substring contains a sentinel
- B
They make all ordinary suffixes equal
- C
They allow the suffix array to be stored without indices
- D
Their suffixes can be placed before the ordinary suffixes and then ignored in the relevant comparison
Correct answer
DTheir suffixes can be placed before the ordinary suffixes and then ignored in the relevant comparison
Explanation
Sentinels smaller than ordinary characters sort their suffixes separately at the beginning, where they can be excluded from the substantive search.
- A
- 147
In the sliding-window method for a k-string longest-common-substring problem, when is a window valid?
- A
When it contains suffixes from at least k different source strings
- B
When every suffix in it comes from the same source string
- C
When its first LCP value is the largest in the entire array
- D
When it contains exactly k suffixes total
Correct answer
AWhen it contains suffixes from at least k different source strings
Explanation
The window must represent at least k distinct source strings so that its common prefix is shared among them.
- A
- 148
How is the common-prefix length for a window of adjacent suffixes determined?
- A
By the number of distinct characters in the concatenated text
- B
By the minimum relevant LCP value within the window
- C
By the maximum suffix length in the window
- D
By the sum of all suffix-array indices in the window
Correct answer
BBy the minimum relevant LCP value within the window
Explanation
Every suffix in the window shares only as much prefix as the weakest adjacent LCP link, so the minimum LCP determines the common length.
- A
- 149
In the described sliding-window search, what should the algorithm do when the window contains fewer than k source-string colors?
- A
Shrink the window further
- B
Stop, because no valid answer exists
- C
Expand the window to include more suffixes
- D
Replace the LCP array with the suffix array
Correct answer
CExpand the window to include more suffixes
Explanation
The window must gain another source-string color before it can form a valid candidate, so it is expanded.
- A
- 150
What is the total number of nonempty substrings in a string of length n?
- A
n!
- B
n2
- C
2n
- D
2n(n+1)
Correct answer
D2n(n+1)
Explanation
There are n substrings of length one, n−1 of length two, and so on, totaling 2n(n+1).
- A

Ask anything
We've read this whole study set, so questions about it get the best answers.