Tuesday, September 12, 2017

Yatra.com Interview Experience | The Celebrity Problem

Yatra.com Interview Experience|The Celebrity Problem

The Celebrity Problem

In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in minimum number of questions.

We can describe the problem input as an array of numbers/characters representing persons in the party. We also have a hypothetical function HaveAcquaintance(A, B) which returns true if A knows B, false otherwise.

How can we solve the problem?.

We measure the complexity in terms of calls made to HaveAcquaintance().

There are many solution to this question.Let us see below:

Solution 1 (Graph)

We can model the solution using graphs. Initialize indegree and outdegree of every vertex as 0. If A knows B, draw a directed edge from A to B, increase indegree of B and outdegree of A by 1. Construct all possible edges of the graph for every possible pair [i, j]. We have NC2 pairs. If celebrity is present in the party, we will have one sink node in the graph with outdegree of zero, and indegree of N-1. We can find the sink node in (N) time, but the overall complexity is O(N2) as we need to construct the graph first.

Solution 2 (Recursion)

We can decompose the problem into combination of smaller instances. Say, if we know celebrity of N-1 persons, can we extend the solution to N? We have two possibilities, Celebrity(N-1) may know N, or N already knew Celebrity(N-1). In the former case, N will be celebrity if N doesn’t know anyone else. In the later case we need to check that Celebrity(N-1) doesn’t know N.

Solve the problem of smaller instance during divide step. On the way back, we find the celebrity (if present) from the smaller instance. During combine stage, check whether the returned celebrity is known to everyone and he doesn’t know anyone. The recurrence of the recursive decomposition is,

T(N) = T(N-1) + O(N)

T(N) = O(N2). You may try writing pseudo code to check your recursion skills.

Solution 3 (Using Stack)

The graph construction takes O(N2) time, it is similar to brute force search. In case of recursion, we reduce the problem instance by not more than one, and also combine step may examine M-1 persons (M – instance size).
We have following observation based on elimination technique (Refer Polya’s How to Solve It book).

If A knows B, then A can’t be celebrity. Discard A, and B may be celebrity.
If A doesn’t know B, then B can’t be celebrity. Discard B, and A may be celebrity.
Repeat above two steps till we left with only one person.
Ensure the remained person is celebrity. (Why do we need this step?)
We can use stack to verity celebrity.

Push all the celebrities into a stack.
Pop off top two persons from the stack, discard one person based on return status of HaveAcquaintance(A, B).
Push the remained person onto stack.
Repeat step 2 and 3 until only one person remains in the stack.
Check the remained person in stack doesn’t have acquaintance with anyone else.
We will discard N elements utmost (Why?). If the celebrity is present in the party, we will call HaveAcquaintance() 3(N-1) times. Here is code using stack.

Sample Code:

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
import java.util.Stack;

public class CelebrityTest
{
    // Person with 2 is celebrity
    static int MATRIX[][] = { { 0, 0, 1, 0 },
                              { 0, 0, 1, 0 },
                              { 0, 0, 0, 0 },
                              { 0, 0, 1, 0 } };

    // Returns true if a knows b, false otherwise
    static boolean knows(int a, int b)
    {
        boolean res = (MATRIX[a][b] == 1) ? true : false;
        return res;
    }

    // Returns -1 if celebrity is not present.
    // If present, returns id (value from 0 to n-1).
    static int findCelebrity(int n)
    {
        Stack<Integer> st = new Stack<Integer>();
        int c;

        // Step 1 :Push everybody onto stack
        for (int i = 0; i < n; i++)
        {
            st.push(i);
        }

        while (st.size() > 1)
        {
            // Step 2 :Pop off top two persons from the
            // stack, discard one person based on return
            // status of knows(A, B).
            int a = st.pop();
            int b = st.pop();

            // Step 3 : Push the remained person onto stack.
            if (knows(a, b))
            {
                st.push(b);
            }

            else
                st.push(a);
        }

        c = st.pop();

        // Step 5 : Check if the last person is
        // celebrity or not
        for (int i = 0; i < n; i++)
        {
            // If any person doesn't know 'c' or 'a'
            // doesn't know any person, return -1
            if (i != c && (knows(c, i) || !knows(i, c)))
                return -1;
        }
        return c;
    }

