Showing posts with label binary array. Show all posts
Showing posts with label binary array. Show all posts

Thursday, February 6, 2014

Provide an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0

This updated information has been further expanded upon on my new website. You can find the updated details here: https://k5kc.com/cs/algorithms/set-matrix-zeros-problem/.

Problem

Provide an algorithm such that if an element in an MxN matrix is 0, its entire row and  column is set to 0

Example

Input : 

1 0 1 1 0
0 1 1 1 0
1 1 1 1 1
1 0 1 1 1
1 1 1 1 1

Output :
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 0 0 0
0 0 1 1 0


Solution


Method 1 - Using the extra space and O(n^2) solution
In this approach we can do :
  1. Scan the matrix, store the numbers of rows and columns that will be set to zero to two sets
  2. Iterate through those two sets and set corresponding row and col to zeros.
public static void setZero(int[][] matrix) {
    Set<Integer> rowToClear = new HashSet<Integer>();
    Set<Integer> colToClear = new HashSet<Integer>();
    for(int i = 0; i < matrix.length; ++i) {
        for(int j = 0; j < matrix[0].length; ++j) {
            if(matrix[i][j] == 0) {
                rowToClear.add(i);
                colToClear.add(j);
            }
        }
    }
     
    for(Integer row : rowToClear) {
        for(int j = 0; j < matrix[row].length; ++j) {
            matrix[row][j] = 0;
        }
    }
     
    for(Integer col : colToClear) {
        for(int i = 0; i < matrix.length; ++i) {
            matrix[i][col] = 0;
        }
    }
}

Time complexity - O(M*N) and space complexity O(M+N).

Also, as SET takes more space, rather than using SET, we can use a simple boolean arrays.


boolean[] rowBooleanVectors = new boolean[matrix.length];
boolean[] colBooleanVectors = new boolean[matrix[0].length];
for(int i = 0; i < matrix.length; ++i) {
    for(int j = 0; j < matrix[0].length; ++j) {
        if(matrix[i][j] == 0) {
            rowBooleanVectors[i] = true;
            colBooleanVectors[j] = true;
        }
    }
}
 
for(int i = 0; i < matrix.length; ++i) {
    for(int j = 0; j < matrix[0].length; ++j) {
        if( rowBooleanVectors[i] || colBooleanVectors[j])
            matrix[i][j] = 0;
    }
}

Time complexity - O(M*N) and space complexity O(M+N).

Method 2 -  Space efficient and O(n^2) solution
This method is a space optimized version of above method 1. This method uses the first row and first column of the input matrix in place of the auxiliary arrays rowBooleanArray[] and colBooleanArray[] of method 1.

So what we do is: first take care of first row and column and store the info about these two in two flag variables rowFlag and colFlag. Once we have this info, we can use first row and first column as auxiliary.

We now need 2 passes.

I use 1rst column and first row as markers to know where are rows/cols with only 1's. Then, there are 2 variables l and c to remember if 1rst row/column are all 1's also. So the first pass sets the markers and resets the rest to 0's.
The second pass sets 1 in places where rows and cols where marked to be 1, and resets 1st line/col depending on l and c.

arrays and apply method 1 for submatrix (matrix excluding first row and first column) of size (M-1)*(N-1).
1) Scan the first row and set a variable rowFlag to indicate whether we need to set all 0s in first row or not.
2) Scan the first column and set a variable colFlag to indicate whether we need to set all 0s in first column or not.
3) Use first row and first column as the auxiliary arrays row[] and col[] respectively, consider the matrix as submatrix starting from second row and second column and apply method 1.
4) Finally, using rowFlag and colFlag, update first row and first column if needed.

Here is the code:
N = matrix.length;
M = matrix[0].length;

// pass 1

// 1 rst line/column
int c = 1
for(int i = 0; i < N; ++i) {
    c &= matrix[i][0]
}

l = 1
for(int j = 0; j < M; ++j) {
    l &= matrix[0][i]
}


