The Maximum K to Sort a Permutation coding problem gives you a permutation of integers from 1 to n and asks for the largest value K such that if you look at the last K elements of the array, they form a sorted (ascending) suffix. In other words, find the longest already-sorted suffix in the permutation. This is about identifying the boundary where the "sorted" region of the permutation begins from the right.
Amazon includes this problem to test understanding of permutation structure and suffix scanning. It's deceptively simple but requires careful reasoning about what "already in place" means for a permutation. Candidates who understand that the sorted suffix of a permutation [1..n] must consist of exactly the elements n, n-1, ..., n-k+1 can solve this in O(n) with a single right-to-left scan. Others might overcomplicate it.
The solution uses a single right-to-left linear scan combined with bit tracking. Scan from right to left. Maintain the current minimum value seen so far from the right. The sorted suffix consists of elements where each element equals the count of elements seen so far from the right AND no element larger than the current has appeared out of order to the left. More precisely: the suffix is sorted iff it consists of {n, n-1, ..., n-k+1} in that order. Scan right-to-left and verify this property.
Permutation: [3, 1, 2, 5, 4], n = 5.
Permutation: [1, 2, 3, 4, 5]:
Permutation: [2, 1, 3, 4, 5]:
For the Array Bit Manipulation interview pattern in this context, recognize that permutations have structure you can exploit. The maximum already-sorted suffix is found with a single backward scan checking the ascending condition. Always clarify "sorted ascending or descending" in interviews — this problem's answer can differ drastically based on that assumption.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Triplets with Even XOR Set Bits II | Medium | Solve | |
| Decode XORed Permutation | Medium | Solve | |
| Neighboring Bitwise XOR | Medium | Solve | |
| Minimum Number of Operations to Make Array XOR Equal to K | Medium | Solve | |
| Find The Original Array of Prefix Xor | Medium | Solve |