user3668129
user3668129

Reputation: 4820

Interview question: Even and odd elements at even and odd positions (keep elements order)

The following question asked in an interview:

Given an array. The task is to arrange the array such that:

- The order of elements must remain same.

Example:

Input: Arr = 2, 4, 6, 8, 10, 1, 3, 5, 7, 9

Output: Arr= 2,1,4,3,6,5,8,7,10,9

Is there a solution with no constant space (i.e O(1)) and in O(N) time ?

Upvotes: 1

Views: 1206

Answers (1)

Ido
Ido

Reputation: 92

If there's n/2 even elements and n/2 odd elements the solution can be very simple, keep an 'even pointer' and 'odd pointer' to the first even empty place in the new array, and the first odd empty place at the new array. than just go over the old array, fill elements at the right position, and don't forget to increase the pointer by 2; If the number of odd elements is diffrenet than the even ones- u can disocover how much even and odd numners are at O(n), so again, the question is quite simple.

Upvotes: 0

Related Questions