Visa OA question Array
Anonymous User
414

🃏 Problem: Sort the Deck with One Shuffle Move

You are given a deck of n cards numbered from 1 to n, arranged in some arbitrary order.

In one operation, you can take the top k cards (where 0 ≤ k < n) from the deck and move them to the bottom, keeping their relative order the same.

Your task is to determine the minimum number k such that after performing this operation exactly once, the deck becomes sorted in ascending order (i.e., [1, 2, 3, ..., n]).

If it is not possible to sort the deck using exactly one such shuffle, return -1.

🔹 Example 1

Input:
deck = [3, 4, 5, 1, 2]

Output:
3

Explanation:
If we move the top 3 cards [3, 4, 5] to the bottom,
the deck becomes [1, 2, 3, 4, 5], which is sorted.
Hence, the answer is 3.

🔹 Example 2

Input:
deck = [1, 2, 3, 4, 5]

Output:
0

Explanation:
The deck is already sorted, so no moves are needed.

🔹 Example 3

Input:
deck = [3, 2, 1]

Output:
-1

Explanation:
No single shuffle operation can sort this deck.

🔹 Constraints

1 ≤ n ≤ 10⁵

deck contains a permutation of integers from 1 to n.

Comments (6)