Saturday 15 September 2012

Arithmetic With Precision

                                Arithmetic With Precision

Have you ever used C/C++. Tried to perform simple arithmetic operations on real numbers of considerably longer length. If yes, then you must have known that none of these languages provide you the answers with perfect precision. Even the same may be the case with java. So, here is the task. Just take two numbers (of course real), try to perform any arithmetic operation (+,-,/,*) and then try to simply print it on the console, but with infinite precision.


    987432189374581923.123276453
+ 199283777167383992.383477628
____________________________________________

Take care, answer should look like one of operands, without any exponential notation.

Sunday 9 September 2012

Stack with min operation in O(1)



Stack with push, pop and min,  all in O(1)

 

Problem

How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element so far? Push, pop and min should all operate in O(1) time.

Trivia

This is a pretty standard question now. The question has been asked in many interviews in past and will be asked in many interviews in future.

Approach

There can be many ways to approach this problem:
1) One way is to introduce another variable min in data structure 'Node' which keep tracks of min element so far in the stack.

So the new data structure for stack would look something like:
struct Stack_Node {
   int val;
   int min;
   struct Node *next;
}  Node;

Now when you push the element into stack, its local min variable is calculated and updated.
new->min = Minimum(value, top->min);
And while doing the pop operation, the min is already up to date in stack so far. So one can simply delete the top node.

There is just one problem with this approach - if it is a large stack, we will waste a lot of space keeping track of min element. So if space isn't the issue, like it isn't now a days :), this method is perfectly fine. Otherwise we can do better too.

2) The other way to solve a problem is using additional stack which keep tracks of min so far.

So the new push and pop operations for stack would be like:
stack<int> s2;
push {
    if (value <= s2.top())  s2.push(value)
    s1.push(value)
}
pop {
    value = s1.pop()
    if(value=s2.top()) s2.pop()
}
min {
    if(!s2.isEmpty()) s2.top()
}


Time Complexity

Push - O(1)
Pop - O(1)
Min - O(1)


There is a similar question in which you have to design a stack which, in addition to push and pop, also has a function max which returns the maximum element so far.


Sunday 2 September 2012

Tower Of Hanoi - Non-recursive Approach

Tower Of Hanoi

                                                             --  shaikzakir3149@gmail.com


Hello all, this is my first post. Hope you find it useful ...


Implement non-recursive Towers of Hanoi. Given the number n of disks as input, maintain appropriate pegs/rods to simulate the movement of the disks among the three pegs: Source, Auxilary & Destination.
Output the sequence of moves of the disks. Following is an example of the output expected by your program.

No. of disks: 3
Sequence of Moves
1. Source → Destination
2. Source → Auxilary
3. Destination → Auxilary
4. Source → Destination
5. Auxilary → Source
6. Auxilary → Destination
7. Source → Destination

Note: Remember that towers of hanoi can be solved in (2^n - 1) at the best for given n disks.



Algorithm:

While size of Destination is less not equal to n
do
{
If num of disks is even then

       Make legal move between Source and Auxilary
       Make the legal move between pegs Source and Destination

else

        Make the legal move between pegs Source and Destination  
        Make the legal move between pegs Source and Auxilary

endif

Make legal move between pegs Auxilary and Destination



}
end While


Note that a legal move is one which abides by the rules of the puzzle. Only a smaller disk can be moved onto a larger disk.

Running Time Complexity :

 The runtime complexity of this algorithm is O((2^n - 1)/3) which is equivalent to O(2^n). Clearly the stack operations (push, pop and peek) have a runtime equal to O(1).

The code is given in Java.


Source Code :


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//package tower.of.hanoi;
import java.io.*;
import java.util.Stack;
import java.util.EmptyStackException;
/**
 *
 * @author Shaik
 */
