hi, let Avik connect you.
** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.
** You can check all the posts on the Posts page.
** More about me in the About Me section.
Print the Pattern
Problem: Print the Pattern
Problem Link: https://www.codingninjas.com/codestudio/problems/print-the-pattern_893299
Companies Asked: MindTree
Approach:
There will be N rows and N columns.
Starting from N = 1 to N*N fill the first N numbers into the 0th row.
Then insert the next N numbers into (N-1)th row.
For the next N numbers, insert them into 1st row.
Then for the next N number, insert them into (N-2)th row.
Keep doing until we met at the end.
Time and Space Complexity:
Time Complexity: O(N*N)
Space Complexity: O(N*N)
Code [C++]
#include <bits/stdc++.h>
string to_str(int number){
string newStr = "";
while(number){
char ch = (number % 10) + '0';
newStr += ch;
number /= 10;
}
reverse(newStr.begin(), newStr.end());
return newStr;
}
vector<string> printPattern(int n)
{
vector<string>ans(n, "");
int number = 1;
for(int i=0; i<=(n/2 - (n % 2 == 0)); i++){
for(int j=0; j<n; j++){
if(j > 0) ans[i] += " ";
ans[i] += to_str(number);
number++;
}
if(i == n/2 && (n % 2) == 1) break;
for(int j=0; j<n; j++){
if(j > 0) ans[n-i-1] += " ";
ans[n-i-1] += to_str(number);
number++;
}
}
return ans;
}