codekofi
← All problems

Problem 49

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1vector<int> solution(const vector<vector<int>>& grid) {
2
3 vector<int> ans;
4
5 if (grid.empty() || grid[0].empty()) {
6 return ans;
7 }
8
9 int rows = grid.size();
10 int cols = grid[0].size();
11
12 int top = 0;
13 int bottom = rows - 1;
14 int left = 0;
15 int right = cols - 1;
16
17 while (top <= bottom && left <= right) {
18
19 for (int c = left; c <= right; c++) {
20 ans.push_back(grid[top][c]);
21 }
22 top++;
23
24 for (int r = top; r <= bottom; r++) {
25 ans.push_back(grid[r][right]);
26 }
27 right--;
28
29 if (top <= bottom) {
30 for (int c = right; c >= left; c--) {
31 ans.push_back(grid[bottom][c]);
32 }
33 bottom--;
34 }
35
36 if (left <= right) {
37 for (int r = bottom; r >= top; r--) {
38 ans.push_back(grid[r][left]);
39 }
40 left++;
41 }
42 }
43
44 return ans;
45}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.