Data Structures & AlgorithmsVery hardProduct Company SDE · matrix simulation
Problem: What is the spiral (clockwise from the top-left) traversal of the matrix [[1,2,3],[4,5,6],[7,8,9]]? Print the list produced by the code.
Problem: What is the spiral (clockwise from the top-left) traversal of the matrix [[1,2,3],[4,5,6],[7,8,9]]? Print the list produced by the code.
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
out = []
top, bot, left, right = 0, 2, 0, 2
while top <= bot and left <= right:
out += M[top][left:right + 1]
top += 1
out += [M[r][right] for r in range(top, bot + 1)]
right -= 1
if top <= bot:
out += M[bot][left:right + 1][::-1]
bot -= 1
if left <= right and top <= bot:
out += [M[r][left] for r in range(bot, top - 1, -1)]
left += 1
print(out)What is printed?- A. [1, 2, 3, 6, 9, 8, 7, 5, 4]
- B. [1, 4, 7, 8, 9, 6, 3, 2, 5]
- C. [1, 2, 3, 6, 9, 8, 7, 4]
- D. [1, 2, 3, 6, 9, 8, 7, 4, 5]
Correct answer: D. [1, 2, 3, 6, 9, 8, 7, 4, 5]
The boundaries shrink after each side, which yields 1, 2, 3, then 6, 9, then 8, 7, then 4, and finally the centre 5.
More Coding Interview Problems questions
- Problem: How many swaps does insertion sort perform on [3, 2, 1]? Count the shifts in the code. python a = [3, 2, 1] swaps = 0 for i in…
- Problem: What is the minimum number of intervals from [[1,4],[3,7],[6,10],[9,10]] needed to cover the segment [1, 10]? Run the greedy…
- Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] XOR a[j] = 1? Run the code. python a = [1, 2, 3, 4, 5] print(sum(1 for i in…
- Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code. python from collections import…
- Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the…
- Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP. python a, b = 'horse', 'ros' dp = [[0] (len(b) + 1) for…