Krishnatejaswi S

Permutations

Link to the problem : Permutations

Intuition

The idea is to generate a permutation of the numbers from 1 to n such that the difference between any two consecutive elements is at least greater than 1.

One way to do this is to first write all the even numbers between 1 and n in increasing order and then write all the odd numbers between 1 and n in increasing order.

This is only one such solution. There are other solutions as well.

Edge case:

Solution

 1def main():
 2    n = int(input())
 3    if n == 1:
 4        print(1)
 5        return
 6    if n < 4:
 7        print("NO SOLUTION")
 8        return
 9    for i in range(2,n+1,2):
10        print(i, end=" ")
11    for i in range(1,n+1,2):
12        print(i, end=" ")
13
14if __name__ == "__main__":
15    main()

Other possible solutions

Reply to this post by email ↪