Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Rotate an n × n image 90° clockwise in place.
Problem: Rotate an n × n image 90° clockwise in place.
def rotate(m):
n = len(m)
for i in range(n):
for j in range(i + 1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m: row.reverse()
return m
print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))What is printed?- A. [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
- B. [[3, 6, 9], [2, 5, 8], [1, 4, 7]]
- C. [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
- D. [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
Correct answer: A. [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Transpose, then reverse each row = clockwise rotation. Transpose then reverse the column order of rows (or reverse rows first) gives counter-clockwise [[3,6,9],…]. The j loop starts at i + 1 so each pair is swapped once; starting at 0 would swap twice and undo the transpose. O(n²), O(1) space.
More Coding Interview Problems questions
- Problem: Set the whole row and column to 0 for every 0 in a matrix. python def zeroes(m): R, C = len(m), len(m[0]) rows = {r for r in…
- Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting. java static int majority(int[]…
- Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag). cpp void sort012(vector<int>& a) { int lo = 0, mid = 0, hi =…
- Problem: Find the next lexicographic permutation of a digit list in place. python def nextperm(a): i = len(a) - 2 while i >= 0 and a[i] >=…
- Problem: Count pairs of songs whose total duration is divisible by 60. python def pairs60(t): cnt = [0] 60; res = 0 for x in t: r = x % 60…
- Problem: Find the length of the longest subarray with equal numbers of 0s and 1s. python def longesteq(a): first = {0: -1}; bal = best = 0…