Algos && Data structures problem -2

Question (Leet code)

Sort the array by parity int[] nums={2,3,4,5,6};  to {2,4,6,3,5} //might be sorted or not sorted by O(n) time complexity and No extra space complexity.

Answer

So basically we are given the Array which can be sorted not we don't know we need to arrange the elements as from even to odd like stated in question so how can we do that?

Basically the first thing that we can do it the brute Force method like check by the entire array taking elements one by one and checking the odd and the evens and can take some extra array to add first the even ones and after that the odd ones but here we are said that we need an optimal soln by no extra time and space so lets do that

int[] nums={2,3,4,5,6}; //{2,4,6,3,5} //might be sorted or not sorted
        int i=0;
        
       for (int j=0;j<nums.length;j++) {
           if(nums[j]%2==0) {// if this matches so the num i even
               int temp=nums[i];
               nums[i]=nums[j];
               nums[j]=temp;
               i=i+1;
           }
        
    }
       for (int k : nums) {
        System.out.println(k);
    }

the above is the code for its tested well and now lets dry run it

So as we see that we need to take one variable that is i and we initialized it to 0 that is index 0

and there is a normal for loop like the loop will run j times in that loop we need to perform the operation of checking the even number

lets move further now say 2 comes i.e first element of index 0 yes its even so we store 2 in the temp

i.e temp=2 

then we store 2 in the nums[0]
and then we store temps value to nums[j] that is nums[0]=2

if we have even number then only we need to increment the value of i

So now i=1 and j =1

now 3 is the input to the condition.

so now will not enter into the condition so array is like [2,3,4,5,6]

leaving i=1 and now j=2 so the next value is 4 comes inside the condition

temp=a[1] i.e 3
a[1]=a[2] i.e 4
and a[2] is temp that is 3

so the array now is [2,4,3,5,6] like wise we can dry run it.

Hope you like the solution can suggest me if any in the comments below.

Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another