// other line/cols
// use line1, col1 to keep only those with 1
for(int i = 1; i < N; ++i) {//start iterating with 1
    for(int j = 1; j < M; ++j) {
        if (matrix[i][j] == 0){
            matrix[0][j] = 0
            matrix[i][0] = 0
  }
        else
            matrix[i][j] = 0
 }
}
// pass 2

// if line1 and col1 are ones: it is 1
for(int i = 1; i < N; ++i){
    for(int j = 1; j < M; ++j) {
        if( matrix[i][0] & matrix[0][j] == 1)
            matrix[i][j] = 1
 }
}

// 1rst row and col: reset if 0
if (l == 0){
    for(int i = 0; i < N; ++i) {
        matrix [i][0] = 0
 }
}
if (c == 0){
    for(int j = 1; j < M; ++j) {
        matrix [0][j] = 0
 }
}

print(matrix);


Time Complexity: O(M*N)
Auxiliary Space: O(1)

Reference

Thursday, January 5, 2012

Sorting Array of Three Kinds or The Dutch National Flag Problem OR three color sort

This updated information has been further expanded upon on my new website. You can find the updated details here: https://k5kc.com/cs/algorithms/dutch-national-flag-dnf-problem/.

Question: given an array of three different kinds of value such as array(1, 2, 0, 2, 1) and array(a, b, a, c, b), write an algorithm to sort the array. For example, input array(1, 2, 0, 2, 1) becomes array(0, 1, 1, 2, 2) and input array(a, b, a, c, b) becomes array(a, a, b, b, c). This problem is also called three color sort.

Solution: the Dutch National Flag Algorithm sorts an array of red, blue, and white objects by separating them from each other based on their colors. Hence, we can adopt the algorithm to sort any array of three different kinds of objects / values.

Though at the basics, it is using quicksort algorithm's partition logic.

Let's take a look at the implementation below where we sort an array of three different integers (in cpp) :

Let high be the higher of the 3 elements, and low be the lower of 3 elements , like in (0, 2, 1, 0, 1, 2) low =0, and high=2.

void dutchFlagSort(int inArray[], int arraySize, int high, int low)
{
  if (arraySize == 0)
    return;

  int lower = 0;
  while (inArray[lower] == low && lower < arraySize)
    lower++;

  int upper = arraySize - 1;
  while (inArray[upper] == high && upper >= 0)
    upper--;

  int temp = 0;
  int pivot;
  for (pivot = lower; pivot <= upper;)
  {
    if (inArray[pivot] == low)
    {
      temp = inArray[pivot];
      inArray[pivot] = inArray[lower];
      inArray[lower] = temp;
      pivot++;
      lower++;
    }
    else if (inArray[pivot] == high)
    {
      temp = inArray[pivot];
      inArray[pivot] = inArray[upper];
      inArray[upper] = temp;
      upper--;
    }
    else
      pivot++;
  }
}

Time complexity - O(n)

Explanation: the method above takes in an array of integers, the array's size, and the order of the integers (low and high) as arguments. Notice that low indicates the lowest value in the array and high indicates the highest value in the array. For example, if our array is (1, 2, 3, 1, 2, 3) then the low maybe 1 and high maybe 3. The algorithm uses those indicators to sort the array. We can actually specify low and high as any value in the array if we want to. It only affects how the array places the integers.

The basic strategy behind the method is to partition the array into three regions, low, middle and high. These regions correspond to the three kinds of integers. Low integers whose values equal low, high integers whose values equal high, and the middle integers whose values are anything other than high and low.
That's why we have three different iterators. Any integer before lower is low integer, and any integer after upper is high integer. The pivot iterator traveses the array and swaps high and low integers to their correct places. However, it skips over the middle integers because they are supposed to be in the region between low and high integer regions. Let's do an example to clear things up.
Example: lets Dutch Flag sort this array (0, 2, 1, 0, 1, 2)

  1. low = 0, high = 2
  2. After the first while loop, lower = 1. After the second while loop, upper = 4. Finally, pivot = 1.
     3.  Entering the for loop:

First iteration: array[pivot] = 2 (high), so we swap array[pivot] with array[upper] and decrease upper by 1.

