
Introduction
Puzzles are good exercise for the brain. They help in enhancing the cognitive abilities of the brain helping with Problem Solving and related skills. There are numerous types of puzzles; each one having a logic inherent to itself which helps in cracking it. A good puzzle well is actually like a good mystery that we may have read about or watched on TV. It has the finest of hints which help in reaching its solution.
The following article discusses one such puzzle so let's get right to it.
Pattern
For Number of Rows = 5, the pattern is as follows
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
5 4 3 2 1 0
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
Approach
From the above pattern, it is visible that we print n+1 rows in increasing reverse order and then n rows in decreasing reverse order.
Increasing Reverse Order:
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
5 4 3 2 1 0
Decreasing Reverse Order
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
Brute Method: It can be achieved using 2 nested loops. One nested loop is used to print n+1 Increasing Reverse Pattern and another nested loop to print n Decreasing Reverse Pattern.
Optimized Method: Only one Nested loop is used with Improved Mathematical Logic.
Code using Brute Method
#include<stdio.h>
void main(){
int i,j;
int n=3;
for(i=0;i<=n;i++){
for(j=n;j>=n-i;j--){
printf("%d ",j);
}
printf("\n");
}
for(i=1;i<=n;i++){
for(j=n;j>=i;j--){
printf("%d ",j);
}
printf("\n");
}
}
Output
3
3 2
3 2 1
3 2 1 0
3 2 1
3 2
3
Complexity Analysis
Time Complexity: O(N2)
Space Complexity: O(1)
Code using Single Nested Loop
#include<stdio.h>
void main(){
int n=4,i,j,x;
for(i=n;i>=-n;i--){
if(i>=0)
x=i;
else
x=-1*i;
for(j=n;j>=x;j--){
printf("%d ",j);
}
printf("\n");
}
}
Output
4
4 3
4 3 2
4 3 2 1
4 3 2 1 0
4 3 2 1
4 3 2
4 3
4
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(1)