Solution

Approach 1: Two Pass

Intuition and Algorithm

Read all the even integers and put them into places ans, ans, ans, and so on.

Then, read all the odd integers and put them into places ans, ans, ans, etc.

Complexity Analysis

• Time Complexity: , where is the length of A.

• Space Complexity: .

Intuition

We are motivated (perhaps by the interviewer) to pursue a solution where we modify the original array A in place.

First, it is enough to put all even elements in the correct place, since all odd elements will be in the correct place too. So let's only focus on A, A, A, ...

Ideally, we would like to have some partition where everything to the left is already correct, and everything to the right is undecided.

Indeed, this idea works if we separate it into two slices even = A, A, A, ... and odd = A, A, A, .... Our invariant will be that everything less than i in the even slice is correct, and everything less than j in the odd slice is correct.

Algorithm

For each even i, let's make A[i] even. To do it, we will draft an element from the odd slice. We pass j through the odd slice until we find an even element, then swap. Our invariant is maintained, so the algorithm is correct.

Complexity Analysis

• Time Complexity: , where is the length of A.

• Space Complexity: .

Analysis written by: @awice.