Library Shelf Merge Log
The city archive juggles dozens of narrow bookcases that periodically run out of space. To keep the catalog tidy, librarians follow a printed schedule that merges sections: pick two shelves, take their current books, and produce a single combined shelf sorted by spine number. After the merge, the old shelves are cleared and the new shelf appears in their place, preserving alphabetical order of call numbers. When the schedule ends, the head librarian wants a report showing the final arrangement of every shelf from left to right.
You are given an array shelves where each entry is a list of spine numbers already in non-decreasing order, and a list merges where each command is [left, right]. For each command, create a new shelf by merging the two specified shelves like a standard merge step in merge sort (stable and ascending). Replace shelves[left] with the merged shelf, then remove shelves[right]. Indices in merges always reference existing shelves at the time of execution, and left < right. Continue processing commands sequentially. Return the final array of shelves.
If shelves[right] becomes empty, treat it as an empty list ready for removal. You do not need to log intermediate merges; only return the final shelf configuration.
Example 1:
Input: shelves = [[2,4],[1,3,5],[6]], merges = [[0,1],[0,1]]
Output: [[[1,2,3,4,5,6]]]
Explanation: First merge shelves 0 and 1 into [1,2,3,4,5], then merge that shelf with the final shelf [6].
Example 2:
Input: shelves = [[10],[8,12],[9]], merges = [[1,2]]
Output: [[10],[8,9,12]]
Explanation: Only shelf index 1 and 2 are merged; shelf 0 remains unchanged.
Example 3:
Input: shelves = [[1,4],[2,3]], merges = []
Output: [[1,4],[2,3]]
Explanation: With no merges scheduled, the layout stays intact.
Related Problems
No related problems found
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
