Friday, February 13, 2015

Pancake sorting

Given an an unsorted array, sort the given array. You are allowed to do only following operation on array:
rev(arr, i): Reverse arr from 0 to i

Implementation:

void rev(int *arr, int i)
{
     int start = 0;
     while(start < i)
     {
                 swap(arr[start], arr[i]);
                 --i;
                 ++start;
     }
}

int findMaxIndex(int *arr, int n)
{
    int max = 0;
    for(int i = 0; i < n; ++i)
    {
            if(arr[i] > arr[max])
                      max = i;
    }
    return max;
}

void panCakeSort(int *arr, int n)
{
     for(int currSize = n; currSize > 1; --currSize)
     {
             int mi = findMaxIndex(arr, currSize);
             if(mi != currSize - 1)
             {
                   rev(arr, mi);
                   rev(arr, currSize - 1);
             }
     }

}

Thursday, February 5, 2015

Microsoft Question: Nuts and Bolts problem

Question: Given an array of nuts of different sizes and array bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently with the given constraint that comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller.

Solution: Tweak quick sort to achieve it.

Implementation:

int split(int *arr, int low, int high, int pivot)
{
        int j = low;
        for(int i = low; i < high; ++i)
        {
                if(arr[i] < pivot)
                {
                        std::swap(arr[i], arr[j]);
                        ++j;
                }
                else if(arr[i] == pivot)
                {
                        std::swap(arr[i], arr[high]);
                        --i;
                }
        }
        std::swap(arr[j], arr[high]);
        return j;
}

void matchNutsBolts(int *nuts, int *bolts, int low, int high)
{
        if(!nuts || !bolts)
                return;
        if(low < high)
        {
                int pivot = split(nuts, low, high, bolts[high]);
                split(bolts, low, high, nuts[pivot]);
                matchNutsBolts(nuts, bolts, low, pivot - 1);
                matchNutsBolts(nuts, bolts, pivot + 1, high);
        }

}

Complexity: O(nlogn)

Wave sort an array.

Question: Given an unsorted array, sort it in wave form. Wave sorted array looks like as follows:
arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]...

Solution: Traverse all elements at even positions in the array and compare nth element with it's previous element(n-1th), if it is greater than previous, swap previous and current.
Now, again compare the nth element with its next element(n + 1th), if it is greater than next, swap next and current.

Implementation:

void sortWave(int* arr, int len)
{
        if(arr == NULL || len == 0 || len == 1)
                return;
        for(int i = 0; i < len; i+=2)
        {
                if(i>0 && arr[i-1] > arr[i])
                        std::swap(arr[i], arr[i-1]);
                if(i<len-1 && arr[i] < arr[i+1])
                        std::swap(arr[i], arr[i+1]);
        }

}

Complexity: O(n)

Alternative approach: Sort the array and swap adjacent elements. But the complexity of this approach will be O(nlogn)

Saturday, January 31, 2015

Binary Search Tree

The property that makes a Binary Tree into Binary Search Tree is that for every node, X, in the tree, the values of all the keys in the left subtree are smaller than the key value in X and the values of all the keys in the right subtree are larger than or equal to key value in X.

Example of a Binary Search Tree is:


The class to implement Binary Search Tree :

// Node class

template < class Etype >
class TreeNode
{
public:
        Etype element;
        TreeNode* Left;
        TreeNode* Right;
        TreeNode( Etype e = 0, TreeNode* l = NULL, TreeNode* r = NULL) : 
        element ( e), left ( l ), right ( r ) { }
        friend int height ( TreeNode *T);
        friend void inOrderTraversal ( TreeNode *T);
        friend void preOrderTraversal ( TreeNode *T);
        friend void postOrderTraversal ( TreeNode *T);
        friend class BinarySearchTree < Etype >;
};

// Binary Search Tree Class

template<class Etype>
class BinarySearchTree
{
public: 
         BinarySearchTree ( ) : Root ( NULL ) { }
         void insert ( const Etype & x ) {  insert ( x, root ); }
         void remove ( const Etype& x ) { Remove (  x, root ); }
private:
         void insert ( const Etype& x, TreeNode<Etype>* & T );
         void remove ( const Etype& x, TreeNode<Etype>* & T);
         TreeNode *root;
};

Height:

