Choose the scenario where using an array is better than using a linked list.
Think about how arrays store elements contiguously and how that affects access speed.
Arrays store elements in continuous memory locations, allowing fast access by index. Linked lists require traversal to access elements, making arrays better for random access.
What is the output of the following C code simulating access times for array and linked list?
int main() { int arr[5] = {10, 20, 30, 40, 50}; struct Node { int val; struct Node* next; }; struct Node n1 = {10, NULL}, n2 = {20, NULL}, n3 = {30, NULL}, n4 = {40, NULL}, n5 = {50, NULL}; n1.next = &n2; n2.next = &n3; n3.next = &n4; n4.next = &n5; // Access 3rd element in array int arr_val = arr[2]; // Access 3rd element in linked list struct Node* temp = &n1; for(int i = 0; i < 2; i++) { temp = temp->next; } int list_val = temp->val; printf("Array value: %d\nLinked list value: %d\n", arr_val, list_val); return 0; }
Remember array indexing starts at 0 and linked list traversal moves node by node.
Accessing the 3rd element (index 2) in the array gives 30. Traversing two nodes from the head in the linked list also reaches the node with value 30.
Consider this C code snippet that tries to resize an array using malloc and memcpy. Identify the error causing a runtime crash.
int* resize_array(int* arr, int old_size, int new_size) { int* new_arr = malloc(new_size * sizeof(int)); memcpy(new_arr, arr, new_size * sizeof(int)); free(arr); return new_arr; }
Check the number of bytes copied compared to the original array size.
memcpy copies new_size elements, but the original array only has old_size elements. Copying beyond old_size causes undefined behavior and possible crash.
You need to store a collection of items where you must insert new items frequently at random positions and also access items by index quickly. Which data structure is best?
Think about which structure supports both fast insertion and fast indexed access.
Dynamic arrays have fast indexed access but slow insertions in the middle. Linked lists have fast insertions but slow indexed access. Balanced binary search trees can provide balanced performance for both operations.
Explain why arrays often provide better CPU cache performance compared to linked lists.
Consider how memory layout affects CPU cache behavior.
Arrays store elements next to each other in memory, so when CPU loads one element, nearby elements are also loaded into cache, improving access speed. Linked lists store elements scattered in memory, causing more cache misses.
