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.
Number Pattern
Problem: Number Pattern
Problem Link: www.codingninjas.com/codestudio/problems/number-pattern_1263682
Companies Asked: Adobe
Approach:
Declare a 2D vector, ans, and a variable number.
First, run a loop from 0 to N.
Run a loop nested to the previous loop from 0 to n-i.
Insert the number into the ans[i].
Increase the number by one.
Then, run a loop from n-1 to 0.
Run a loop nested to the previous loop from 0 to n-i.
Insert the number into the ans[i].
Increase the number by one.
Return ans.
Time and Space Complexity:
Time Complexity: O(N^2)
Space Complexity: O(N^2)
Code [C++]
#include <bits/stdc++.h>
vector<vector<int>>printPattern(int n)
{
int total_numbers = 1;
vector<vector<int>>ans(n);
for(int i=0; i<n; i++){
for(int j=0; j<n-i; j++){
ans[i].push_back(total_numbers++);
}
}
for(int i=n-1; i>=0; i--){
for(int j=0; j<n-i; j++){
ans[i].push_back(total_numbers++);
}
}
return ans;
}