int height ( TreeNode *T)
{
        return ( T ? 1 + Max ( height ( T-> left ), height ( T-> right ) ) : 0 ) ; 
}

Inorder Traversal:

void inOrderTraversal ( TreeNode *T)
{
       if ( T )
       {
                inOrderTraversal ( T-> left );
                cout<< T-> element;
                inOrderTraversal ( T-> right);
        }
}

Preorder Traversal:


void preOrderTraversal ( TreeNode *T)
{
       if ( T )
       {
                cout<< T-> element;
                preOrderTraversal ( T-> left );
                preOrderTraversal ( T-> right);

        }

}

Postorder Traversal:


void postOrderTraversal ( TreeNode *T)
{
       if ( T )
       {
                postOrderTraversal ( T-> left );
                postOrderTraversal ( T-> right);
                cout<< T-> element;
        }

}




Insert:

Following image shows how to insert an element in Binary Search Tree:




Following is the implementation of insert( ) function:

template < class Etype >
void BinarSearchTree< Etype > :: insert ( const Etype & x, TreeNode<Etype> * & T)
{
         if ( T = = NULL )
                 T = new TreeNode<Etype> ( x );
        else
        {
                 if ( x < T -> element )
                          insert ( x, T->left );
                 else if ( x > T-> element)
                          insert ( T-> right )
         }
}


Remove:

Following image shows how to remove an element in Binary Search Tree:



Following is the implementation of remove( ) function:

template < class Etype >
void BinarySearchTree< Etype > :: remove ( const Etype & x, TreeNode<Etype> * & T)
{
        TreeNode<Etype> *tmpCell;
   
        if ( T = = NULL )
                 cout << " Element Not Found ";
        else if ( x < T-> element )
                 remove ( x, T-> left );
        else if ( x > T-> element )
                 remove ( x, T-> right );
        else       // element found
        {
                  if ( T-> left != NULL && T -> right != NULL )
                  {
                            tmpCell = findMin ( T-> right );   // Minimum element
                            T-> element = tmpCell -> element;
                            remove ( T->element, T->right );
                  }
                 else
                 {
                          tmpCell = T;
                          if ( T-> left)
                                     T = T-> left;
                         else if ( T-> right )
                                     T = T-> right;
                         delete tmpCell;
                  }
        }
}

Linked List

Well the first Data Structure that we studied is Linked List and it also provides a way to implement various Advance Data Structures. It can be defined in the following way --

                    "A Linked List is a Data Structure that consists of a sequence of Data Records such that in each record there is a field that contains a reference or link to the next record in the sequence."


Above is the Singly Linked List in which each node has data and a link to the next node in the List. Head node is the start of the List. Next of the last node in the List is NULL.

To implement Singly Linked List, I used following way (C++) --

template <class Etype>
class List
{
     struct Node
     {
            Etype element;
            Node *next;
            Node(Etype E = 0, Node *N = NULL) : element ( E ), next ( N ) { }
      };
    
     Node *head; // start position of head 
     Node *curr;  // To optimize and support many operation, think what we can do with this

   // then various operations, constructors, destructors etc.
};

* In My implementation, head is always in the list even in the case of empty list and head will remain same for lifetime of a list object.


Insert ::
//Insert after curr

template < class Etype  >
void List < Etype > :: insert ( const Etype & data )
{
     curr->next = new Node (data, curr->next );
}

See the following figure for more clarification, it shows insert( 30 ) --


Remove ::
template < class Etype >
int List < Etype > :: remove ( const Etype & data )
{
      if ( Find_Prev( data ) )   // set curr to the node whose next node's element is data
      {
              Node *toDelete = curr->next;
              curr->next = toDelete->next;
              delete toDelete;
               return 1;
      }
      return 0;
}

Following figure shows remove( 8 )



Friday, December 5, 2014

Microsoft Question: Find the pivot element in an array in which elements are first in strictly decreasing and then in strictly increasing order.

Question: 
You are given an array in which elements are first in strictly decreasing and then in strictly increasing order. You need to find the index of pivot element in that array.
For example: arr = {6, 4, 2, 4, 6} then index of pivot element is 2.

Solution:
Modify binary search for this particular problem.