    // Driver program to test above methods
    public static void main(String[] args)
    {
        int n = 4;
        int result = findCelebrity(n);
        if (result == -1)
        {
            System.out.println("No Celebrity");
        }
        else
            System.out.println("Celebrity ID " + result);
    }
}

OutPut:Celebrity ID 2

Complexity O(N). Total comparisons 3(N-1).

Try the above code for successful MATRIX {{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}}.

Note: You may think that why do we need a new graph as we already have access to input matrix. Note that the matrix MATRIX used to help the hypothetical function HaveAcquaintance(A, B), but never accessed via usual notation MATRIX[i, j]. We have access to the input only through the function HaveAcquiantance(A, B). Matrix is just a way to code the solution. We can assume the cost of hypothetical function as O(1).

If still not clear, assume that the function HaveAcquiantance accessing information stored in a set of linked lists arranged in levels. List node will have next and nextLevel pointers. Every level will have N nodes i.e. an N element list, next points to next node in the current level list and the nextLevel pointer in last node of every list will point to head of next level list. For example the linked list representation of above matrix looks like,

L0 0->0->1->0
             |
L1           0->0->1->0
                       |
L2                     0->0->1->0
                                 |
L3                               0->0->1->0
The function HaveAcquanintance(i, j) will search in the list for j-th node in the i-th level. Out goal is to minimize calls to HaveAcquanintance function.


Word Break Problem Java Solution

Word Break Problem Java Solution

Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
This is a famous Google interview question, also being asked by many other companies now a days.

Consider the following dictionary 

{ i, like, sam, sung, samsung, mobile, ice, 
  cream, icecream, man, go, mango}

Input:  ilike
Output: Yes
The string can be segmented as "i like".

Input:  ilikesamsung
Output: Yes

The string can be segmented as "i like samsung" or
"i like sam sung".

i have given two solution in my sample code.you can use any of them.i have given solution is
using HashSet and other one using simple logic.

Sample Code:

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class WordBreakProblemApp
{
private static Set<String> DICTIONARY = new HashSet<String>();
static
{
DICTIONARY.add("mobile");
DICTIONARY.add("samsung");
DICTIONARY.add("sam");
DICTIONARY.add("sung");
DICTIONARY.add("man");
DICTIONARY.add("mango");
DICTIONARY.add("icecream");
DICTIONARY.add("and");
DICTIONARY.add("go");
DICTIONARY.add("i");
DICTIONARY.add("love");
DICTIONARY.add("ice");
DICTIONARY.add("cream");
}

private static boolean existInDictionary(String string)
{
return DICTIONARY.contains(string.toLowerCase());
}

private static void wordutil(String input)
{
processInputString(input, input.length(), "");
}

private static void processInputString(String input, int size, String result)
{

for (int i = 1; i <= size; i++)
{
if (existInDictionary(input.substring(0, i)))
{
if (i == size)
{
  System.out.println(result + " " + input);
  break;
}

else
{
  processInputString(input.substring(i, size), size - i,
  result + " " + input.substring(0, i) + " ");
}
}
 }
}

public static void main(String[] args)
{
   wordutil("ilovesamsungmobile");
}


/*********You can use this method too.it is optional****************/

   public boolean wb(int start, String str, List<String> wordDict, StringBuilder sb)
   {
        for(int i=start; i<str.length(); i++)
        {
                String sub = str.substring(start,i+1);
                System.out.println(sub);
                if(wordDict.contains(sub))
                {
                    sb.append(sub);
                    if(sb.length() == str.length())
                    {
                        return true;
                    }
                 
                    boolean r = wb(i+1, str, wordDict, sb);
                    if(r) return r;
                    sb.setLength(sb.length()-sub.length());
                }
        }
        return false;
    }
}

Output:

 i  love  sam  sung  mobile
 i  love  samsung  mobile


Trending Interview Question Puzzle | Pirates and Gems

