Ctrl K

Evens to the Left

Easy
A row of boxes stands in a warehouse, each labeled with a number: boxes[i]. A sorting robot has to place every even-numbered box to the left of every odd-numbered one. It works with two grips. The left grip starts at the first box and the right grip at the last. While the left grip is to the left of the right grip, the robot does one of three things: - if the box under the left grip is even, the left grip moves one position to the right; - otherwise, if the box under the right grip is odd, the right grip moves one position to the left; - otherwise the robot swaps the two boxes, and both grips take one step towards each other. Once the grips meet or cross, the robot stops. Return the row of boxes as the robot leaves it. Try to do it without an extra array.
Example 1
boxes=[7, 2, 5, 8, 4] → [4, 2, 8, 5, 7]

The left grip is on 7 (odd) and the right grip is on 4 (even), so they swap: [4, 2, 5, 8, 7]. Next the left grip passes 2 and stops at 5, the right grip stops at 8, and they swap again: [4, 2, 8, 5, 7]. The grips have met, so the robot stops.

Example 2
boxes=[3, 1, 6] → [6, 1, 3]

3 and 6 swap, after which the grips meet: [6, 1, 3].

Example 3
boxes=[10] → [10]
Constraints
  • 1 ≤ len(boxes) ≤ 5000
  • 0 ≤ boxes[i] ≤ 5000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMerge Into the Spare Tail EasyValues in Both Lists EasyShared Values With Repeats EasyCake Slices for Guests EasyParity in Its Place Easy
loading Python…
Input
boxes=[7, 2, 5, 8, 4]
Expected
[4, 2, 8, 5, 7]

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.