Which statement best describes the memory layout difference between an array and a linked list?
Think about how you find the next element in each data structure.
Arrays store elements next to each other in memory, making access by index fast. Linked lists store nodes anywhere in memory, each node pointing to the next, so elements are not contiguous.
Consider this JavaScript simulation of memory addresses for an array and a linked list. What is the printed output?
const array = [10, 20, 30]; const linkedList = [{value: 10, next: 1}, {value: 20, next: 2}, {value: 30, next: null}]; console.log('Array memory addresses:'); for(let i = 0; i < array.length; i++) { console.log(`Address ${100 + i * 4}: ${array[i]}`); } console.log('Linked list memory addresses:'); for(let i = 0; i < linkedList.length; i++) { console.log(`Address ${Math.floor(Math.random() * 1000)}: ${linkedList[i].value}`); }
Look at how the addresses for array elements are calculated versus linked list nodes.
The array elements have fixed addresses increasing by 4 bytes each (simulated). The linked list nodes have random addresses to simulate scattered memory.
Given this linked list traversal code, why does it cause an error?
const linkedList = { value: 1, next: { value: 2, next: { value: 3, next: null } } };
let current = linkedList;
while(current.next !== null) {
console.log(current.value);
current = current.next;
}
console.log(current.value);Check the loop condition and when values are printed.
The loop stops when current.next is null, so the last node's value is printed after the loop. This is intentional and does not cause an error.
What is the output after inserting value 15 at index 1 in both an array and a linked list?
let array = [10, 20, 30]; array.splice(1, 0, 15); function Node(value, next = null) { this.value = value; this.next = next; } let head = new Node(10, new Node(20, new Node(30))); function insertAt(head, index, value) { if(index === 0) return new Node(value, head); let current = head; let i = 0; while(current !== null && i < index - 1) { current = current.next; i++; } if(current === null) return head; current.next = new Node(value, current.next); return head; } head = insertAt(head, 1, 15); function printList(head) { let current = head; let result = ''; while(current !== null) { result += current.value + ' -> '; current = current.next; } result += 'null'; return result; } console.log('Array:', array); console.log('Linked List:', printList(head));
Check how splice works on arrays and how insertAt works on linked lists.
Inserting 15 at index 1 shifts elements in the array and inserts the new node in the linked list at the same position.
Why is inserting an element in the middle of a linked list generally faster than inserting in the middle of an array?
Think about what happens to elements after the insertion point in both structures.
Linked lists insert by changing pointers, no shifting needed. Arrays require shifting elements to make space, which takes more time.