Trending Interview Question Puzzle | Pirates and Gems

Question:

Seven pirates attacked the British ship and looted some rare gems from them. They decided to rest for some time and then divide the gems later. While everyone was resting, two pirates wake up and planned to divide gems equally between the two. When they divided gems equally, one gem was left. So, they decided to wake up the third pirate and divide among three, but alas again one gem was left. They decide to wake up the fourth pirate to divide the gems and again one gem was left. The same happened again with the fifth and sixth. Finally, they woke up the 7th pirate and this time the gems were divided equally.

How many minimum gems did they stole in total ?


Solution:

301

Explanation:

1. When there are two pirates, 301/2 = 1 (Remainder)
2. When there are three pirates, 301/3 = 1 (Remainder)
3. When there are four pirates, 301/4 = 1 (Remainder)
4. When there are five pirates, 301/5 = 1 (Remainder)
5. When there are six pirates, 301/6 = 1 (Remainder)
6. When there are seven pirates, 301/7 = 0 (Remainder)


Check Whether a number is Duck Number or not java solution

Check Whether a number is Duck Number or not?

A Duck number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number. For example 3210, 8050896, 70709 are all duck numbers whereas 02364, 03401 are not.

The task is to check whether the given number is a duck number or not.

Examples:

Input : 707069
Output : It is a duck number.
Explanation: 707069 does not contains zeros at the beginning.

Input : 02364
Output : It is not a duck number.
Explanation: in 02364 there is a zero at the beginning of the number.

Sample code:

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class DuckeNumberApp
{
public static void main(String[] args)
{
String num1 = "1023";

        char first_digit1 = num1.charAt(0);
       
        if( check_duck(num1) > 0 && first_digit1 != '0')
            System.out.println("It is a duck number");
        else
            System.out.println("It is not a duck number");
}

public  static int check_duck( String num)
       {
       int len = num.length();
       int count_zero = 0 ;
       char ch;

       for(int i = 1;i < len ;i++)
       {    
           ch=num.charAt(i);
           if(ch=='0')
               count_zero++;
       }
       return count_zero ;
    }
}


Output:

It is a duck number

Trending Interview Puzzle | Truth and Lie Question

Trending Interview Puzzle | Truth and Lie Question

There are two tribes, “Lie tribe” and “Truth Tribe”. “Lie tribe”, as per the name, always lie and “Truth tribe” always speak the truth. You meet three of the persons from these tribes and ask the first person: “Which tribe do you belong to ?”. He replies something in his language which you don’t understand. Second person translates to you that, he is saying that he belongs to the “Lie Tribe”. Third person says that second person is lying.

Question is : Which tribe does the third person belong to?


Solution: Truth Tribe

Explanation: 

As per question we dont know the first person belongs to which tribe.So now if we assume the
first person is from Truth Tribe then he will be definetley saying that he is from "truth tribe".
So in this case the second person must be lying.

Now again, if we assume the first person is from"Lie tribe" then also he will say that he belongs
to truth tribe.So second person is lying again in this case.

SO the conclusion is in both the cases,he belongs to "truth tribe".

Trending Puzzle in Interview | Black and White Balls

Black and White Balls Puzzle

You have 20 white and 13 black balls in a bag. You pull out 2 balls one after another. If the balls are of same color, then you replace them with a white ball – but if they are of different color, you replace them with a black ball. Once you take out the balls, you do not put them back in the bag – so the balls keep reducing. What would be the color of the last ball remaining in the bag.

Solution: Black

How?

So the solution is very simple,the trick is in the solution itself.Let me give you hint again

"You pull out 2 balls one after another. If the balls are of same color, then you replace them with a white ball – but if they are of different color, you replace them with a black ball."

So, the black balls would always be odd in numbers – either you remove 2 together or remove 1 and add 1 – so they remain odd always. So, the last ball in the bag would be a black ball only.

Monday, September 11, 2017

Number of jumps for a thief to cross walls?


Number of jumps for a thief to cross walls?.

