#K60522. Minimum Adjacent Swaps to Bring Target to Front
Minimum Adjacent Swaps to Bring Target to Front
Minimum Adjacent Swaps to Bring Target to Front
Given T test cases, each consisting of a list of words and a target word, your task is to determine the minimum number of adjacent swaps required to bring the target word to the beginning of the list.
An adjacent swap allows you to swap two consecutive words. If the target word is not present in the list, print -1.
Note: The number of swaps needed is exactly the index of the target word in the list (0-indexed), because each swap moves the word one position closer to the start.
inputFormat
The input begins with an integer T
denoting the number of test cases.
For each test case, the first line contains an integer n
and a string target
separated by a space. The second line contains n
space-separated words.
For example:
5 6 date apple banana cherry date fig grape 4 grapefruit lemon orange pear watermelon 1 apple apple 3 mango kiwi mango papaya 5 target a b c d target
outputFormat
For each test case, output a single integer on a separate line representing the minimum number of adjacent swaps required to move the target word to the front of the list. If the target word is not found, output -1
.
3 -1 0 1 4## sample
5
6 date
apple banana cherry date fig grape
4 grapefruit
lemon orange pear watermelon
1 apple
apple
3 mango
kiwi mango papaya
5 target
a b c d target
3
-1
0
1
4
</p>