Permutation Swap (Codeforces 1828B)
Tags: Math, number theory

You are given an unsorted permutation $$$p_1, p_2, \ldots, p_n$$$. To sort the permutation, you choose a constant $$$k$$$ ($$$k \ge 1$$$) and do some operations on the permutation. In one operation, you can choose two integers $$$i$$$, $$$j$$$ ($$$1 \le j < i \le n$$$) such that $$$i - j = k$$$, then swap $$$p_i$$$ and $$$p_j$$$.What is the maximum value of $$$k$$$ that you can choose to sort the given permutation?A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n = 3$$$ but there is $$$4$$$ in the array).An unsorted permutation $$$p$$$ is a permutation such that there is at least one position $$$i$$$ that satisfies $$$p_i \ne i$$$.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows.The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^{5}$$$) — the length of the permutation $$$p$$$.The second line of each test case contains $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) — the permutation $$$p$$$. It is guaranteed that the given numbers form a permutation of length $$$n$$$ and the given permutation is unsorted.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$.

Output: For each test case, output the maximum value of $$$k$$$ that you can choose to sort the given permutation.We can show that an answer always exists.

Note: In the first test case, the maximum value of $$$k$$$ you can choose is $$$1$$$. The operations used to sort the permutation are:   Swap $$$p_2$$$ and $$$p_1$$$ ($$$2 - 1 = 1$$$) $$$\rightarrow$$$ $$$p = [1, 3, 2]$$$  Swap $$$p_2$$$ and $$$p_3$$$ ($$$3 - 2 = 1$$$) $$$\rightarrow$$$ $$$p = [1, 2, 3]$$$ In the second test case, the maximum value of $$$k$$$ you can choose is $$$2$$$. The operations used to sort the permutation are:   Swap $$$p_3$$$ and $$$p_1$$$ ($$$3 - 1 = 2$$$) $$$\rightarrow$$$ $$$p = [1, 4, 3, 2]$$$  Swap $$$p_4$$$ and $$$p_2$$$ ($$$4 - 2 = 2$$$) $$$\rightarrow$$$ $$$p = [1, 2, 3, 4]$$$ 

Sample Inputs:
7
3
3 1 2
4
3 4 1 2
7
4 2 6 7 5 3 1
9
1 6 7 4 9 2 3 8 5
6
1 5 3 4 2 6
10
3 10 5 2 9 6 7 8 1 4
11
1 11 6 4 8 3 7 5 9 10 2

Sample Outputs:
1
2
3
4
3
2
3

Solution (Python):
from sys import stdin, stdout, setrecursionlimit
read = stdin.readline
write = stdout.write
import math

def solve():
    n = int(read())
    p = list(map(int, read().split()))
    pos = [0] * n
    for i in range(n):
        pos[p[i] - 1] = i
    GCD = abs(pos[0])
    for i in range(1, n):
        GCD = math.gcd(GCD, abs(pos[i] - i))
    print(GCD)

def main():
    t = int(input())
    for _ in range(t):
        solve()
main()

Solution (Python):
import os
import sys
import collections
from io import BytesIO, IOBase
from math import ceil, floor, sqrt, sin, cos, tan, factorial, inf, gcd as g
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda : sys.stdin.readline().rstrip('\r\n')
cout = sys.stdout.write
data = collections.Counter
queue = collections.deque
endl = lambda : sys.stdout.write('\n')
ii = lambda : int(input())
fi = lambda : float(input())
si = lambda : input().rstrip()
mi = lambda : map(int, input().split())
mf = lambda : map(float, input().split())
msi = lambda : map(str, input().strip().split(' '))
li = lambda : list(mi())
lf = lambda : list(mf())
ls = lambda : list(msi())
arrsi = lambda : list(si())
set_ii = lambda : set(li())
set_fi = lambda : set(lf())
set_si = lambda : set(input())

def ipow(x, y):
    return int(pow(x, y))

def maps(arr):
    return map(str, arr)

def YES():
    sys.stdout.write('YES\n')

def Yes():
    sys.stdout.write('Yes\n')

def yes():
    sys.stdout.write('yes\n')

def NO():
    sys.stdout.write('NO\n')

def No():
    sys.stdout.write('No\n')

def no():
    sys.stdout.write('no\n')

def NOT():
    sys.stdout.write('NOT\n')

class Solution:

    def __init__(self):
        return

    def solve(self):
        for _ in range(ii()):
            n = ii()
            arr = li()[:n]
            ans = 0
            for i in range(n):
                ans = g(ans, abs(arr[i] - (i + 1)))
            sys.stdout.write(f'{ans}\n')
if __name__ == '__main__':
    Solution().solve()

Solution (Python):
import sys
input = sys.stdin.readline
import math

def readList():
    return list(map(int, input().split()))

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def solve():
    (n, arr, d) = (readInt(), readList(), 0)
    for i in range(n):
        d = math.gcd(d, abs(arr[i] - 1 - i))
    return d
for _ in range(int(input())):
    print(solve())