#C7568. Rearrange List to Avoid Adjacent Consecutive Numbers

    ID: 51453 Type: Default 1000ms 256MiB

Rearrange List to Avoid Adjacent Consecutive Numbers

Rearrange List to Avoid Adjacent Consecutive Numbers

You are given a list of unique integers. Your task is to determine whether it is possible to rearrange the list such that the absolute difference between any two adjacent elements is not equal to 1.

In other words, if the rearranged list is denoted as \(a_1, a_2, \dots, a_n\), then for every \(i\) with \(1 \le i < n\), it must hold that:

[ |a_{i+1} - a_i| \neq 1 ]

Note: In this problem, the input will be given in the standard input (stdin) where the first line contains an integer \(n\) representing the number of elements, and the second line contains \(n\) space-separated integers. The output should be printed to the standard output (stdout) as either True or False (without quotes).

Examples:

  • For input: 4\n1 3 7 9, one valid rearrangement is the sorted order [1, 3, 7, 9] with adjacent differences 2, 4, and 2. Thus, the output is True.
  • For input: 5\n3 4 5 1 7, the sorted order [1, 3, 4, 5, 7] has differences 2, 1, 1, and 2. Since there exist adjacent differences equal to 1, the output is False.

The intended solution uses a simple strategy by sorting the list and then checking if there is any pair of consecutive numbers (which will be adjacent in the sorted order). If such a pair exists, then it is assumed that no valid rearrangement exists; otherwise, it is valid.

inputFormat

The first line of input contains an integer \(n\) (\(n \ge 0\)), representing the number of elements in the list. The second line contains \(n\) space-separated integers.

If \(n = 0\), then the list is empty.

outputFormat

Output a single line: True if it is possible to rearrange the list such that the absolute difference between any two adjacent elements is not 1, and False otherwise.

## sample
4
1 3 7 9
True