Monday, April 25, 2011

BST to Doubly Link List

To solve this problem, First we will analyze the different Cases :-
  Case 1: Leaf Node - left & right child is Null
  Case 2: No Left Subtree   - left Child is Null
  Case 2: No Right Subtree  - right Child is Null
  Case 2: No Left Subtree   - left Child is Null

Tuesday, April 5, 2011

Java 'ArrayList' Pseudocode ....


protected int modCount = 0;




ArrayList(int initialSize)
        IF  initialSize<0  THEN
                       Throw exception "Invalid Size"
       else
             arrayElement= new Object[initialSize];
        
ArrayList() 
  Call ArrayList(defaultSize); // default-size is 10

ArrayList(Collection<? extends E> C)
     arrayElement = C.toArray();
     size = arrayElement.length;
     IF arrayElement.getClass() != Object[].class THEN
                 arrayElement = Arrays.copyOf(arrayElement, size, Object[].class);

ensureCapacity(int newCapacity) 
   modCount++
   oldCapacity  = arrayElement.length;
    IF newCapacity > oldCapacity THEN
         Object[] oldData = arrayElement;
         newCap = (oldCap *3)/2 +1;
         IF newCap < newCapacity THEN
                   newCap=newCapacity;

         ENDIF
    END IF
  arrayElement =Arrays.copyOf(arrayElement, newCap); // My own implementation is at the end.

add(E data)
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = data;



add(int index, E element)
 IF index > size OR  index < 0 THEN
        throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
 ENDIF
 ensureCapacity(size+1);  // Increments modCount!!
 System.arraycopy(elementData, index, elementData, index + 1, size - index); //shifting the right hand side elements by 1.
 elementData[index] = element;
 size++;

RangeCheck(int index)
   IF index >= size THEN
        throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size);

 remove(int index)
  RangeCheck(index)
  modCount++;   // modification count
  Object oldVal = elementData.get(index);
  int numMoved = size - index - 1;


addAll(Collection<? extends E> c)





Object[] a = c.toArray();
length = a.length;
ensureCapacity(size + numNew);
System.arraycopy(a, 0, elementData, size, numNew);
 size = size + numNew;
return numNew != 0;




  ........... to be continued (will add other details later)

Wednesday, March 23, 2011

Advantages of Iterator over forEach

1. Iterator is a design pattern and is a light-weight container.
2. Iterator doesnt need to know what the collection is (i.e. a List or sth else )
3. Using iterator ,we can remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering.
4. Similarly, forEach is not usable for loops where you need to replace elements in a list or array as you traverse it, but Iterator can be used.
5 .Finally, forEach is not usable for loops that must iterate over multiple collections in parallel.

Friday, March 4, 2011

finally Vs finilize


  • finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

  • finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Wednesday, February 23, 2011

Equilibrium index of an Array

Ques :What is "Equilibrium index of an Array" ?
Ans:   Equilibrium index of an Array is an index of Array, such that the sum of elements at lower indices is equal to the sum of elements at higher indices. Value of element at the index is not taken into account.
For example, In the below Array:
Array-7   1    5    -4    3   0
Index        0   1    2   3   4    5   6
So here Index 3 and 6 are equilibrium index.
3 is an equilibrium index, because:     A[0]+A[1]+A[2]  = A[4]+A[5]+A[6]
6 is also an equilibrium index, because: A[0]+A[1]+A[2]+A[3]+A[4]+A[5] = 0

Method-1: Brute-Force method
 This method uses two loops to find the leftSum and rightSum for each index while traversing the array. 
void printEquilibriumIndexes(int arr[], int n){
    for (int i = 0; i < n; ++i){
        int leftSum = 0, rightSum = 0;
        for (int j=0; j<i; j++)
            leftSum += arr[j];
        for(int j=i+1; j<n; j++)
            rightSum += arr[j];       
        if (leftSum == rightSum)
           System.out.println("Index : "+i);
    }
}

Time complexity: O(n^2) 
Method-2: In this more efficient method where we keep track of the sum of all the elements in the Array and hence do not calculate the leftSum and rightSum from scratch but just update them based on the current index.
/**
 * This function will print all the Equilibrium Indexes in array arr
 */
void printEquilibriumIndexes(int arr[], int n){
    int rightSum = 0;   // Sum of all the Elements to the right of an Element
    int leftSum = 0; // Sum of all the Elements to the left of an Element

    for (int i=0; i<n; ++i)
        rightSum += arr[i];

    for (int i = 0; i < n; ++i){
        rightSum -= arr[i];
        if (leftSum == rightSum)
           System.out.println("Index: "+i);

        leftSum += arr[i];
    }
}

Tuesday, February 22, 2011

Rotate an array by K Position left.

