The cars that stay put
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- lists
- sorting
- division
Problem
The Dry Valley rail yard has one rule: freight cars, marked with an even number, are locked to the track and never move. Passenger cars, marked with an odd number, can move, and the yardmaster wants them in order from smallest to largest, in the spots they already take up.
Write a function that takes a list of integers (it may be empty and may have negatives) and returns a new list: every even number stays where it is, and the odd numbers, sorted from smallest to largest, fill the odd spots from left to right. 0 is even, and a negative like -3 is odd.
With [5, 8, 3, 2, 1]: the 8 and the 2 stay put; the odd 5, 3 and 1 are placed as 1, 3 and 5. You get [1, 8, 3, 2, 5].
Examples
The example
[5, 8, 3, 2, 1] → [1, 8, 3, 2, 5]
All freight
[4, 2, 0, 6] → [4, 2, 0, 6]
All passenger
[7, 3, 9, 1] → [1, 3, 7, 9]
Repeated odd numbers
[3, 6, 3, 1] → [1, 6, 3, 3]
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def sort_cars(cars):
passJavaScript
function sortCars(cars) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.