1. Home
  2. Explore
  3. Computer Science
  4. C Programming Data Structures

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

C Programming Data Structures

  • 36Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Array Limitations

What is the primary limitation of arrays as a data structure?

36 questions

  1. 1

    What is the primary limitation of arrays as a data structure?

    Model answer

    Arrays require you to decide their size in advance, making it difficult to grow or shrink them dynamically.

    Explanation

    Arrays store data contiguously in memory, which offers fast access. However, this contiguity also means their size must be fixed at the time of declaration. If you need more space later, you typically have to create a new, larger array and copy all elements, which is time-consuming. Conversely, allocating too much space upfront leads to wasted memory.

  2. 2

    Explain the difference between a data structure and an abstract data type (ADT).

    Model answer

    A data structure is a concrete way to organize data in memory using variables and pointers, while an abstract data type (ADT) is a higher-level, more conceptual description of how information is organized, focusing on its properties and operations without specifying implementation details.

    Explanation

    A data structure (like an array or a linked list) is a physical implementation of data organization in a computer's memory. An ADT (like a queue or a stack) defines a set of operations and behaviors, independent of how those operations are actually carried out. For example, a queue ADT defines 'enqueue' and 'dequeue' operations, but it could be implemented using an array or a linked list.

  3. 3

    Describe the First In, First Out (FIFO) property of a queue.

    Model answer

    The FIFO property of a queue means that the first element added to the queue is always the first one to be removed.

    Explanation

    Queues mimic real-world lines, such as waiting for a movie or printing documents. Elements are added to one end (enqueue) and removed from the other (dequeue). This ensures fairness, as items are processed in the order they arrived.

  4. 4

    What are the two fundamental operations associated with a queue?

    Model answer

    The two fundamental operations for a queue are enqueue, which adds an element to the queue, and dequeue, which removes an element from the queue.

    Explanation

    Enqueue conceptually represents joining the end of a line, while dequeue represents being served at the front of the line. These operations maintain the FIFO property of the queue.

  5. 5

    Why would a struct queue need to keep track of both capacity and size?

    Model answer

    A struct queue needs capacity to know the maximum number of items it can hold (e.g., a constant 50), and size to track the current number of valid items in the queue (e.g., 0 to 49), differentiating valid data from potential garbage values.

    Explanation

    Capacity is the total allocated space, usually fixed for an array-based implementation. Size, on the other hand, indicates how many of those allocated slots are currently occupied by meaningful data. This distinction is crucial for managing the queue, preventing overflows (when size equals capacity) and underflows (when attempting to dequeue from an empty queue, i.e., size is 0).

  6. 6

    Describe the Last In, First Out (LIFO) property of a stack.

    Model answer

    The LIFO property of a stack means that the last element added to the stack is always the first one to be removed.

    Explanation

    Stacks are like a pile of clothes or trays in a dining hall. You can only add or remove items from the 'top'. This means the most recently added item is the first one accessible, while items at the bottom might remain untouched for a long time.

  7. 7

    What are the two fundamental operations associated with a stack?

    Model answer

    The two fundamental operations for a stack are push, which adds an element to the top of the stack, and pop, which removes the top element from the stack.

    Explanation

    Push places an item on the stack, making it the new top element. Pop removes the current top element, revealing the item beneath it. These operations strictly adhere to the LIFO principle.

  8. 8

    In what real-world scenario might a stack (LIFO) be preferable or naturally occur compared to a queue (FIFO)?

    Model answer

    A real-world scenario where a stack naturally occurs is with items in a drawer like sweaters, where the last sweater put on top is the first one taken out. In technology, an email inbox often behaves like a stack where new emails appear at the top.

    Explanation

    While queues ensure fairness (first come, first served), stacks are useful in situations where only the most recent item needs immediate attention, or where physical constraints dictate LIFO behavior. Examples include undo/redo functionality in software, call stacks in programming, or managing browser history (last visited page is the first to go back to).

  9. 9

    What is the primary downside of using realloc to grow an array dynamically?

    Model answer

    Even though realloc is convenient, if the desired larger contiguous memory block isn't available at the original location, realloc must copy all existing data to a new, larger location, which incurs linear time complexity proportional to the number of elements.

    Explanation

    realloc attempts to extend the existing memory block in place. If it can't, it allocates a completely new, larger block of memory elsewhere, copies the contents of the old block to the new one, and then frees the old block. This copying operation takes time proportional to the size of the array, making repeated reallocations inefficient for frequent growth.

  10. 10

    Explain the time-space trade-off in computing, specifically as it relates to dynamic arrays and pre-allocating memory.

    Model answer

    The time-space trade-off means optimizing for speed often requires more memory, and vice-versa. Pre-allocating a large array saves time by avoiding costly realloc operations, but wastes space if not all of it is used.

    Explanation

    When growing an array, you can either: 1) Allocate just enough memory and realloc when needed, saving space but incurring time costs for copying (linear time). 2) Over-allocate a very large array from the start, saving time by always having enough space, but wasting memory if most of it remains unused. The optimal choice depends on the specific application's priorities.

  11. 11

    What are the three existing C syntaxes that, when combined with the new arrow operator, allow for building complex data structures like linked lists?

    Model answer

    The three existing C syntaxes are struct (and typedef), the . (dot) operator, and the * (star/dereference) operator. The new -> (arrow) operator simplifies accessing members of a structure through a pointer.

    Explanation

    The struct keyword allows you to define custom data types. typedef provides an alias for these structures. The . operator accesses members of a structure directly. The * operator dereferences a pointer to access the value it points to. The -> operator is a shorthand for (*pointer).member, used when accessing a structure member via a pointer.

  12. 12

    How does a linked list fundamentally solve the contiguity problem of arrays?

    Model answer

    A linked list solves the contiguity problem by storing data elements (nodes) at potentially non-contiguous locations in memory and using pointers within each node to link them together sequentially.

    Explanation

    Unlike arrays, where elements must be physically adjacent, a linked list allows elements to be scattered throughout memory. Each 'node' in the list contains not only the data but also a pointer (or reference) to the next node in the sequence. This flexible arrangement means new nodes can be inserted or deleted anywhere without shifting existing elements, making dynamic resizing efficient.

  13. 13

    What is the main downside of a linked list compared to an array, even though it offers dynamic sizing?

    Model answer

    The main downside of a linked list is the additional memory overhead required to store pointers for each node, and the inability to perform binary search efficiently due to non-contiguous memory access.

    Explanation

    Each node in a linked list stores data and a pointer to the next node. This pointer takes up extra memory compared to storing just the data in an array. Additionally, accessing an element in the middle of a linked list requires traversing from the beginning, making random access and binary search (which relies on random access) inefficient (typically O(n)).

  14. 14

    In the context of linked lists, what does NULL signify?

    Model answer

    In a linked list, NULL is a special sentinel value for a pointer that signifies the end of the list, indicating that there are no more nodes to follow.

    Explanation

    When a node's next pointer is NULL, it means that node is the last one in the sequence. The pointer to the head of an empty linked list is also NULL. This convention allows algorithms to correctly detect the start and end of a list during traversal, insertion, or deletion.

  15. 15

    What is the purpose of the head or list pointer in a linked list?

    Model answer

    The head or list pointer in a linked list is a single pointer that always keeps track of the memory address of the very first node in the list.

    Explanation

    Without a pointer to the beginning of the list (the 'head' or 'root'), you would lose access to all the nodes. This pointer serves as the entry point for all operations, such as traversing, searching, inserting, or deleting elements within the linked list.

  16. 16

    Why is it important to initialize a newly created node's next pointer to NULL?

    Model answer

    It's important to initialize a newly created node's next pointer to NULL to ensure it doesn't contain a garbage value, which could lead to unpredictable behavior or crashes if treated as a valid memory address.

    Explanation

    When memory is allocated with malloc, its contents are uninitialized ('garbage values'). If the next pointer is not explicitly set to NULL, it might point to a random, invalid memory location. This is crucial for correctly identifying the end of a list and preventing attempts to dereference invalid pointers.

  17. 17

    What is an 'orphaned' node in a linked list, and why is it a problem?

    Model answer

    An orphaned node is a chunk of allocated memory that is no longer pointed to by any variable in the program, making it impossible to access or free it later. This results in a memory leak.

    Explanation

    If you update a pointer (e.g., list = n) without ensuring that the previously pointed-to node (list before the update) is still accessible from somewhere else, that node becomes 'orphaned'. Since no variables point to it, the program loses its address and cannot interact with it, including freeing it. This memory remains reserved by the program but unusable, leading to a memory leak.

  18. 18

    What is the Big O running time for searching a linked list, and why?

    Model answer

    The Big O running time for searching a linked list is O(n), because in the worst case, you might have to traverse all 'n' nodes from the beginning to find the desired value.

    Explanation

    Linked lists do not allow for random access like arrays. To find an element, you must start at the head and follow each next pointer sequentially. If the item is at the end of the list or not present, you will visit every node, hence linear time complexity.

  19. 19

    What is the Big O running time for prepending (inserting at the beginning) a new node into a linked list, and why?

    Model answer

    The Big O running time for prepending a node into a linked list is O(1) (constant time), because it only involves updating a few pointers at the head of the list, regardless of the list's length.

    Explanation

    To prepend, you simply create a new node, set its next pointer to point to the current head of the list, and then update the list's head pointer to point to the new node. These operations take a fixed number of steps, irrespective of how many elements are already in the list, making it a constant-time operation.

  20. 20

    What is the Big O running time for appending (inserting at the end) a new node into a singly linked list, and why?

    Model answer

    The Big O running time for appending a node to a singly linked list is O(n), because in the worst case, you must traverse the entire list to find the last node before adding the new one.

    Explanation

    To append a node, you must start from the head and follow each next pointer until you reach the current last node (the one whose next pointer is NULL). Once found, you update its next pointer to point to the new node. This traversal takes time proportional to the number of nodes in the list, resulting in linear time complexity.

  21. 21

    When freeing memory in a linked list using a loop, why is it crucial to store the next pointer before freeing the current node?

    Model answer

    It's crucial to store the next pointer (e.g., in a temporary variable) before freeing the current node because once a node's memory is freed, accessing its next field is undefined behavior, as the memory might no longer be valid or owned by the program.

    Explanation

    If you try to access pointer->next after calling free(pointer), you are touching memory that the operating system has potentially reclaimed or repurposed. This can lead to crashes, corrupt data, or other unpredictable errors. By storing the next pointer before freeing, you retain the address needed to advance to the next node in the list.

  22. 22

    What is a binary search tree, and how does it combine aspects of arrays and linked lists?

    Model answer

    A binary search tree is a two-dimensional data structure where each node contains data and two pointers (left and right children). It combines the dynamic growth of linked lists with the ordered structure that allows for binary search, similar to sorted arrays.

    Explanation

    It's 'binary' because each node has at most two children. It's a 'search' tree because values are organized: all values in the left subtree are less than the node's value, and all in the right subtree are greater. This allows for efficient O(log n) searching like binary search on sorted arrays, while using pointers to dynamically allocate nodes like linked lists, avoiding the fixed-size limitation of arrays.

  23. 23

    Why can't binary search be performed efficiently on a singly linked list?

    Model answer

    Binary search cannot be performed efficiently on a singly linked list because it requires constant-time random access to elements (e.g., jumping to the middle), which linked lists do not support.

    Explanation

    A singly linked list only allows traversal in one direction, from head to tail. To find the middle element, you first need to count all elements (O(n)), then traverse half the list (O(n/2)). This repeated linear traversal makes binary search, which relies on quickly narrowing down the search space by jumping to the middle, inefficient and effectively degenerates to O(n) search.

  24. 24

    How do binary search trees achieve O(log n) search time, similar to binary search on a sorted array?

    Model answer

    Binary search trees achieve O(log n) search time by maintaining a hierarchical structure where at each node, the search path is narrowed down by comparing the target value with the node's value, deciding to go left (for smaller values) or right (for larger values).

    Explanation

    The 'binary search tree property' ensures that all nodes in the left subtree are less than the current node, and all in the right subtree are greater. This allows a 'divide and conquer' approach: starting at the root, you compare the target value. If it's less, you eliminate the right subtree; if greater, you eliminate the left. This effectively halves the remaining search space with each comparison, leading to logarithmic time complexity.

  25. 25

    What is the primary downside or risk associated with binary search trees, even with their O(log n) search time?

    Model answer

    The primary downside of binary search trees is that if elements are inserted in an unlucky, sorted, or reverse-sorted order, the tree can become unbalanced and degenerate into a linked list, causing search, insertion, and deletion times to revert to O(n).

    Explanation

    An 'unbalanced' tree occurs when most nodes are added to one side, creating a long, stringy path rather than a broad, shallow one. For example, inserting 1, 2, 3, 4, 5 sequentially will create a tree where each node only has a right child. In this scenario, searching for the last element requires traversing every node, just like a linked list, thereby losing the O(log n) advantage.

  26. 26

    What is a 'dictionary' as an abstract data type in computing?

    Model answer

    A dictionary (also known as a map or associative array) is an abstract data type that stores a collection of key-value pairs, allowing for efficient retrieval of a value based on its unique key.

    Explanation

    Like a physical dictionary that maps words to definitions, a computing dictionary maps a 'key' (e.g., a person's name) to a 'value' (e.g., their phone number). The key must be unique, allowing for direct lookup. This ADT focuses on the functionality of associating and retrieving information, not on the underlying storage method.

  27. 27

    What is the 'Holy Grail' of algorithms and data structures in terms of running time, and why is it sought after?

    Model answer

    The 'Holy Grail' is achieving O(1) or constant time complexity, meaning the operation takes a fixed amount of time regardless of the size of the input data.

    Explanation

    Constant time is ideal because performance doesn't degrade as the dataset grows. If an algorithm takes 10 steps for 10 items and 10 steps for a billion items, its efficiency is maximal. This is highly sought after for critical operations in large-scale systems.

  28. 28

    Explain the concept of 'hashing' and a 'hash function'.

    Model answer

    Hashing is the process of using a 'hash function' to map input data (like a key) of arbitrary size to a fixed-size output (a hash value or index), typically for determining where data should be stored in a data structure.

    Explanation

    A hash function takes an input (e.g., a string like 'Mario') and produces a numerical output (e.g., 12). The goal is to distribute inputs uniformly across a 'range' of possible outputs (e.g., 0-25 for 'buckets'). This allows data to be quickly placed into specific 'buckets' or locations, helping to organize and retrieve it efficiently.

  29. 29

    What is a 'hash table', and how is it typically implemented using other data structures?

    Model answer

    A hash table is a data structure that implements a dictionary by using a hash function to map keys to an array of buckets, where each bucket typically contains a linked list (or 'chain') to handle collisions.

    Explanation

    It's an 'array of linked lists'. The hash function takes a key (e.g., 'Mario') and calculates an index for the main array (e.g., index 12). If multiple keys map to the same index (a 'collision'), they are stored in a linked list at that array location. This allows for fast average-case lookup (O(1)) by jumping to the array index, then potentially traversing a short linked list.

  30. 30

    What is a 'collision' in the context of a hash table, and how are they typically handled?

    Model answer

    A collision occurs when two different keys, when passed through the hash function, produce the same hash value (i.e., map to the same bucket). Collisions are typically handled by storing all colliding keys in a linked list (or 'chain') at that specific bucket location.

    Explanation

    Since a hash function maps a potentially large set of inputs to a smaller, fixed set of outputs, collisions are inevitable (Birthday Problem). Chaining, where each array index points to the head of a linked list, is a common method. When a key hashes to an occupied bucket, the new key-value pair is simply added to the linked list already present at that bucket.

  31. 31

    In the worst-case scenario, what is the Big O running time for searching a hash table, and why?

    Model answer

    In the worst-case scenario, the Big O running time for searching a hash table can be O(n), because all 'n' elements might hash to the same bucket, effectively degenerating the hash table into a single linked list.

    Explanation

    If a poor hash function is used, or if input data is adversarially chosen, all keys might map to the same array index. In this extreme case, searching for an element would involve traversing a linked list containing all 'n' elements, which takes linear time. This is why a good hash function is critical for hash table performance.

  32. 32

    How can a hash function be made 'smarter' to reduce the probability of collisions?

    Model answer

    A hash function can be made 'smarter' by taking into account more of the input data (e.g., more than just the first letter of a name) and by mapping inputs to a much larger number of buckets to achieve a more uniform distribution.

    Explanation

    A naive hash function (like one only looking at the first letter) will have many collisions. A smarter function might combine ASCII values of several characters, use modulo arithmetic on prime numbers, or leverage more complex algorithms to produce hash values that are widely and evenly distributed across the available buckets. Increasing the number of buckets also statistically reduces collision probability.

  33. 33

    What is the trade-off of making a hash table much larger (e.g., 17,000 buckets instead of 26) to reduce collisions?

    Model answer

    The trade-off of making a hash table much larger to reduce collisions is a significant increase in memory usage, as most of the numerous buckets in the array will likely remain empty or unused, especially if the data set is sparse.

    Explanation

    While increasing the number of buckets improves the 'spread' of hashed items and reduces collisions, it means allocating a much larger underlying array. If the actual data stored is small relative to the number of buckets, a lot of memory will be wasted on empty array slots. This is a direct example of the space-time trade-off.

  34. 34

    What is a 'trie' data structure, and what is its primary advantage?

    Model answer

    A trie (prefix tree) is a tree-like data structure that is a tree of arrays, where each node is an array of pointers (typically 26 for the alphabet). Its primary advantage is providing true O(1) (constant time) search, insertion, and deletion, dependent only on the length of the key, not the total number of keys.

    Explanation

    Each path from the root to a node in a trie represents a prefix of a key, and keys are stored implicitly by their path through the tree. To find a key like 'TOAD', you traverse from the root: array[T] -> array[O] -> array[A] -> array[D]. The operations depend on the length of 'TOAD' (4 steps) and not on how many other words are in the trie. This makes it extremely fast for prefix-based searches and dictionary operations.

  35. 35

    How does a trie achieve constant time complexity for operations like search and insertion, independent of 'n' (the total number of items)?

    Model answer

    A trie achieves constant time complexity by structuring data based on prefixes, where each step of traversal corresponds to a character in the key. The time taken depends only on the length of the key (L), not the total number of keys (N), effectively making it O(L), which is bounded by a constant maximum key length.

    Explanation

    When searching for a word, you follow pointers from one array to the next, corresponding to each letter of the word. For example, finding 'Tom' involves three lookups (T, O, M). The time taken is proportional to the length of 'Tom', not the total number of words in the dictionary. Since word lengths have a practical upper bound, this effectively becomes constant time in a practical sense, as N can be vastly larger than L.

  36. 36

    What is the primary trade-off or disadvantage of using a trie data structure?

    Model answer

    The primary disadvantage of a trie is its significant memory consumption, as it often requires allocating a large number of arrays (each typically 26 pointers for the alphabet) even if many of the pointer slots remain unused.

    Explanation

    Each node in a trie is effectively an array (e.g., 26 pointers). For a long word, you might create many such arrays. If the dataset is sparse (e.g., many possible prefixes are not used by actual words), a large portion of these arrays will contain null pointers, leading to considerable memory waste. This is a stark example of trading space for time, achieving extremely fast operations at the cost of potentially high memory usage.

1 of 36
Question 1 of 36

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent