Saturday, September 3, 2011

Atoi


int atoi( char* pStr ) {  
int iRetVal = 0;    
if (pStr)  
{    
 while ( *pStr && *pStr <= '9' && *pStr >= '0' )     
 {      
  iRetVal = (iRetVal * 10) + (*pStr - '0');      
  pStr++;    
 }  
}   
return iRetVal; 
} 


If we allow -ve and + signs we need to take care of them as well in the out put and check for invalid characters.

Check if array elements are consecutive


The idea is to check for following two conditions. If following two conditions are true, then return true.

1) max – min + 1 = n where max is the maximum element in array, min is minimum element in array 
                               and n is the number of elements in array.
2) All elements are distinct.

To check if all elements are distinct, we can create a visited[] array of size n. 
We can map the ith element of input array arr[] to visited array by using arr[i] – min as index in visited[].

Majority Element


A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).

Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows:

       I/P : 3 3 4 2 4 4 2 4 4
       O/P : 4 

       I/P : 3 3 4 2 4 4 2 4
       O/P : NONE

Using Moore’s Voting Algorithm:

This is a two step process.
1. Get an element occurring most of the time in the array. This phase will make sure that if there is a majority element then it will return that only.
2. Check if the element obtained from above step is majority element.

1. Finding a Candidate:
           The algorithm for first phase that works in O(n) is known as Moore’s Voting Algorithm. Basic idea of the algorithm is if we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element.

    findCandidate(a[], size)
        1.  Initialize index and count of majority element
            maj_index = 0, count = 1
        2.  Loop for i = 1 to size – 1
            (a)If a[maj_index] == a[i]
                count++
           (b)Else
               count--;
           (c)If count == 0
              maj_index = i;
             count = 1
       3.  Return a[maj_index]

Above algorithm loops through each element and maintains a count of a[maj_index], If next element is same then increments the count,
if next element is not same then decrements the count, and if the count reaches 0 then changes the maj_index to the current element and sets count to 1.

First Phase algorithm gives us a candidate element. In second phase we need to check if the candidate is really a majority element.
Second phase is simple and can be easily done in O(n). We just need to check if count of the candidate element is greater than n/2.

Example : A[] = 2, 2, 3, 5, 2, 2, 6 , answer : 2.

 2. Check if the element obtained in step 1 is majority

      printMajority (a[], size)
         1.  Find the candidate for majority
         2.  If candidate is majority. i.e., appears more than n/2 times.
              Print the candidate
        3.  Else
              Print "NONE"

Searching a pivot in the sorted rotated array

Implement the following function, FindSortedArrayRotation, which takes as its input an array of unique integers that has been sorted in ascending order, then rotated by an unknown amount X where 0 <= X <= (arrayLength – 1). An array rotation by amount X moves every element array[i] to array[(i + X) % arrayLength]. FindSortedArrayRotation discovers and returns X by examining the array.

Solution:
This time you have to search for the rotation pivot. There is a subtle observation. This problem is in fact the same as finding the minimum element’s index. If the middle element is greater than the right most element, then the pivot must be to the right; if it is not, the pivot must be to the left.

1
2
3
4
5
6
7
8
9
10
11
12
13
int FindSortedArrayRotation(int A[], int N) {
  int L = 0;
  int R = N - 1;
 
  while (A[L] > A[R]) {
    int M = L + (R - L) / 2;
    if (A[M] > A[R])
      L = M + 1;
    else
      R = M;
  }
  return L;
}

Some Test Cases:

{ 1 }
return 0

{ 1, 2 }
return 0

{ 2, 1 }
return 1

{ 1, 2, 3 }
return 0

{ 3, 1, 2 }
return 1

{ 2, 3, 1 }
return 2

{ 1, 2, 3, 4, 5 }
return 0

{ 2, 3, 4, 5, 1 }
return 4

{ 3, 4, 5, 1, 2 }
return 3

{ 4, 5, 1, 2, 3 }
return 2

{ 5, 1, 2, 3, 4 }
return 1

{ 1, 2, 3, 4, 5, 6 }
return 0

{ 2, 3, 4, 5, 6, 1 }
return 5

{ 3, 4, 5, 6, 1, 2 }
return 4

{ 4, 5, 6, 1, 2, 3 }
return 3

{ 5, 6, 1, 2, 3, 4 }
return 2

{ 6, 1, 2, 3, 4, 5 }
return 1

{ 6, 8, 1, 2, 4, 5 }
return 2

Searching an Element in a Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). How do you find an element in the rotated array efficiently?

At first look, we know that we can do a linear search in O(n) time. But linear search does not need the elements to be sorted in any way.

First, we know that it is a sorted array that’s been rotated. Although we do not know where the rotation pivot is, there is a property we can take advantage of. Here, we make an observation that a rotated array can be classified as two sub-array that is sorted (i.e., 4 5 6 7 0 1 2 consists of two sub-arrays 4 5 6 7 and 0 1 2.

Do not jump to conclusion that we need to first find the location of the pivot and then do binary search on both sub-arrays. Although this can be done in O(lg n) time, this is not necessary and is more complicated.

In fact, we don’t need to know where the pivot is. Look at the middle element (7). Compare it with the left most (4) and right most element (2). The left most element (4) is less than (7). This gives us valuable information — All elements in the bottom half must be in strictly increasing order. Therefore, if the key we are looking for is between 4 and 7, we eliminate the upper half; if not, we eliminate the bottom half.

When left index is greater than right index, we have to stop searching as the key we are finding is not in the array.

Since we reduce the search space by half each time, the complexity must be in the order of O(lg n). It is similar to binary search but is somehow modified for this problem. In fact, this is more general than binary search, as it works for both rotated and non-rotated arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int rotated_binary_search(int A[], int N, int key) {
  int L = 0;
  int R = N - 1;
 
  while (L <= R) {
    // Avoid overflow, same as M=(L+R)/2
    int M = L + ((R - L) / 2);
    if (A[M] == key) return M;
 
    // the bottom half is sorted
    if (A[L] <= A[M]) {
      if (A[L] <= key && key < A[M])
        R = M - 1;
      else
        L = M + 1;
    }
    // the upper half is sorted
    else {
      if (A[M] < key && key <= A[R])
        L = M + 1;
      else
        R = M - 1;
    }
  }
  return -1;
}

Find Minimum Spanning Tree in a weighted graph

Prim's Algorithm : Click Here

Kruskal's Algorithm : Click Here

Segregate even and odd nodes in a Linked List


Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear 
before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.

Method 1 
The idea is to get pointer to the last node of list. And then traverse the list starting from the head node and 
move the odd valued nodes from their current position to end of the list.

Algorithm: 

   1) Get pointer to the last node.
   2) Move all the odd nodes to the end.
        a) Consider all odd nodes before the first even node and move them to end.
        b) Change the head pointer to point to the first even node.
        c) Consider all odd nodes after the first even node and move them to the end.