Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element copies caused by 1000 appends.
Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element copies caused by 1000 appends.
cap, size, copies = 1, 0, 0
for _ in range(1000):
if size == cap:
copies += size; cap *= 2
size += 1
print(copies)What is printed?- A. 1000
- B. 999
- C. 1023
- D. 2047
Correct answer: C. 1023
Resizes happen at sizes 1, 2, 4, …, 512, copying 1 + 2 + … + 512 = 1023 elements. This geometric sum is below 2n, so each append costs O(1) amortised.
More Coding Interview Problems questions
- Problem: A Rabin–Karp search uses a weak hash (the sum of character codes) and verifies every hash hit. Count true matches and spurious…
- Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix'). python def happy(s): p = [0] len(s); k = 0 for i…
- Problem: Generate the 'look-and-say' sequence starting from '1'. python def nxt(s): out, i = [], 0 while i < len(s): j = i while j <…
- Problem: Print a matrix in spiral order. python def spiral(m): res = [] while m: res += m.pop(0) m = [list(r) for r in zip(m)][::-1]…
- Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with…
- In the Tower of Hanoi with 5 discs and 3 pegs A, B, C in a row, moves are allowed only between ADJACENT pegs (A↔B, B↔C, never A↔C…