Trains the technique from
LeetCode 2074Reverse Nodes in Even Length GroupsThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A shunting yard holds one chain of coupled railcars. The chain reaches you as a list cars of car weights in order from the locomotive end to the tail, so cars[0] is the car coupled straight behind the locomotive and each following entry is the next car back.
Starting at the locomotive end, the chain is carved into consecutive groups. The first group takes 1 car, the second takes 2 cars, the third takes 3, and each group after that takes one more car than the group before it. The final group takes whatever cars are still left, which can be fewer than its turn calls for.
Every group holding an even number of cars has its cars put back in the opposite order, within the same stretch of the chain. Groups holding an odd number of cars are left as they are. Group boundaries never move, and no car ever leaves the group it landed in.
Return the weights of the chain in the resulting order. Do the rearranging by uncoupling and recoupling cars inside the chain rather than by building a fresh chain alongside it, and use only a constant amount of extra space beyond the chain itself.
Example 1
The groups hold 1, 2, 3 and 1 cars, so only the pair 7 and 19 changes places; the group of three and the lone car at the tail stay as they were.
Example 2
The groups hold 1, 2 and 2 cars, because only two cars are left for the third group; both pairs change places.
Example 3
The groups hold 1, 2, 3, 4 and 2 cars; the groups of two and of four are put back in the opposite order and the groups of one and three are untouched.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def flip_even_groups(cars: list[int]) -> list[int]:public int[] flipEvenGroups(int[] cars)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.