Data Structures Fundamentals
- 139Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is a data structure?
139 questions
- 1
What is a data structure?
Model answer
A data structure organizes data so it can be accessed, queried, or updated efficiently.
Explanation
Its purpose is to organize data for efficient use.
- 2
Why are data structures important for algorithms and software?
Model answer
They help create fast, powerful algorithms, organize data naturally, and make code cleaner and easier to understand.
Explanation
Choosing a suitable structure can improve both program performance and clarity.
- 3
What is an abstract data type, and how does it differ from a data structure?
Model answer
An abstract data type defines the behavior and interface an implementation must provide; a data structure is a concrete way to implement that interface.
Explanation
The abstract type specifies what operations do, not how they are implemented or what programming language is used.
- 4
How does the transportation analogy illustrate the difference between an abstract data type and its implementations?
Model answer
Getting from point A to point B represents the abstract goal; walking, biking, or taking a train represents different concrete implementations.
Explanation
Several implementations can provide the behavior specified by the same abstraction.
- 5
How can a list abstract data type be implemented, and what operations can those implementations support?
Model answer
A list can be implemented with a dynamic array or a linked list, and both can support adding, removing, and indexing elements.
Explanation
An abstract type can have multiple underlying implementations.
- 6
Can a queue be implemented using stacks, even if that is not the most efficient approach?
Model answer
Yes. A queue can be implemented using stacks; an implementation may be less efficient while still providing the required queue behavior.
Explanation
The abstract data type specifies behavior, not implementation efficiency.
- 7
What two resource questions does computational complexity help answer?
Model answer
It estimates how much time an algorithm takes and how much space it requires.
Explanation
Both running time and memory use matter when assessing an algorithm.
- 8
What does Big O notation describe in this material?
Model answer
It describes an algorithmâs worst-case growth in time or space as input size becomes arbitrarily large.
Explanation
Big O focuses on the worst case and large inputs.
- 9
Why does searching an unordered list take linear time in the worst case?
Model answer
The target may be the last element or absent, requiring a scan of all n elements.
Explanation
The amount of work can grow in proportion to the list size.
- 10
Why does Big O ignore constant terms and constant multiplicative factors?
Model answer
They do not change the asymptotic growth rate as the input becomes arbitrarily large.
Explanation
For example, a constant added to a function or multiplying it by a constant does not change its dominant growth class.
- 11
What is the Big O complexity of 7log(n3)+15n2+2n3+8?
Model answer
It is O(n3) because n3 is the dominant term.
Explanation
Big O retains the fastest-growing term and ignores constants and lower-order terms.
- 12
What do n and the common Big O classes O(1), O(logn), O(n), and O(nk) represent?
Model answer
n is input size; the classes represent constant, logarithmic, linear, and polynomial growth, respectively.
Explanation
Examples of polynomial growth include quadratic and cubic time.
- 13
What are examples of growth rates beyond the basic constant, logarithmic, and polynomial classes?
Model answer
Examples include O(2n), O(3n), O(n!), O(nâ), and O(nloglogn).
Explanation
Many mathematical expressions involving input size can describe a complexity class.
- 14
Why do loops with a fixed number of iterations take constant time with respect to input size?
Model answer
Their work does not depend on n, so increasing the input size does not increase the number of iterations.
Explanation
A fixed amount of work is classified as O(1).
- 15
How do nested loops affect complexity, and what complexity results from an outer loop of n iterations and inner loops of 3n and 2n iterations?
Model answer
Multiply the work across different loop levels and add work from separate inner loops; here the work is n(3n+2n)=5n2, or O(n2).
Explanation
The dominant term is quadratic.
- 16
What is the difference between a static array and a dynamic array?
Model answer
A static array has fixed capacity; a dynamic array can grow or shrink as needed, commonly by managing an internal static array.
Explanation
A dynamic array hides unused capacity from the user while maintaining extra internal slots.
- 17
What does it mean for an array to be indexable, and what are its usual valid indices?
Model answer
Each slot can be referenced by a number; a zero-based array of length n usually has indices from 0 through nâ1.
Explanation
An index identifies a particular position in the array.
- 18
What does it mean that a static array occupies contiguous memory?
Model answer
Its elements occupy adjacent memory addresses in one continuous block.
Explanation
The array does not consist of separated memory locations with gaps between its elements.
- 19
Name several common uses of arrays.
Model answer
Arrays store objects temporarily, buffer input or output, serve as lookup tables, return multiple values through a reference, and cache subproblems in dynamic programming.
Explanation
Their indexing makes them useful in many different tasks.
- 20
How can an array buffer help process a file that is too large to fit in memory?
Model answer
It stores a small chunk of the file at a time, allowing the program to process the entire file piece by piece.
Explanation
The buffer avoids needing to load the whole file into memory at once.
- 21
Why are array accesses constant time, while searching an array can take linear time?
Model answer
Indexing directly identifies a slot, but searching may require checking every element when the target is absent or near the end.
Explanation
Direct access takes O(1); worst-case scanning takes O(n).
- 22
Why can insertion or deletion in an array require linear time?
Model answer
Elements may need to shift to make or close a gap, and a dynamic array may also need to copy elements into a resized internal array.
Explanation
The number of moved or copied elements can grow with the array size.
- 23
Why is appending to a dynamic array described as constant time in the material, despite occasional resizing?
Model answer
Resizing and copying are infrequent, so appends are treated as constant time on an amortized basis.
Explanation
Most appends do not trigger a resize.
- 24
How does a dynamic array commonly grow when its internal array is full?
Model answer
It allocates a larger array, commonly double the capacity, copies the existing elements, and inserts the new element.
Explanation
Doubling provides room for subsequent appends before another resize is needed.
- 25
In a dynamic-array implementation, what is the difference between its length and its capacity?
Model answer
Length is the number of elements the user considers present; capacity is the size of the underlying array, which may include unused slots.
Explanation
Extra capacity is internal storage reserved for future growth.
- 26
What happens when code accesses an array index outside its valid range?
Model answer
The access is out of bounds and may produce an exception; the material notes that C does not always throw one.
Explanation
For a zero-based array of length n, index n is invalid.
- 27
What distinguishes a singly linked list from a doubly linked list?
Model answer
A singly linked node points to the next node; a doubly linked node points to both the next and previous nodes.
Explanation
The extra previous pointer supports backward traversal.
- 28
What are the head, tail, and nodes of a linked list?
Model answer
The head is the first node, the tail is the last node, and each node stores data and pointer or reference information linking it to other nodes.
Explanation
Keeping a reference to the head provides a starting point for traversals.
- 29
What does the final node of a non-circular linked list point to?
Model answer
Its next pointer is null, indicating there are no further nodes.
Explanation
In a circular linked list, by contrast, the last node can point back to the first.
- 30
How do linked lists support common abstract data types and other structures?
Model answer
They can implement lists, stacks, and queues, and are also used in circular lists, hash-table separate chaining, and graph adjacency lists.
Explanation
Their node links make them useful for representing sequential and connected data.
- 31
How can a circular linked list model repeating processes or structures?
Model answer
By making the last node point to the first, it can represent cycles such as round-robin ordering or the corners of a polygon.
Explanation
The link from the end back to the beginning creates a repeating traversal.
- 32
What are the main memory and traversal trade-offs between singly and doubly linked lists?
Model answer
Singly linked lists use less memory but cannot move directly backward; doubly linked lists use an additional pointer per node but support backward traversal.
Explanation
Pointers can consume substantial memory, especially on 64-bit machines.
- 33
How can a known node be removed from a doubly linked list in constant time?
Model answer
Reconnect its previous node to its next node, then remove the node itself.
Explanation
The nodeâs two links provide access to both neighbors.
- 34
Why can removing the tail of a singly linked list take linear time even if the list stores a tail reference?
Model answer
After removing the tail, the list must find the node before it to establish the new tail, and a singly linked list has no backward link.
Explanation
Finding that predecessor may require traversing from the head.
- 35
What are the worst-case complexities of searching a linked list and inserting at its head?
Model answer
Searching is O(n); inserting at the head is O(1) when the head reference is maintained.
Explanation
Search may inspect every node, while head insertion changes only a small number of links.
- 36
What pointer changes are needed to insert a node in the middle of a singly linked list?
Model answer
Set the new nodeâs next pointer to the following node, then set the preceding nodeâs next pointer to the new node.
Explanation
The preceding node must be reached by traversal before the links can be updated.
- 37
How does removing a middle node differ in singly and doubly linked lists?
Model answer
A singly linked list needs the preceding nodeâs pointer changed to skip the target; a doubly linked list reconnects the targetâs previous and next nodes.
Explanation
A doubly linked node directly provides access to both neighbors.
- 38
Why should removed linked-list nodes be deallocated or made unreachable?
Model answer
Proper cleanup prevents memory leaks in languages where memory must be managed explicitly; in garbage-collected languages, an unreachable node can be collected.
Explanation
References to removed nodes should no longer keep them in use.
- 39
What principle governs stack operations, and where are elements added and removed?
Model answer
A stack follows last in, first out (LIFO); both push and pop operate at the top.
Explanation
The most recently pushed item is the next one popped.
- 40
What access does the stack interface provide while operating on its elements?
Model answer
Stack operations act on the top element; they do not provide direct access to the other elements.
Explanation
This restriction is central to stack behavior.
- 41
Give examples of how stacks are used in computing.
Model answer
Stacks support editor or browser navigation, matching-brace checks, recursion, depth-first search, and models such as the Tower of Hanoi.
Explanation
These tasks use the stackâs last-in, first-out behavior.
- 42
How does a call stack support recursion?
Model answer
It stores earlier function calls; when a function returns, its stack frame is popped and execution resumes at the preceding call.
Explanation
The stack preserves the sequence of active calls.
- 43
How can a stack determine whether brackets in a string are properly matched?
Model answer
Push opening brackets; for each closing bracket, reject an empty stack or a mismatched top, otherwise pop the matching opener. Accept only if the stack is empty at the end.
Explanation
The top opening bracket must match the next closing bracket encountered.
- 44
Why must a bracket-matching algorithm check that the stack is empty after processing the whole string?
Model answer
Unmatched opening brackets may remain on the stack even if every closing bracket encountered so far matched.
Explanation
A valid sequence must have no unmatched openers or closers.
- 45
How can a stack be implemented using a singly linked list?
Model answer
Push new nodes at the head and pop by advancing the head to the next node.
Explanation
Using the head avoids the traversal that tail operations could require.
- 46
What are the time complexities of stack push, pop, and peek, and why?
Model answer
Each is O(1) when the top reference is maintained.
Explanation
Each operation accesses or changes only the top element.
- 47
What is a queue, and where are its insertion and removal ends?
Model answer
A queue is a linear structure that adds elements at the back and removes them from the front.
Explanation
Adding is enqueueing; removing from the front is dequeueing or polling.
- 48
How does a queue differ from a stack in its ordering behavior?
Model answer
A queue removes from the front after adding at the back, whereas a stack adds and removes at the top.
Explanation
A queue models the order in which items arrive for service.
- 49
How can a queue be used to manage a limited number of server requests?
Model answer
Process the requests that can be served immediately and enqueue the rest; whenever a request finishes, dequeue the next one.
Explanation
The queue holds waiting work in arrival order.
- 50
How can a queue keep track of only the most recent x elements?
Model answer
Enqueue each new element and dequeue an element when the queue exceeds x items.
Explanation
This retains a moving window of recent items.
- 51
What is the role of a queue in breadth-first search?
Model answer
It holds discovered nodes awaiting processing, so nodes are explored in expanding layers from the start node.
Explanation
Dequeue a node, then enqueue its unvisited neighbors.
- 52
Why might breadth-first search fail to visit a node in a disconnected graph?
Model answer
A node in a separate component is unreachable from the chosen starting node.
Explanation
The search ends when no reachable nodes remain in its queue.
- 53
What are the typical complexities of queue enqueue, dequeue, and peek operations, and of searching for or removing an arbitrary element?
Model answer
Enqueue, dequeue, and peek are O(1); searching for or removing an arbitrary element is O(n).
Explanation
An arbitrary element may require scanning the queue.
- 54
What does a priority queue guarantee about which element is removed next?
Model answer
It removes an element with the highest priority among those currently present.
Explanation
The priority ordering determines which element comes out first.
- 55
Why must elements in a priority queue be comparable?
Model answer
They must be orderable so the structure can assign relative priorities.
Explanation
Without an ordering, the next highest-priority element cannot be determined.
- 56
What is the difference between a priority queue and a heap?
Model answer
A priority queue is an abstract data type defining behavior; a heap is one possible implementation.
Explanation
Other structures can implement the same priority-queue behavior, though with different performance.
- 57
What is the heap invariant, and how do min-heaps and max-heaps differ?
Model answer
Every parent is ordered relative to its children; a min-heap has parents no greater than their children, while a max-heap has parents no smaller than their children.
Explanation
The root therefore stores a minimum in a min-heap or a maximum in a max-heap.
- 58
What structural condition must every heap satisfy?
Model answer
A heap must be a tree and satisfy its heap invariant.
Explanation
A structure containing a cycle is not a heap.
- 59
What is the complete binary tree property?
Model answer
Every level except possibly the last is full, and nodes on the last level are as far left as possible.
Explanation
This property determines where the next node is inserted.
- 60
How is a complete binary heap commonly represented in an array, and how are child indices calculated with zero-based indexing?
Model answer
Read the array level by level; for a node at index i, its left and right children are at 2i+1 and 2i+2.
Explanation
The array representation makes parent and child locations easy to compute.
- 61
How is a value inserted into a binary heap while preserving its properties?
Model answer
Place it at the next complete-tree position, then bubble it up by swapping with its parent until the heap invariant holds.
Explanation
This upward adjustment is also called swimming or sifting up.
- 62
How is the root removed from a binary heap?
Model answer
Swap the root with the last element, remove the last element, then bubble the new root down until the heap invariant holds.
Explanation
During sinking, swap with the more suitable child, such as the smaller child in a min-heap.
- 63
Why can removing an arbitrary non-root value from a heap take linear time in a basic implementation?
Model answer
The implementation must first scan the heap to find the valueâs position.
Explanation
Once found, the node can be exchanged with the last element and the heap repaired.
- 64
What are the complexities of peeking, adding, polling, and building a heap from an unordered array?
Model answer
Peek is O(1); add and poll are O(logn); heap construction can be done in O(n).
Explanation
Adding and polling may require restoring the heap invariant.
- 65
How can a hash table improve arbitrary removal and containment checks in a heap?
Model answer
Map each value to the heap index or indices where it occurs; this can make containment checks constant time and removal logarithmic, at the cost of extra space and update overhead.
Explanation
The mapping must be updated whenever heap elements move.
- 66
How can a min-priority queue be made to behave like a max-priority queue?
Model answer
Reverse the comparison ordering, or for numbers, negate values when inserting and negate them again when retrieving.
Explanation
The reversed ordering makes larger original values come out first.
- 67
Why should negating a comparator preserve equality?
Model answer
Equal elements must remain equal under the reversed ordering; negation reverses less-than and greater-than while leaving equality unchanged.
Explanation
A reversed comparator must change order without changing which values compare as equal.
- 68
What is an indexed priority queue, and what problem does it solve?
Model answer
It is a priority queue that associates keys with values and supports efficient lookup, update, and deletion of a particular keyâs entry.
Explanation
A traditional heap may need a linear scan to locate an arbitrary value.
- 69
What mappings are maintained by an indexed priority queue implemented as a heap?
Model answer
It maintains key-to-index identification, a position map from key indices to heap positions, an inverse map from heap positions to key indices, and a values array indexed by key index.
Explanation
The two maps let the structure locate a keyâs node and identify the key at a node.
- 70
How does an indexed priority queue keep its maps correct when swapping heap nodes?
Model answer
It swaps the relevant key-index entries in the inverse map and updates the corresponding positions in the position map; the values array stays indexed by key.
Explanation
Heap positions change during swaps, but key-associated values need not move.
- 71
How does an indexed priority queue insert a key-value pair?
Model answer
Assign or obtain its key index, store its value, place it at the next heap position, update both maps, and swim it until the heap invariant holds.
Explanation
Map updates are needed both at insertion and during subsequent swaps.
- 72
How does an indexed priority queue remove a specified key efficiently?
Model answer
Use the key index and position map to find its node, swap it with the last node, remove it, then swim or sink the replacement as needed.
Explanation
The maps avoid a linear scan for the nodeâs location.
- 73
What are the typical complexities of an indexed priority queueâs key lookup, insertion, removal, and update?
Model answer
Key lookup is O(1), while insertion, removal, and updates that restore heap order are O(logn).
Explanation
The maps locate nodes quickly; heap reordering accounts for logarithmic work.
- 74
What do increase-key and decrease-key operations do?
Model answer
They update a keyâs value only when the new value increases or decreases it, respectively, according to the queueâs ordering.
Explanation
They are restricted update operations useful in algorithms such as shortest-path and minimum-spanning-tree algorithms.
- 75
What does a union-find data structure track, and what are its two main operations?
Model answer
It tracks elements partitioned into disjoint sets; find identifies an elementâs set, and union merges two sets.
Explanation
It is also called a disjoint-set structure.
- 76
How can union-find represent groups that merge over time?
Model answer
Initially separate elements belong to separate sets; union merges selected sets, and find reports the set an element currently belongs to.
Explanation
The structure supports repeated group merging and membership queries.
- 77
What kinds of problems use union-find?
Model answer
Applications include Kruskalâs minimum spanning tree algorithm, grid percolation, graph connectivity, image processing, and some tree problems.
Explanation
These tasks often need repeated connectivity checks or group merges.
- 78
What is a minimum spanning tree?
Model answer
It is a subset of a graphâs edges that connects all vertices with minimum total edge weight.
Explanation
A graph may have more than one minimum spanning tree.
- 79
How does Kruskalâs algorithm use union-find?
Model answer
Sort edges by increasing weight; add an edge only when its endpoints are in different sets, then union those sets.
Explanation
Skipping edges within the same set avoids creating cycles.
- 80
How can union-find be represented using an array?
Model answer
Each array entry records an elementâs parent; initially each element is its own parent and therefore a root.
Explanation
A mapping from objects to integer indices can make this array-based representation practical.
- 81
How does find determine an elementâs set in an array-based union-find?
Model answer
Follow parent links until reaching a root whose parent is itself.
Explanation
The root identifies the component to which the element belongs.
- 82
How does union merge two components in a basic union-find?
Model answer
Find both roots; if they differ, make one root the parent of the other.
Explanation
If the roots are already equal, the elements are already in the same component.
- 83
What does path compression do in union-find?
Model answer
During find, it makes nodes along the traversed path point directly to the root.
Explanation
Future lookups along that path then require fewer parent-link steps.
- 84
What are the stated complexities of union-find with path compression?
Model answer
Construction is linear; find and union are amortized constant time, and counting components is constant time.
Explanation
The amortized bound results from the structureâs optimizations over a sequence of operations.
- 85
How does union-find maintain a count of components?
Model answer
It starts with one component per element and decreases the count by one whenever two distinct components are merged.
Explanation
The number of components equals the number of roots.
- 86
What defines a tree in the graph-theoretic descriptions given?
Model answer
A tree is a connected, acyclic undirected graph; equivalently, a tree with n nodes has nâ1 edges and exactly one path between any two vertices.
Explanation
A cycle would create more than one route between some vertices.
- 87
What are a root, parent, child, leaf, and subtree in a rooted tree?
Model answer
The root is the topmost node; a parent is above its child; a leaf has no children; and a subtree is a node together with its descendants.
Explanation
A subtree may consist of a single node.
- 88
What makes a tree a binary tree?
Model answer
Every node has at most two children.
Explanation
A node may have zero, one, or two children.
- 89
What is the binary search tree invariant?
Model answer
Values in a nodeâs left subtree are smaller than the nodeâs value, and values in its right subtree are larger.
Explanation
The values must be comparable so the correct subtree can be selected.
- 90
Why can an ordinary binary search tree have logarithmic average-case but linear worst-case operations?
Model answer
A reasonably shaped tree has logarithmic height, but ordered insertions can make it degenerate into a chain of height proportional to n.
Explanation
Search, insertion, and deletion depend on the treeâs height.
- 91
How is a value inserted into a binary search tree?
Model answer
Start at the root, compare the value at each node, descend left for a smaller value or right for a larger one, and insert at a null position.
Explanation
Duplicate values must be handled according to the treeâs chosen policy.
- 92
What are the main cases when removing a node from a binary search tree?
Model answer
The node may be a leaf, have only a left or right subtree, or have both subtrees; a node with two subtrees is replaced using a successor from either side.
Explanation
The successor can be the largest value in the left subtree or the smallest in the right subtree.
- 93
How is a node with two children removed from a binary search tree?
Model answer
Copy the value of its in-order successorâtypically the smallest value in its right subtreeâinto the node, then remove the successor from its original position.
Explanation
The successorâs original position can then be handled as a simpler removal case.
- 94
How do preorder, inorder, and postorder traversals differ?
Model answer
Preorder visits a node before its subtrees; inorder visits it between the left and right subtrees; postorder visits it after both subtrees.
Explanation
Their recursive definitions differ in when the node is processed.
- 95
What special ordering does inorder traversal produce on a binary search tree?
Model answer
It visits the stored values in increasing order.
Explanation
The left subtree is visited before the node, and the right subtree afterward.
- 96
How does level-order traversal process a tree?
Model answer
It visits nodes one level at a time, typically using a queue and breadth-first search.
Explanation
Each nodeâs children are enqueued for later processing.
- 97
What is a balanced binary search tree, and why is balancing useful?
Model answer
It is a self-adjusting binary search tree that maintains logarithmic height, keeping operations logarithmic even in the worst case.
Explanation
Balancing prevents the tree from degenerating into a long chain.
- 98
Why are tree rotations valid operations on a binary search tree?
Model answer
They change the treeâs shape while preserving the ordering relationships required by the binary search tree invariant.
Explanation
The values remain ordered even though their parent-child links change.
- 99
What is the balance factor of an AVL node, and what values are allowed?
Model answer
It is the right-subtree height minus the left-subtree height; an AVL tree requires each nodeâs factor to be â1, 0, or 1.
Explanation
A factor of â2 or 2 requires rebalancing.
- 100
What rotations resolve the four AVL imbalance cases?
Model answer
Left-left uses a right rotation; left-right uses a left rotation on the child followed by a right rotation; right-right uses a left rotation; right-left uses a right rotation on the child followed by a left rotation.
Explanation
The double-rotation cases are first transformed into their corresponding single-rotation cases.
- 101
What information must an AVL implementation update after insertion, removal, or rotation?
Model answer
It must update node heights and balance factors, then rebalance where necessary.
Explanation
These values must reflect the changed subtrees for later decisions to be correct.
- 102
What is a hash table, and what must be true of its keys?
Model answer
A hash table maps keys to values using hashing; keys must be unique and hashable.
Explanation
Values may repeat, but a key identifies its associated entry.
- 103
What is a hash function?
Model answer
It maps a key to an integer in a fixed range that can be used to select a location in a table.
Explanation
The same kind of function can be defined for integers, strings, or other objects.
- 104
Why must a hash function be deterministic?
Model answer
The same key must always produce the same hash value, or the table may look in the wrong location for an entry.
Explanation
A hash function that depends on changing state or randomness is unsuitable for ordinary table operations.
- 105
What is a hash collision, and why should a hash function distribute keys uniformly?
Model answer
A collision occurs when distinct keys produce the same hash value; uniform distribution helps avoid crowded locations and excessive collisions.
Explanation
Poor distribution can degrade operations toward linear time.
- 106
What does it mean for a key type to be hashable?
Model answer
A hashable key has a deterministic hash function and is generally immutable so its hash does not change while it is used as a key.
Explanation
Changing a key after insertion could make it unreachable in the table.
- 107
How does a hash table use a hash value to access an entry?
Model answer
It uses the hash value, normalized to a valid table index, to locate the entryâs bucket or slot.
Explanation
This indexed access is the basis of the hash tableâs fast average performance.
- 108
Why can comparing hash values speed up checking whether two objects are equal?
Model answer
Different hash values prove the objects are unequal, so full comparison is unnecessary; matching hashes still require checking the objects themselves.
Explanation
Equal hash values do not guarantee equal objects.
- 109
What are the two common hash-collision resolution strategies described?
Model answer
Separate chaining stores colliding entries in an auxiliary structure; open addressing probes for another slot within the table array.
Explanation
Separate chaining uses extra structures, while open addressing stores entries directly in the table.
- 110
How does separate chaining handle a collision and a lookup?
Model answer
Each bucket holds a collection, often a linked list; after hashing to a bucket, scan that collection to find the matching key.
Explanation
The key is checked because multiple entries may share the same bucket.
- 111
Can a separate-chaining bucket use a structure other than a linked list?
Model answer
Yes. It can use arrays, trees, balanced trees, or a hybrid structure.
Explanation
The bucket structure is an implementation choice.
- 112
What is a hash tableâs load factor, and why resize the table?
Model answer
The load factor is the number of stored items divided by table capacity; resizing provides more room and helps limit collision-related slowdowns.
Explanation
After resizing, stored entries must be rehashed for their new table positions.
- 113
What are the average and worst-case operation complexities for a hash table?
Model answer
Insertion, lookup, and removal can be O(1) on average, but can become O(n) with poor hashing or heavy collisions.
Explanation
Performance depends on how effectively keys are distributed.
- 114
How does open addressing resolve a collision?
Model answer
It follows a probing sequence from the keyâs initial hashed position until it finds an available slot.
Explanation
The key-value pairs remain in the hash table array itself.
- 115
What is the load factorâs significance for open addressing?
Model answer
As the table fills, finding an open slot becomes harder, so the load factor must be kept below a chosen threshold by resizing.
Explanation
A high load factor can make probing increasingly costly.
- 116
What is linear probing, and what condition helps its probing sequence visit every table slot?
Model answer
Linear probing offsets the initial position by a linear function; for a step size a, it visits every slot when a and the table size n are relatively prime.
Explanation
A greatest common divisor of 1 prevents a shorter repeating cycle.
- 117
What is quadratic probing, and why must its parameters be chosen carefully?
Model answer
It uses a quadratic function for offsets; some choices cycle through only part of the table and can fail to reach an empty slot.
Explanation
Working schemes impose conditions on the probing formula, table size, or load factor.
- 118
How does double hashing choose probe offsets, and how can a full-cycle sequence be encouraged?
Model answer
It uses a second hash function to determine the probe step; choosing a prime table size and a nonzero step relatively prime to it supports a full cycle.
Explanation
A zero step would repeatedly inspect the same location.
- 119
Why can naive deletion break searches in an open-addressed table?
Model answer
Replacing a deleted entry with an empty slot can make a later search stop before reaching a colliding key stored farther along the probe sequence.
Explanation
An empty slot normally signals that the search can end.
- 120
How do tombstones support deletion in open addressing?
Model answer
Mark a deleted slot with a tombstone; searches skip it and continue probing, while insertions may reuse it.
Explanation
Tombstones distinguish deleted entries from slots that were never occupied.
- 121
How can a tombstone encountered during a search improve later lookup performance?
Model answer
After finding the target farther along the probe sequence, move it into the first encountered tombstone and mark its former slot deleted.
Explanation
This lazy relocation shortens the path of future lookups.
- 122
How are tombstones eventually removed from an open-addressed table?
Model answer
They disappear when the table is resized and entries are reinserted; they may also be reused by new insertions.
Explanation
Tombstones contribute to occupied capacity and can otherwise accumulate.
- 123
What does a Fenwick tree support, and what problem motivates it?
Model answer
It supports range-sum queries and point updates efficiently; it improves on prefix sums, which make queries fast but require costly recomputation after an update.
Explanation
A Fenwick tree supports both operations in logarithmic time.
- 124
How does a Fenwick tree organize responsibility for array ranges?
Model answer
Each cell stores information for a range determined by its indexâs least significant set bit.
Explanation
The responsible range has length equal to that bitâs value.
- 125
How is a Fenwick-tree prefix sum computed?
Model answer
Start at the requested index, add its stored value, and repeatedly subtract the indexâs least significant set bit until reaching zero.
Explanation
This visits the disjoint ranges that together cover the prefix.
- 126
How is a range sum obtained from Fenwick-tree prefix sums?
Model answer
Subtract the prefix sum immediately before the range from the prefix sum through its final index.
Explanation
The difference cancels the values outside the requested interval.
- 127
How does a Fenwick tree perform a point update?
Model answer
Add the update value at the target index, then repeatedly add the least significant set bit to find and update the cells responsible for it.
Explanation
This moves upward through the cells whose ranges include the updated position.
- 128
How can a Fenwick tree be constructed in linear time?
Model answer
Copy the input values into the tree array, then propagate each value to its immediate parent at index i+LSB(i) when that parent is in bounds.
Explanation
Propagating contributions in place avoids performing a separate logarithmic update for every element.
- 129
What are the typical complexities of Fenwick-tree construction, point updates, and range queries?
Model answer
Construction can be O(n); point updates and range queries are O(logn).
Explanation
Queries and updates visit a logarithmic number of index positions.
- 130
What indexing convention is commonly used for Fenwick trees?
Model answer
Fenwick trees commonly use one-based indexing.
Explanation
The least-significant-bit operations rely on positive index values.
- 131
What is a suffix of a string, and what is a suffix array?
Model answer
A suffix is a nonempty substring extending to the end of a string; a suffix array stores the starting indices of all suffixes sorted lexicographically.
Explanation
The original string and sorted indices represent the suffixes without storing each suffix separately.
- 132
Why are suffix arrays more space-efficient than storing every suffix explicitly?
Model answer
They store the original string and the starting indices of sorted suffixes rather than separate copies of all suffix strings.
Explanation
This gives a compressed representation of the sorted suffixes.
- 133
What does an LCP array record?
Model answer
Each entry records the length of the longest common prefix of a pair of adjacent sorted suffixes.
Explanation
The first entry is conventionally set to zero because it has no preceding suffix.
- 134
How can suffix-array and LCP information count the unique substrings of a string?
Model answer
There are n(n+1)/2 substrings in total, and the sum of the LCP values counts repeated substrings; subtract that sum to obtain the number of unique substrings.
Explanation
Each common-prefix character accounts for a substring duplicated between adjacent sorted suffixes.
- 135
How can a suffix array and LCP array find the longest repeated substring?
Model answer
Find the maximum LCP value; the corresponding shared prefix is a longest repeated substring.
Explanation
If several entries share the maximum value, there can be multiple longest repeated substrings.
- 136
How can suffix arrays help find the longest common substring shared by at least k of several strings?
Model answer
Concatenate the strings with distinct, lexicographically small sentinels, build the suffix and LCP arrays, then use a sliding window containing suffixes from at least k different strings and maximize the windowâs minimum LCP.
Explanation
The sentinels separate source strings, and the window tracks whether enough distinct strings contribute.
- 137
Why are distinct sentinel characters needed when concatenating strings for a multi-string suffix-array search?
Model answer
They prevent suffixes from running across string boundaries and identify where each original string ends.
Explanation
The sentinels should sort before the ordinary characters so their suffixes can be ignored at the start of the sorted order.
- 138
How does the sliding-window method for the k-string longest common substring problem adjust its window?
Model answer
Expand the window when it lacks enough distinct source strings; when it contains enough, query its minimum LCP and shrink the window.
Explanation
A color-count structure, such as a hash table, can track which source strings are represented.
- 139
What is the longest common substring, and how does a suffix-array approach compare with dynamic programming?
Model answer
It is the longest contiguous substring shared by the required strings; the material contrasts dynamic programming with a suffix-array approach that can run in time proportional to the total input length.
Explanation
The suffix-array method uses suffix and LCP information rather than comparing all string-position combinations.

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