Second iteration: pivot = 1, lower = 1, and upper = 3. Because array[pivot] = 1, we do nothing but increasing pivot by 1.

 Third iteration: pivot = 2, lower = 1, and upper = 3. Again, array[pivot] = 1, we just increase pivot by 1 and move on.



Fourth iteration: pivot = 3, lower = 1, and upper = 3. Since array[pivot] = 0 (low), we swap array[pivot] and array[lower]. Then, we increase both pivot and lower by 1.


Fifth iteration: pivot = 4, lower = 2, and upper = 3. The loop terminates here because pivot is now greater than upper. Here is the final array. Notice how all the 0s, 1s and 2s are separated and sorted in ascending order.




Thanks.

Source

Monday, January 2, 2012

Find the point of transition from 0 to 1 in an infinite sorted array containings only 0 and 1 .

Approach 1(bad): Iterating over the array until we find 1, as the array is sort. In worst case it will go till the last element, and hence this is bad approach.

Approach 2 :  Club binary search approach and array's random access property

Since the array is infinitely increasing i.e. we don't know array size in advance, so we can't directly apply traditional BinarySearch (in which we partition the problem size in half in each iteration, kind of top down approach). We can apply reverse of BinarySearch approach.

We can think of sorted infinite 0 and 1 array as infinite size bit stream on disk with 0 set bits followed by 1 bits.

Approach:
Start with first bit, if it is 1 we are lucky and got the switch index, else if it is 0 check the 2,4,8,16,32,64.... 2^n bits till we get first 1 set bit index say its 'i'. (We are moving by power of 2, rather than 3, 4 etc, because it minimizes the range of data to find the element). Now we have to find between index i/2 to i where the swich happened and this can be done by simple binary search (size of the array to look into is i/2).


Pseudocode:
int GetSwitchIndex()
{
  for(int i=0;;i++)//infinite loop based on break statement
  {
    int arrIndex = power(2,i);
    //lucky case - when first element is lucky
    if(array[arrIndex]==1&&i==0)
      return 0;
    if(array[arrIndex]==1)
      for(int j=arrIndex/2 ; j < arrIndex;j++)
      {
        if(array[j]==1)
          return j;//this is our index
      }
  }//end outer for loop
}

Time Complexity: log(N), N is index at which switch happened.

Monday, April 26, 2010

Sorting binary array - Array containing only 0 and 1 in one pass OR two color sort

Problem

Sort a binary array - array containing 0s and 1s in 1 pass. This is also called two color sort.

Example

Input - Binary unsorted array
A = {0,1,1,0,0,1};

Output - binary sorted array
B = {0,0,0,1,1,1}

Solution

This is similar to quicksort partition algorithm. Though normal sorting takes O(n log n) time, but we have to just partition 0 from 1, and hence it should only take time of partitioning - O(n). Lets see how?

We take low at index 0 of array, high at the of the array. Now we will follow this pseudocode:

Pseudocode:

low = 0; 
high = arr.length - 1;

while (low < high) {
    while (arr[low] == 0) {
        low ++;
    }
    while (arr[high] == 1) {
        high --;
    }
    if (arr[low] > arr[high] ) {
        swap arr[low], arr[high]
    }
}


c implementation
int main()
{
 int arr[] = {1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1};
 int N = 18;
 int *low, *high;

 low = arr;//low points to start of arr
 high = arr + N;//high points to end of arr
 while(low <= high)
 {
  while( (low < high) && (*low == 0) )
   low ++;

  while( (low < high) && (*high== 1) )
   high--;

  if( low < high)
  {
   int temp = *low ;
   *low = *high;
   *high = temp;
   low ++;
   high--;
  }
 }
 for(int i=0;i<N;i++)
  printf("%d ",arr[i]);

 return 0;
}

Time complexity:
Since we have to examine each of n input elements, we can't improve on O(n). Also, since the algorithm requires O(1) memory, you can't improve on that either (there's nothing asymptotically better than O(1)).

But it is still better than comparison sorts like quicksort, merge sort. Though the below pseudocode will look like partition method in quicksort, which was also O(n) algorithm.


Thanks.