Saturday, October 1, 2011

[Amazon] Sort array which contains only 0, 1 or 2 in O(n)

Problem: Sort an array which contains only 0, 1 or 2. The time complexity should not be more than O(n).

Example:
Input: arr = [0, 1, 2, 0, 1, 1, 2]
Output: [0, 0, 1, 1, 1, 2, 2]


Approach: We will use three pointer approach here.


Implementation in C#:

    public void SortColors(int[] nums)
    {
        int length = nums?.Length ?? 0;
        if (length <= 1)
        {
            return;
        }
        int low = 0;
        int high = length - 1;
        for (int mid = 0; mid <= high;)
        {
            Console.WriteLine($"{mid}: {nums[mid]}");
            switch(nums[mid])
            {
                case 0: this.Swap(nums, low++, mid++);
                    break;
                case 1: mid++;
                    break;
                case 2: this.Swap(nums, mid, high--);
                    break;
            }
        }
    }

    private void Swap(int[] nums, int i, int j)
    {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }


Complexity: O(n)

No comments:

Post a Comment