Flip a Section of the Parade
Medium · Linked Lists · about 25 min
The floats in a parade are a linked list, front to back. The organiser wants the floats from position left to position right to drive in reverse order, while every other float keeps its place.
Positions start at 1 for the first float and both ends are included. Build the chain from values, reverse that section by relinking nodes, and return the new order as a list.
1 <= left <= right <= len(values).
Example: flip_section([1, 2, 3, 4, 5], 2, 4) → [1, 4, 3, 2, 5]
Hints
- Positions start at 1. Walk left - 1 steps from a dummy node to reach the node just before the section.
- Keep a pointer to the first node of the section. It will end up as the last node of the section.
- Repeat right - left times: unhook the node after that first node and insert it right after the node before the section.
Learn the pattern first: the Linked Lists lesson.
More Linked Lists problems
- Merge Two Delivery Routes (Easy)
- Cancel the K-th Last Booking (Easy)
- Deal From Both Ends (Medium)
- Does the Treasure Hunt Loop? (Medium)
- Add Two Digit Chains (Medium)