Which situation is best suited for using an array instead of other data structures like linked lists or hash tables?
Think about how arrays store elements contiguously and allow direct access by position.
Arrays store elements in continuous memory locations, so accessing any element by its index is very fast (constant time). Other structures like linked lists require traversal, and hash tables are optimized for key lookups, not index access.
What is the output of the following TypeScript code?
const arr = [10, 20, 30, 40]; const linkedList = { value: 10, next: { value: 20, next: { value: 30, next: null } } }; console.log(arr[2]); console.log(linkedList.next.next.value);
Remember array indices start at 0 and linked list traversal requires following 'next' pointers.
arr[2] accesses the third element in the array, which is 30. linkedList.next.next.value accesses the third node's value, also 30.
You need to store a collection of items where you will frequently insert new items in the middle and also need to access items by position quickly. Which data structure is the best choice?
Consider which structure allows efficient insertion and backward/forward traversal.
Doubly linked lists allow insertion anywhere efficiently and traversal in both directions, which helps with accessing elements near the insertion point. Arrays have fast access but slow insertion in the middle. Hash tables do not support positional access.
Consider this TypeScript code that inserts elements at the start of an array repeatedly. Why does it become slow as the array grows?
const arr: number[] = [];
for(let i = 0; i < 10000; i++) {
arr.unshift(i);
}Think about what happens internally when you add an element at the start of an array.
unshift inserts at the start, so all existing elements must move one position right, causing O(n) time per insertion. This slows down as the array grows.
Why might you choose an array instead of a hash table when storing data indexed by consecutive integers?
Consider memory layout and access speed for consecutive integer keys.
Arrays store elements contiguously, so accessing by consecutive integer indices is very fast and memory efficient. Hash tables have overhead for hashing and storing keys, making them less efficient for this use case.
