Data Structures & AlgorithmsVery hardProduct company OA
What is the minimum number of swaps (of any two elements) needed to sort the permutation [4, 3, 1, 2, 6, 5] into ascending order?
- A. 4
- B. 3
- C. 5
- D. 6
Correct answer: A. 4
Decompose into cycles of 'value v belongs at position v': positions 1 → 4 → 2 → 3 → 1 form a 4-cycle (needs 3 swaps) and 5 ↔ 6 is a 2-cycle (1 swap). Minimum = n − (number of cycles) = 6 − 2 = 4. Adjacent-swap counting (inversions) gives a larger number; '3' sees only the long cycle.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A stack-based decoder expands k[s] into s repeated k times (nesting allowed). What does '2[x3[y]z]q' decode to?
- Adjacent equal pairs are removed repeatedly with a stack until none remain. What is left of 'pqqprrsttsx'?
- An array is split into the MAXIMUM number of contiguous chunks such that sorting each chunk separately and concatenating them gives the…
- An extended Boyer–Moore vote keeps two candidates to find every value occurring MORE than n/3 times, then verifies them with a second…
- Only the head pointer of a singly linked list of n nodes is known (no length is stored). What is the time to reach its middle node?
- An empty deque performs pushfront(1), pushfront(2), pushfront(3) and then popback(). Which value is removed?