DSA sheet / Introductory

Permutations

easy about 15 min constructionmath
Open on CSES

The problem in brief

Given n (up to a million), output any ordering of the numbers 1 to n in which adjacent numbers never differ by exactly 1. If no such ordering exists, print NO SOLUTION. Any valid ordering is accepted.

Try it

Tab indents; press Esc, then Tab, to leave the box. Ctrl+Enter runs.

Hints

Stuck? Reveal one hint at a time. Each nudges without giving away the next.

The walkthrough

Spoilers ahead: open a section only after you have given the hints a fair try.

How to think

Constructive problems reward exploring small cases and hunting for structure, not for search. Brute force over all n! permutations is out for anything past 10, so ask what structure forbids “differ by 1”. The answer is parity: two numbers that differ by 1 always have opposite parity. If you write all numbers of one parity in a row, they trivially differ by even amounts.

That leaves one seam. Trying n = 2 and 3 by hand shows no arrangement works (2 numbers are consecutive; for 3, the number 2 is adjacent to one of its neighbours in value wherever it goes). From n = 4 on, the seam between “last even” and “first odd” is between a number at least 4 and the number 1, which are far apart. That is the whole solution.

The habit: split the universe by an invariant that makes the forbidden relation impossible inside each part, then check only the junctions.

Intuition

Two lines of people: all the even-numbered ones, then all the odd-numbered ones. Inside a line nobody is next to their numeric neighbour. The only place two people meet across lines is the join, and with at least four people the join pairs a large even number with 1.

Approach
  1. If n is 1, print 1.
  2. If n is 2 or 3, print NO SOLUTION.
  3. Otherwise print 2, 4, 6, … up to n, then 1, 3, 5, … up to n.

Edge cases: n = 1 is valid (a single number has no neighbours). For n = 4 the answer 2 4 1 3 has seam 4 to 1, difference 3. Build the output in one buffer, since n can be a million.

Complexity

O(n) time and O(n) output.

Solutions

Written from scratch and checked by compiling and running each one against a brute force on random inputs. Fast input/output, the way you would submit it.

Show solutions (C++17, Python 3, Java 17, Node.js)
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    scanf("%d", &n);
    if (n == 1) {
        puts("1");
    } else if (n <= 3) {
        puts("NO SOLUTION");
    } else {
        string out;
        for (int i = 2; i <= n; i += 2) out += to_string(i) + " ";
        for (int i = 1; i <= n; i += 2) out += to_string(i) + " ";
        out.pop_back();
        puts(out.c_str());
    }
    return 0;
}

Problem: CSES Problem Set (Antti Laaksonen, University of Helsinki), CC BY-NC-SA 4.0. The explanations and code above are original (© Anupam Kumar).

Related problems

Back to the sheet