Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Print a matrix in spiral order (clockwise from the top-left).
Problem: Print a matrix in spiral order (clockwise from the top-left).
vector<int> spiral(vector<vector<int>>& m) {
vector<int> out;
int top = 0, bot = m.size() - 1, l = 0, r = m[0].size() - 1;
while (top <= bot && l <= r) {
for (int c = l; c <= r; c++) out.push_back(m[top][c]); top++;
for (int i = top; i <= bot; i++) out.push_back(m[i][r]); r--;
if (top <= bot) { for (int c = r; c >= l; c--) out.push_back(m[bot][c]); bot--; }
if (l <= r) { for (int i = bot; i >= top; i--) out.push_back(m[i][l]); l++; }
}
return out;
}
// m = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}What does spiral(m) contain, in order?- A. 1 2 3 4 8 12 11 10 9 5 6 7 6
- B. 1 2 3 4 8 12 11 10 9 5 6 7
- C. 1 2 3 4 8 12 11 10 9 5 7 6
- D. 1 2 3 4 5 6 7 8 9 10 11 12
Correct answer: B. 1 2 3 4 8 12 11 10 9 5 6 7
Peel the boundary layer by layer. The guards 'if (top <= bot)' and 'if (l <= r)' stop the last row or column from being printed twice in non-square matrices (without them 6 would repeat). O(R·C).
More Coding Interview Problems questions
- Problem: Rotate an n × n image 90° clockwise in place. python def rotate(m): n = len(m) for i in range(n): for j in range(i + 1, n)…
- 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…