CA 08 - Sort 0s, 1s, and 2s

 Sort 0s, 1s and 2s

Given an array arr[] containing only 0s, 1s, and 2s. Sort the array in ascending order.

Note: You need to solve this problem without utilizing the built-in sort function.
Input: arr[] = [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]
Explanation: 0s, 1s and 2s are segregated into ascending order.
Input: arr[] = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
Explanation: 0s, 1s and 2s are segregated into ascending order.
Expected Complexities
Time Complexity: O(n)
Auxiliary Space: O(1)

CODE:
    The initial approach of solving this problem, was using the appropriate sorting method to sort the given array. Given that the expected Auxiliary space as O(1), the array should be sorted in place, thus quick sort is used. 
class Solution:
    def sort012(self,arr):
        def quicksort(arr, first, last):
            if first < last:
                pivot = first
                i = first
                j = last
       
                while i < j:
                    while i < len(arr) and arr[i] <= arr[pivot]:
                        i += 1
                    while arr[j] > arr[pivot]:
                        j -= 1
       
                    if i < j:
                        arr[i], arr[j] = arr[j], arr[i]
       
                arr[pivot], arr[j] = arr[j], arr[pivot]
                quicksort(arr, first, j - 1)
                quicksort(arr, j + 1, last)
               
        quicksort(arr,0,len(arr)-1)

 but here the time complexity for worst case will be O(n^2), thus only 1010 testcases passed and hit a time limit exceed. 

    Approaching this problem with tim sort will make the problem to be solved with the above constraints. The other method is to approach this with Dutch National Flag algorithm, which is pretty much closer to quicksort

class Solution:
    def sort012(self,arr):
        low = 0
        mid = 0
        high = len(arr) - 1
   
        while mid <= high:
            if arr[mid] == 0:
                arr[low], arr[mid] = arr[mid], arr[low]
                low += 1
                mid += 1
            elif arr[mid] == 1:
                mid += 1
            else:
                arr[mid], arr[high] = arr[high], arr[mid]
                high -= 1
   

Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries