Printing 1,000,000 numbers in 1 sec. in Python 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(&quot;NO SOLUTION&quot;)
elif n == 1:
    print(1)
elif n == 4:
    print(&quot;3 1 4 2&quot;)
else:
    for i in range(1, n + 1, 2):
        print(str(i) + &quot; &quot;, end=&quot; &quot;)
    for i in range(2, n + 1, 2):
        print(str(i) + &quot; &quot;, end=&quot; &quot;)

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?
Nice solution, few suggestions:

Printing the numbers one by one might be the issue. Generate the list of numbers first and then call print only once.
The case n==1 is already handled, so the first elif can be removed.

Applying the suggestions:
n = int(input())
if n == 2 or n == 3:
    print(&quot;NO SOLUTION&quot;)
elif n == 4:
    print(&quot;3 1 4 2&quot;)
else:
    beautiful_perm = [*range(1, n + 1, 2), *range(2, n + 1, 2)]
    print(' '.join(map(str, beautiful_perm)))

By inverting the ranges we don't need to check for n==4:
n = int(input())
if n == 2 or n == 3:
    print(&quot;NO SOLUTION&quot;)
else:
    beautiful_perm = [*range(2, n + 1, 2), *range(1, n + 1, 2)]
    print(' '.join(map(str, beautiful_perm)))

Runtime on CSES:
n = 906819 (CPython3)
Original: 0.92 s
Improved: 0.26 s

n = 1000000 (CPython3)
Original: timeout
Improved: 0.28 s

n = 1000000 (PyPy3)
Original: 0.61 s
Improved: 0.15 s