DEV Community

Tanishka V
Tanishka V

Posted on

ASSIGNMENT 8

๐Ÿ“Œ Problem Statement

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

โš ๏ธ Constraint:
You cannot use built-in sorting functions.


๐Ÿงช Examples

Example 1

Input:  [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]
Enter fullscreen mode Exit fullscreen mode

Example 2

Input:  [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]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Optimal Approach: Dutch National Flag Algorithm

This problem can be solved efficiently using the Dutch National Flag Algorithm, which works in:

  • โฑ Time Complexity: O(n) (single pass)
  • ๐Ÿ“ฆ Space Complexity: O(1) (no extra space)

๐Ÿง  Idea Behind the Algorithm

We divide the array into three regions:

  • 0s region โ†’ beginning
  • 1s region โ†’ middle
  • 2s region โ†’ end

We use three pointers:

  • low โ†’ position for next 0
  • mid โ†’ current element
  • high โ†’ position for next 2

๐Ÿ”„ Algorithm Steps

  1. Initialize:
   low = 0, mid = 0, high = n - 1
Enter fullscreen mode Exit fullscreen mode
  1. Traverse while mid <= high:
  • If arr[mid] == 0: โ†’ Swap arr[low] and arr[mid], increment both low and mid
  • If arr[mid] == 1: โ†’ Just move mid
  • If arr[mid] == 2: โ†’ Swap arr[mid] and arr[high], decrement high

๐Ÿ’ป Python Implementation

def sort_array(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] == 2
            arr[mid], arr[high] = arr[high], arr[mid]
            high -= 1

    return arr


# Example usage
arr = [0, 1, 2, 0, 1, 2]
print(sort_array(arr))
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Output

[0, 0, 1, 1, 2, 2]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Dry Run (Quick Insight)

For input:

[0, 1, 2, 0, 1, 2]
Enter fullscreen mode Exit fullscreen mode
  • 0 โ†’ moved to front
  • 2 โ†’ moved to end
  • 1 โ†’ stays in middle

  • No need for sorting functions โŒ
  • Solved in one pass โœ…
  • Uses constant space โœ…
  • Very common in coding interviews ๐Ÿ”ฅ

Top comments (0)