Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Rotate an array right by k in O(1) extra space with three reversals.
Problem: Rotate an array right by k in O(1) extra space with three reversals.
def rotate(a, k):
n = len(a); k %= n
def rev(i, j):
while i < j: a[i], a[j] = a[j], a[i]; i += 1; j -= 1
rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)
return a
print(rotate([1, 2, 3, 4, 5, 6, 7], 10))What is printed?- A. [4, 5, 6, 7, 1, 2, 3]
- B. [5, 6, 7, 1, 2, 3, 4]
- C. [7, 1, 2, 3, 4, 5, 6]
- D. [3, 2, 1, 7, 6, 5, 4]
Correct answer: B. [5, 6, 7, 1, 2, 3, 4]
k = 10 mod 7 = 3. Reversing all gives 7..1, then reversing the first 3 (5, 6, 7) and the last 4 (1, 2, 3, 4) yields [5, 6, 7, 1, 2, 3, 4]. Rotating LEFT by 3 would give [4, 5, 6, 7, 1, 2, 3].
More Coding Interview Problems questions
- Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment). python import math…
- Edge case: itertools.groupby on unsorted data. python from itertools import groupby data = "aabbbaacc" print([(k, len(list(g))) for k, g…
- Problem: Row n of Pascal's triangle built in place, plus two checks. python def row(n): r = [1] for in range(n): r = [1] + [r[i] + r[i+1]…
- Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted…
- Problem: What does the following print? It is the multiplicative inverse of 7 modulo 26. python print(pow(7, -1, 26))
- Problem: How many trailing zeros does 100! have? Run the code that counts factors of 5. python n = 100 c = 0 p = 5 while p <= n: c += n //…