Interview Questions/Coding/Maximum Sort Step

Maximum Sort Step

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Maximum Sort Step

Given a permutation p, choose a positive integer k. You may swap elements only if their positions differ by exactly k. Return the maximum k that can sort the permutation. If the permutation is already sorted, return 0.

Examples

Example 1
Input:
p = [3, 4, 1, 2]
Output:
2

Explanation: Swaps between positions that differ by 2 can sort the permutation.

Approach hint

Element p[i] must eventually move to position p[i].

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp