This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.
Question:
You are given a structure which holds employee details with two elements, int department and string name.
struct Employee { string Name; int Dept; }
You are given details of N Employees, among which N/2 employees have Dept == 0 and N/2 employees have Dept == 1, arranged in some arbitrary order. You need to sort the employee details based on their Dept value and it should be stable i.e., the order of 1s and 0s in the original record should be maintained.
For example, given the following sample data:
Name Dept X1 0 X2 1 X3 0 X4 1 X5 0
after sorting the result should be:
Name Dept X2 1 X4 1 X1 0 X3 0 X5 0
The algorithm should be stable and the time complexity should be O(N), with constant space for additional variables (which means sorting should be done in-place).
Okey, here is my approach.
e.g a[] = { 1,0,0,0,1,1,1,0,0,1};
Pseudocode:
count1 = 0andcount2 = (n/2)+1Traverse through the array,
At the end of the traversal, you have array filled with numbers 0 to n-1 like:
Now the problem comes to sort the above resultant array, this can be done in O(N) as below:
Note: j loop runs only twice irrespective on ‘n’ and has constant complexity. The order of this whole loop is 2*n = O(n).
After the array is sorted, Again traverse through the array and set elements
arr[0]toarr[n/2]to'1'andarr[(n/2)+1]toarr[n]as'0'.Space complexity is constant and time complexity is O(step2) + O(step4) + O(step5) = n + 2n +n = 4*n = O(n).