Snack Line Rotation with deque()
A group of students is lining up for the snack counter. The student at the very front is asked to step aside for a moment, so everyone else moves forward, and that first student goes to the back of the line.
Your task is to return the new order of the line after one such rotation. In other words, move the first element of the list to the end and keep the order of the remaining students unchanged.
For example, if the line is ["Ayu", "Bima", "Cici"], the new order should be ["Bima", "Cici", "Ayu"]. If the list is empty or has only one student, the result should stay the same because rotating does not change anything meaningful in those cases.
This is a queue-style operation. The front item is removed first and then added at the back, which makes it a nice introduction to Python's deque structure from the collections module.
Example Input & Output
A one-student line looks the same after rotation.
The first student moves to the back after one rotation.
An empty line stays empty.
Algorithm Flow

Solution Approach
This problem behaves like a queue. One item leaves the front, then immediately re-enters at the back. Python's deque is designed for exactly that kind of operation, especially when you want efficient work at both ends.
One compact answer is to turn the list into a deque, rotate it once to the left, and then convert it back into a list:
The call rotate(-1) shifts every item one step toward the front and wraps the old front element to the back. That matches the line-change rule perfectly.
If you want to make the queue behavior more explicit, you can use popleft() and append() instead. Remove the first student, then append that same student to the right side. You just need a small check first so the code does not try to remove an item from an empty deque.
Even though this challenge could also be solved with list slicing, the data-structure lesson here is about using the right tool for queue-like behavior. A deque makes the intent easy to read: front removal and back insertion are the main operations.
The runtime is O(n) overall because the final conversion back to a list touches every element, and the extra space is also O(n) for the deque copy of the input.
Best Answers
from collections import deque
def rotate_snack_line(students):
line = deque(students)
if not line:
return []
line.append(line.popleft())
return list(line)Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