int findPivotInDecIncArray(int *arr, int left, int right)
{
        int mid = left + (right - left) / 2;
        if(left > right)
                return -1;
        if(arr[mid] < arr[mid - 1] && arr[mid] < arr[mid + 1])
                return mid;
        if(arr[mid] <  arr[mid -1] && arr[mid] > arr[mid + 1])
                return findPivotInDecIncArray(arr, mid + 1, right);
        if(arr[mid] > arr[mid - 1] && arr[mid] < arr[mid + 1])
                return findPivotInDecIncArray(arr, left, mid - 1);
        return -1;

Thursday, November 27, 2014

Suffix Array

A suffix array is a sorted array of all the suffixes of a given string. It does the same thing which suffix tree does.
Advantage of suffix array over suffix trees include improved space requirements, simpler linear time construction algorithms and improved cache locality.

Building Suffix Array - Method 1: Make an array of all suffixes and then sort the array.

Implementation:

struct Suffix
{
        int index;
        char* suff;
};

bool compareSuffixes(const Suffix& s1, const Suffix& s2)
{
        return std::strcmp(s1.suff, s2.suff) < 0 ? true : false;
}

int* buildSuffixArray(char* str, int len)
{
        Suffix* suffixes = new Suffix[len];
        for(int i = 0; i < len; ++i)
        {
                suffixes[i].index = i;
                suffixes[i].suff = str + i;
        }
        std::sort(suffixes, suffixes + len, compareSuffixes);
        int *suffixArr = new int[len];
        for(int i = 0; i < len; ++i)
                suffixArr[i] = suffixes[i].index;
        return suffixArr;

}

Time complexity: O(n^2logn)

Building Suffix Array - Method 2: The idea is to use the fact that strings that are to be sorted are suffixes of a single string. The algorithm is mainly based on maintaining the order of the string’s suffixes sorted by their 2^k long prefixes.

Implementation:

struct Suffix
{
        int index;
        int rank[2];
};

bool compareSuffix(const Suffix& s1, const Suffix& s2)
{
        return s1.rank[0] == s2.rank[0] ? (s1.rank[1] < s2.rank[1] ? true : false) : (s1.rank[0] < s2.rank[0] ? true : false);
}

int* buildSuffixArray(char* text, int len)
{
        Suffix* suffixes = new Suffix[len];
        for(int i = 0; i < len; ++i)
        {
                suffixes[i].index = i;
                suffixes[i].rank[0] = text[i] - 'a';
                suffixes[i].rank[1] = ((i+1) < len) ? (text[i+1] - 'a') : -1;
        }

        std::sort(suffixes, suffixes + len, compareSuffix);

        int* index = new int[len];

        for(int k = 4; k < 2*len; k = k*2)
        {
                int rank = 0, prev_rank = suffixes[0].rank[0];
                suffixes[0].rank[0] = rank;
                index[suffixes[0].index] = 0;

                for(int i = 1; i < len; ++i)
                {
                        if(suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1])
                        {
                                prev_rank = suffixes[i].rank[0];
                                suffixes[i].rank[0] = rank;
                        }
                        else
                        {
                                prev_rank = suffixes[i].rank[0];
                                suffixes[i].rank[0] = ++rank;
                        }
                        index[suffixes[i].index] = i;
                }
                for(int i = 0; i < len; ++i)
                {      
                        int nextIndex = suffixes[i].index + k/2;
                        suffixes[i].rank[1] = (nextIndex < len) ? suffixes[index[nextIndex]].rank[0]: -1;
                }

                std::sort(suffixes, suffixes + len, compareSuffix);

        }

        int *suffixArr = new int[len];
        for(int i = 0; i < len; ++i)
                suffixArr[i] = suffixes[i].index;
        return suffixArr;

}


Searching a Pattern: Now we have a sorted array of all the suffixes, we can use binary search to search pattern in the text.

int search(char *text, char *pattern, int *suffArr)
{
        int len = std::strlen(text);
        int patrnLen = std::strlen(pattern);
        int left = 0, right = len - 1;
        while(left <= right)
        {
                int mid = left + (right - left) / 2;
                int result = std::strncmp(pattern, text + suffArr[mid], patrnLen);
                if(result == 0)
                        return suffArr[mid];
                if(result < 0)
                        right = mid - 1;
                else
                        left = mid + 1;
        }
        return -1;

}

Time complexity: O(mlogn)

________________________________________________