A thief trying to escape from a jail. He has to cross N walls each with varying heights (every height is greater than 0). He climbs X feet every time. But, due to the slippery nature of those walls, every time he slips back by Y feet. Now the task is to calculate the total number of jumps required to cross all walls and escape from the jail.


Examples:

Input : heights[] = {11, 11}
                X = 10;
                Y = 1;
Output : 4

He needs to make 2 jumps for first wall
and 2 jumps for second wall.

Input : heights[] = {11, 10, 10, 9}
                 X = 10;
                 Y = 1;
Output : 5

Sample Code:


public class Test
{
static int jumpcount(int x, int y, int n, int height[])
{
int jumps = 0;
for (int i = 0; i < n; i++)
{

// Since all heights are
// greater than 1, at-least
// one jump is always required
jumps++;

// More jumps required if height
// is greater than x.
if (height[i] > x)
{
// Since we have already counted
// one jump
int h = height[i] - (x - y);

// Remaining jumps
jumps += h/(x - y);

// If there was a remainder greater
// than 1. 1 is there to handle cases
// like x = 11, y = 1, height[i] = 21.
if (h % (x-y) > 1)
jumps++;
}
}
return jumps;
}

public static void main(String args[])
{
int x = 10;
int y = 1;
int height[] = { 11, 34, 27, 9 };
int n = height.length;
System.out.println(jumpcount(x, y, n, height));
}
}

Output: 10

Wednesday, September 6, 2017

Main thread in Java

Main thread in Java

Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

In detail,a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its executable code and the values of its variables at any given time.

Main Thread

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program, because it is the one that is executed when our program begins.

Properties :

It is the thread from which other “child” threads will be spawned.

Often, it must be the last thread to finish execution because it performs various shutdown actions



How to control Main thread

The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called. The default priority of Main thread is 5 and for all remaining user threads priority will be inherited from parent to child.

Sample Code:

// Java program to control the Main Thread
public class Test extends Thread
{
public static void main(String[] args)
{
// getting reference to Main thread
Thread t = Thread.currentThread();

// getting name of Main thread
System.out.println("Current thread: " + t.getName());

// changing the name of Main thread
t.setName("Geeks");
System.out.println("After name change: " + t.getName());

// getting priority of Main thread
System.out.println("Main thread priority: "+ t.getPriority());

// setting priority of Main thread to MAX(10)
t.setPriority(MAX_PRIORITY);

System.out.println("Main thread new priority: "+ t.getPriority());


for (int i = 0; i < 5; i++)
{
System.out.println("Main thread");
}

// Main thread creating a child thread
ChildThread ct = new ChildThread();

// getting priority of child thread
// which will be inherited from Main thread
// as it is created by Main thread
System.out.println("Child thread priority: "+ ct.getPriority());

// setting priority of Main thread to MIN(1)
ct.setPriority(MIN_PRIORITY);

System.out.println("Child thread new priority: "+ ct.getPriority());

// starting child thread
ct.start();
}
}

// Child Thread class
class ChildThread extends Thread
{
@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("Child thread");
}
}
}

Output:

Current thread: main
After name change: Geeks
Main thread priority: 5
Main thread new priority: 10
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread priority: 10
Child thread new priority: 1
Child thread
Child thread
Child thread
Child thread
Child thread

Relation between the main() method and main thread in Java

For each program, a Main thread is created by JVM(Java Virtual Machine). The “Main” thread first verifies the existence of the main() method, and then it initializes the class. Note that from JDK 6, main() method is mandatory in a standalone java application.

Deadlocking with use of Main Thread(only single thread)

We can create a deadlock by just using Main thread, i.e. by just using a single thread. The following java program demonstrate this.

// Java program to demonstrate deadlock
// using Main thread
public class Test
{
    public static void main(String[] args)
    {
        try
        {
           
            System.out.println("Entering into Deadlock");
           
            Thread.currentThread().join();
           
            // the following statement will never execute
            System.out.println("This statement will never execute");
           
        }
       
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Entering into Deadlock

Explanation : 

The statement “Thread.currentThread().join()”, will tell Main thread to wait for this thread(i.e. wait for itself) to die. Thus Main thread wait for itself to die, which is nothing but a deadlock.