Rotating Queue

Medium
queue circular-array rotation optimization
Problem Description

Given a circular queue and a sequence of target elements, find the minimum number of rotations needed to bring each target element to the front of the queue in the given order. You can rotate left or right.

Input Format
First line contains n (queue size). Second line contains n space-separated integers (queue elements). Third line contains m (number of targets). Fourth line contains m space-separated target integers.
Output Format
Minimum total rotations needed to bring all targets to front in order.
Constraints
• 1 ≤ n ≤ 1000
• 1 ≤ m ≤ n
• All queue elements are unique
• All targets exist in the queue
• Can rotate left (counter-clockwise) or right (clockwise)
• Choose optimal rotation direction for each target
Sample Input/Output
Input:
5
1 2 3 4 5
3
3 1 4
Output:
6
Explanation

Queue: [1,2,3,4,5]. Target 3: rotate right 2 times → [3,4,5,1,2]. Target 1: rotate right 2 times → [1,2,3,4,5]. Target 4: rotate right 3 times → [4,5,1,2,3]. Total: 2+2+3=7. Wait, let me recalculate optimally...

Solution Hints
105
Points
2000ms
Time Limit
128MB
Memory Limit
Code Editor
Register to Submit
Register to Access Code Editor

Create a free account to solve coding problems and track your progress.

Register Now
Feedback