Data Structures & AlgorithmsHardGATE CS · DSA
Print a matrix in spiral order (right, down, left, up, repeat). What is printed?
Print a matrix in spiral order (right, down, left, up, repeat). What is printed?
m = [[10, 41, 52, 63], [20, 51, 42, 53], [40, 41, 62, 23]]
top, bot, l, r, out = 0, len(m) - 1, 0, len(m[0]) - 1, []
while top <= bot and l <= r:
out += m[top][l:r + 1]; top += 1
out += [m[i][r] for i in range(top, bot + 1)]; r -= 1
if top <= bot: out += m[bot][l:r + 1][::-1]; bot -= 1
if l <= r: out += [m[i][l] for i in range(bot, top - 1, -1)]; l += 1
print(out[6:6 + 4])- A. [41, 62, 40, 20]
- B. [40, 41, 62, 20]
- C. [62, 41, 20, 40]
- D. [62, 41, 40, 20]
Correct answer: D. [62, 41, 40, 20]
The bottom row is read right-to-left and the left column bottom-to-top; the guards stop a single remaining row or column from being read twice. Output: [62, 41, 40, 20].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Binary search with mid = (lo + hi) // 2 (lo = 0, hi = n − 1, loop while lo ≤ hi) looks for 86 in [11, 13, 17, 24, 25, 32, 36, 58, 65, 86…
- Rabin–Karp with a good rolling hash is used to find a pattern of length m in a text of length n. Which statement is correct?
- Reverse the order of words, collapsing multiple spaces. What is printed? python s = " the is new code " w = s.split() print("|" + "…
- Rabin–Karp with base 10 and a deliberately small modulus counts true matches and spurious hits (hash equal, text different). What is…
- 11 people stand in a circle numbered 1 to 11. Counting starts at person 1, and every 4th person is removed (counting continues from the…
- Kadane's algorithm runs on [−4, −7, 9, 3, −5, 4, 1, 4, 8]. What is the maximum sum of a non-empty contiguous subarray?