Number Pattern

Easy
0/40
Average time to solve is 10m
profile
Contributed by
58 upvotes
Asked in companies
AdobeREACH Technologies

Problem statement

Write a program such that you are given an integer ‘N’ and print the pattern consisting of ‘N’ lines.

For Example :
If we are given N=3
The pattern is :
1 2 3 10 11 12 
4 5 8 9 
6 7 
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first and only line contains a single integer ‘N’.
Output Format :
Return the 2D list such that the first list contains elements in the first row, the second list contains elements in the second row and so on.
Constraints :
1 <= N <= 1000

Time Limit : 1sec
Sample Input 1 :
2 
Sample Output 1 :
1 2 5 6 
3 4 
Sample Input 2 :
4
Sample Output 2 :
1 2 3 4 17 18 19 20 
5 6 7 14 15 16 
8 9 12 13 
10 11 
Hint

Divide the pattern into 2 parts.

Approaches (1)
Approach1

Explanation:- The main idea is to divide the patterns into 2 parts. For example:-

N=4

LHS:

1 2 3 4

5 6 7

8 9

10

RHS:

17 18 19 20

14 15 16

12 13

11

In the LHS part, counting is from 1 to N* (N+1)/2.

In RHS part,counting is from (N * (N+1)/2) + 1 to N * (N+1) but from downwards to upwards.

Algorithm :

  • Run a loop from i=0 to N.
  • First, print the pattern from (i-1) * N+1 to (i-1) * N + N - (i-1).
  • Then print the pattern of reverse numbering.
Time Complexity

O(N^2),  Where N is the given input integer.

 

We are printing number from 1 to N*(N+1). Hence time complexity is O(N^2).

Space Complexity

O(1).

 

We are using constant space to solve this.

Code Solution
(100% EXP penalty)
Number Pattern
Full screen
Console