Given a number n. The task is to print n-integers n-times (starting from 1) and right rotate the integers by after each iteration.
Examples:
Input: 6
Output :
1 2 3 4 5 6
2 3 4 5 6 1
3 4 5 6 1 2
4 5 6 1 2 3
5 6 1 2 3 4
6 1 2 3 4 5
Input : 3
Output :
1 2 3
2 3 1
3 1 2
Method 1:
Below is the implementation.
Python3
def print_pattern(n):
for i in range ( 1 , n + 1 , 1 ):
for j in range ( 1 , n + 1 , 1 ):
if i = = j:
print (j, end = " " )
if i < = j:
for k in range (j + 1 , n + 1 , 1 ):
print (k, end = " " )
for p in range ( 1 , j, 1 ):
print (p, end = " " )
print ()
print_pattern( 3 )
|
Method 2: Using pop(),append() and loops
Python3
def print_pattern(n):
x = []
for i in range ( 1 , n + 1 ):
x.append(i)
print (i, end = " " )
print ()
j = 0
while (j < n - 1 ):
a = x[ 0 ]
x.pop( 0 )
x.append(a)
for k in x:
print (k, end = " " )
print ()
j + = 1
print_pattern( 6 )
|
Output
1 2 3 4 5 6
2 3 4 5 6 1
3 4 5 6 1 2
4 5 6 1 2 3
5 6 1 2 3 4
6 1 2 3 4 5
Using modulus operator: In this approach, we are using the modulus operator and adding i to the loop variable j to get the current number in each iteration. The time complexity of this approach is O(n^2) as it requires two nested loops. The space complexity is O(1) as we are only using a few variables and not using any extra data structures.
Python3
def print_pattern(n):
for i in range (n):
for j in range (n):
print ((j + i) % n + 1 , end = " " )
print ()
print_pattern( 6 )
|
Output
1 2 3 4 5 6
2 3 4 5 6 1
3 4 5 6 1 2
4 5 6 1 2 3
5 6 1 2 3 4
6 1 2 3 4 5
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Feb, 2023
Like Article
Save Article