Here's a fairly simple task from CSES Problem Set - Permutations 1070 that reads:
A permutation of integers 1,2, …, n is called beautiful if there are no adjacent elements whose difference is 1.
Given n, construct a beautiful permutation if such a permutation exist
The constraints are pretty tight:
- Time limit: 1.00 s
- Memory limit: 512 MB
- 1 ≤ n ≤ 10^6
Here's the code:
n = int(input())
if n == 2 or n == 3:
print("NO SOLUTION")
elif n == 1:
print(1)
elif n == 4:
print("3 1 4 2")
else:
for i in range(1, n + 1, 2):
print(str(i) + " ", end=" ")
for i in range(2, n + 1, 2):
print(str(i) + " ", end=" ")
It passes all tests except for n = 1000000. For that test it takes 15 sec. on my machine. The code is in Python 3.8
The question is, what can can be improved in terms of printing the numbers?