We have to rotate an a sorted Array by k points. For example, if k=3, for the below array
A ={2, 4, 7, 9, 10, 12, 28, 30, 34, 50}
then after rotation the final array will be A ={9, 10, 12, 28, 30, 34, 50, 2, 4, 7}.

Solution:
 Method 1: Brute Force method : Rotate by one position at a time
/** Rotate the Array k places by rotating by one position at a time
 */
void rotate(int *arr, int n, int k){
    for (int cnt = 0; cnt < k; cnt++){
        int temp = arr[0];
        int i=0;
        for (; i < n-1; i++)
            arr[i] = arr[i+1];
        arr[i] = temp;
    }
}

Method 1: Swapping & Reversing the Sub-array method

For i= 0 to k-1
swap a[i], a[n-i-1]
// arr: 50, 34, 20,
9, 10, 12, 18, 7, 4, 2
Reverse elements from k to n-k-1.        // arr: 50, 34, 20, 18, 12, 10, 9, 7, 4, 2

Reverse elements from 0 to n-k-1.       // arr: 9, 10, 12, 18, 20, 34, 50, 7, 4, 2
Reverse elements from n-k to n-1.       // arr: 9, 10, 12, 18, 20, 34, 50, 2, 4, 7




/**
 * Function to rotate the array arr of size n by k positions
 * We will examine the state of array after each step for following input values
 * arr: 2, 4, 7, 9, 10, 12, 18, 20, 34, 50
 *   n: 10
 *   k: 3
 *
 * Expected Output: 9, 10, 12, 18, 20, 34, 50, 2, 4, 7
 */
void rotate(int *arr, int n, int k){
 for(int i=0; i < k; i++)
        swap(arr,i,n-i-1);
    // arr: 50, 34, 20, 9, 10, 12, 18, 7, 4, 2
    reverse(arr,k,n-k-1);
    // arr: 50, 34, 20, 18, 12, 10, 9, 7, 4, 2
    reverse(arr,0,n-k-1);
    // arr: 9, 10, 12, 18, 20, 34, 50, 7, 4, 2
    reverse(arr,n-k, n-1);
    // arr: 9, 10, 12, 18, 20, 34, 50, 2, 4, 7
}
/**
 * Swap two elements at position a & b of Array arr.
 */
void swap(int *arr, int a, int b){
    int t = arr[a];
    arr[a] = arr[b];
    arr[b] = t;
}

/**
 * Reverse all the elements of array arr between positions a & b (both inclusive)
 */
void reverse(int *arr, int a, int b){
    for(int i=0; i<=(b-a)/2; i++)
        swap(arr, a+i, b-i);
}

/**
 * Function to print the array
 */
void printArray(int arr[], int size){
    for(int i = 0; i < size; i++)
        cout<<arr[i]<<" ";
}

Method-4: Using an Auxiliary Array
If we use a separate array to store the result then things becomes easy. I am sure you can write the function for this one :)
void rotateUsingExtaArray(int arr[], int n, int k){
    for(int i=0; i < n; i++)
        b[i] = arr[(i+k)%n];
}

Time complexity: O(n).   Space Complexity: O(n)


Method-6: Juggling Algorithm
In this method, the array is divided into M sets, where M = GCD(n, k), and rotate the corresponding elements in each set: For Example: If we want to rotate the below array by 2 points

1 2 3 4 5 6

M = GCD(6, 2) = 2;

First Set Moves:








3 2  5 4  1 6

Second Set Moves:
3 4 5 6 1 2
/**
 * Rotate the array arr of size n by k places
 */
void rotateJuggling(int *arr, int n, int k){

    int i, j, p, temp;
    for (i = 0; i < gcd(k, n); i++){

        // moving i'th
        temp = arr[i];
        j = i;
        while(1){

            p = j + k;
            if (p >= n)
                p = p - n;
            if (p == i)
                break;
            arr[j] = arr[p];
            j = p;
        }
        arr[j] = temp;
    }
}


Time complexity:     O(n).
Space Complexity:   O(1).

Sunday, February 20, 2011

Find the N-th largest element in the array of positive integers.. unsorted array

Sort the array in decreasing order then loop through the sorted array while counting unique elements then stop when the count is equal to (n). In the code below we will assume the array is already sorted. You can refer to the following post for more information about merge sort which you can use to efficiently sort the array in O(nlogn) time complexity.

public int NthMaxumum(int[] A){
   int s = A.length;
   //Let us assume we need to find the 3d. maximum which is 4
   int n = 3;
   //Counter
   int c = 1;
   //Initialize n(th) max
   int nmax = A[0];
   //Loop in the array while the count is less than (n)
   for (int i = 0; i < s && c < n; i++){
  //If the current array element is different from the current n(th) max increment the counter
 if (A[i] != nmax) c++;
 //Update n(th) max
 nmax = A[i];
}