public class TowerOfHanoi {

    
    public static int legalMove(Stack A, Stack B)
    {
        int a,b;
        try {
        a = Integer.parseInt(A.peek().toString());
        }
        catch(EmptyStackException e){
        a = 0;    
        }
        try {
            b = Integer.parseInt(B.peek().toString());
        }
        catch(EmptyStackException e){
        b = 0;    
        }
        if(a==b) return 0;
        if(a == 0)             // If peg A is empty, then pop from B and push the disk onto A
    {
        A.push(B.pop());
            return 2;           // Return 2 as move occurred from B to A
    }
        else if(b == 0)        // If peg B is empty, then pop from A and push the disk onto B
        {
        B.push(A.pop());
        return 1;           // Return 1 since move occurred from A to B
    }
        
        if(a<b)
        {
        B.push(A.pop());
        return 1;               // Return 1 since move occurred from A to B
        }
        else if(a > b)            // value of top disk of peg A is greater than the value of topmost disk of peg B
        {
        A.push(B.pop());
        return 2;               // Return 2 since move occurred from B to A
        }
        return -1;
    }
        
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int stepNumber = 0;
        int status = 0;
        try {
        Stack Source = new Stack();
        Stack Auxilary = new Stack();
        Stack Destination = new Stack();
        
        System.out.println("Enter the number of disks : ");
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(input.readLine());
        if(n<=0)
        {
            System.out.println("Sorry wrong input, negative numbers not allowed.");
            System.exit(1);
        }
        for(int i=n; i>0; i--)
            Source.push(i);
        int m = n%2;
        do {
            if(m==1)
            {
                if((status = legalMove(Source,Destination)) == 1)
                    System.out.println((++stepNumber) + ". Source --> Destination");
                else if (status == 2)
                    System.out.println((++stepNumber) + ". Destination --> Source");
                
                if((status = legalMove(Source,Auxilary)) == 1)
                    System.out.println((++stepNumber) + ". Source --> Auxilary");
                else if(status == 2)
                    System.out.println((++stepNumber) + ". Auxilary --> Source");
                else 
                    break;
            }
            
            else
            {
                if((status = legalMove(Source,Auxilary)) == 1)  
                    System.out.println((++stepNumber) + ". Source --> Auxilary");
                else if (status == 2)
                    System.out.println((++stepNumber) + ". Auxilary --> Source");
                
                if((status = legalMove(Source,Destination)) == 1)
                    System.out.println((++stepNumber) + ". Source --> Destination");
                else if(status == 2)
                    System.out.println((++stepNumber) + ". Destination --> Source");
                
            }
            
            if((status = legalMove(Auxilary,Destination)) == 1) 
                System.out.println((++stepNumber) + ". Auxilary --> Destination");
            else if(status == 2)
                System.out.println((++stepNumber) + ". Destination --> Auxilary");
        }while(Destination.size()!=n);
        System.out.println("X-----------------------X");
        }         

        catch (Exception e){
        }
        }
    }


Ibibo Interview Questions (Tradus.in, goIbibo.com, payU.in)


Interview Questions for Software Engineer Profile

Ibibo Web Pvt Ltd - May 2012



round1

1. Linked list contain alphabets.find if it is palindrome or not
2. Array of unsorted no. is given, find triplets which satisfy a2 + b2 = c2.
3. Duplicate a linked list.


round2

1. Sorted array cyclically right-shifted unknown no of times. find an element in it.
2. Stack which does push, pop and findMin in O(1).


round3

1. Given 2 arrays unsorted, insert common elements in third array in O(n).
2. Given 2 arrays unsorted, insert unique elements in third array in O(n).
3. Fill n*n matrix clockwise starting from center. Write efficient code.
ex.   7   8  9
        6   1  2
        5   4  3
4. Print 2D matrix in spiral order.


round4

1. Lots of technical questions from Resume.
2. Given three arrays A,B,C containing unsorted numbers.  Find three numbers a, b, c from each of array A, B, C such that |a-b|, |b-c| and |c-a| are minimum.