Archives

gravatar

Blog # 60 : Thief's Proposal !!


There are 5 thieves. They are all numbered one to five. They have 500 pieces of gold which need to be distributed among themselves. First the number 1 distributes it and after that a voting is done : if he gets majority votes his distribution is carried out else he is killed, if the votes are equal, then also distribution is done his way. If he is killed then next numbered person does the distribution and this goes on till number 5. Each thief values his life more than the gold.
So how does the first thief distribute gold to get maximum and to not get killed also ?

Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Blog # 59 : Will you meet your friend?


Two friends decide to meet at a cafe between 11 am and 12 pm i.e. one hour. They also decide that the one who reaches before the other waits for 5 minutes and if the other does not arrive he leaves. What is the probability of their meeting ?

Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Blog # 58 : Run Length Encoding (RLE)


Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. Count of 1 is not indicated. Write a program to find RLE of given string.

Eg.
input = "aabbbcddeef" RLE = "a2b3cd2e2f"
input = "aaabbcddeeeef" RLE = "a3b2cd2e4f"

Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Blog # 57 : Finding the black sheep [:D]


You have 12 balls. All of them are identical except one, which is either heavier or lighter than the rest. You have a simple two-armed scale, and are permitted three weighing. Can you identify the odd ball, and determine whether it is heavier or lighter than the rest ?

Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Blog # 56 : Next equi-set digit Number


Given an integer N. Devise an algorithm to find out the smallest integer greater than N having the same number of bits set as that of N. (When a bit is 1, we say it is set)


Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.





Courtesy: Vibhaj

gravatar

Blog # 55 : Premutations of every subset


Given a array of characters of size N. Devise an algorithm to generate all possible permutations of given size K (K <= N).

Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.




Courtesy: Vibhaj

gravatar

Blog # 54 : Swapping; Not so easy


Give a method to swap two numbers without using additional memory.



Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Blog # 53 : How to multiply by 7?


Give a fast method to multiply a number by 7.



Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj

gravatar

Blog # 52 : Searching in 2D array

Given 2D array with integers sorted both horizontally and vertically. Devise an efficient algorithm to search for key in the 2D array. What is the complexity ? 

Eg. 

    1 4 7 13 

    2 5 9 15 

    3 6 10 16

Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.




Courtesy: Vibhaj

gravatar

Blog # 51 : Minimum & Maximum + Stack


Assume you have infinite memory. Design an algorithm using stacks that can find the minimum and maximum at any point while reading an infinite sequence of numbers in least possible time.

Eg. 5, 9, 2, 35, 23, 1, ...
After 3rd element, the algorithm would tell min = 2, max = 9
After 6th element, algorithm would tell min = 1, max = 35




Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.




Courtesy: Vibhaj

gravatar

Blog # 50 : Thousand Doors and Final combination

A high school has a strange principal. On the first day, he has his students perform an odd opening day ceremony:There are one thousand lockers and one thousand students in the school. The principal asks the first student to go to every locker and open it. Then he has the second student go to every second locker and close it. The third goes to every third locker and, if it is closed, he opens it, and if it is open, he closes it. The fourth student does this to every fourth locker, and so on. After the process is completed with the thousandth student, how many lockers are open ?

gravatar

Blog # 49 : Weighing machine & Denominations of weights

You are given a weighing machine. Find the minimum number of denominations of weights you need to measure any N kgs given that you may use the denominations on any side of the weighing machine.

gravatar

Blog # 48 : Determine the non-existence


Devise an algorithm to find whether a given number N is of the form 2^x + 2^y (^ means exponentiation, x and y are positive).



Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.





Courtesy: Vibhaj

gravatar

Blog # 47 : 2^x + 2^y


Devise an algorithm to find whether a given number N is of the form 2^x + 2^y (^ means exponentiation, x and y are positive).



Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.



Courtesy: Vibhaj, Gurpreet & Ankit

gravatar

Blog # 46 : Find out the matching sock

Fint out the matching socks: Michael have ten pairs of black socks, eight pairs of white socks and seven pairs of green socks. Everything is mixed in a draw. As there is no light he were not able to identify the color of the socks. How many of the socks did he want to take to match one pair ?




p.s. - For Remarks please hit the question name once, given in the question itself. For Hint, hit it twice and for the solution, hit it thrice.

gravatar

Blog # 45 : Blind Search

A blind search (also called an uninformed search) is a search that has no information about its domain. The only thing that a blind search can do is distinguish a non-goal state from a goal state.

For more read here about Blind Search

Code:
 
#include<iostream>
#include<cstdlib>
#include<map>
#define MAX 50
using namespace std;

map <int,int> mp;

void printpath(int start)
{
 if (mp[start]==-1)
 {
  cout<<start<<endl;
  return;
 }
 else
 {
  cout<<start<<"  ";
  printpath(mp[start]);
 } 
}
int main()
{ 
 int n,adj[MAX][MAX],v[MAX];
 int rnd,start,end,temp;
 bool solve=false;
 cout<<"enter the no of nodes : ";
 cin>>n;
 cout<<"enter the adjacency matrix : ";
 for(int i=0;i<n;i++)
  for(int j=0;j<n;j++)
   cin>>adj[i][j];
 for(int i=0;i<n;i++)
  v[i]=0;
 cout<<"enter the start and end node: ";
 cin>>start>>end;
 temp=start;
 v[start]=1;
 mp[end]=-1;
 while(!solve)
 {
  rnd=random()%n;
  //cout<<"reached here";
  //cout<<"  "<<rnd<<endl; 
  if(rnd==end && adj[start][rnd]==1)
  {
   mp[start]=rnd;
   solve=true;
  }
  else
  {
   if(adj[start][rnd]==1 && v[rnd]==0)
   {
    mp[start]=rnd;
    //cout<<mp[start]<<endl;
    v[rnd]=1;
    start=rnd;
   }
   else
    continue;
  }
 } 
 printpath(temp);
 return 0;
}

gravatar

Blog # 44 : Hill Climbing (A local Search)

In computer science, hill climbing is a mathematical optimization technique which belongs to the family of local search. It is an iterative algorithm that starts with an arbitrary solution to a problem, then attempts to find a better solution by incrementally changing a single element of the solution. If the change produces a better solution, an incremental change is made to the new solution, repeating until no further improvements can be found.

For example, hill climbing can be applied to the Traveling Salesman Problem. It is easy to find an initial solution that visits all the cities but will be very poor compared to the optimal solution. The algorithm starts with such a solution and makes small improvements to it, such as switching the order in which two cities are visited. Eventually, a much shorter route is likely to be obtained.

Read more about Hill Climbing Problem

Code:
#include<iostream>
#include<cstdio>
using namespace std;
int calcCost(int arr[],int N){
 int c=0;
 for(int i=0;i<N;i++){
  for(int j=i+1;j<N;j++) if(arr[j]<arr[i]) c++;
 }
 return c;
}

void swap(int arr[],int i,int j){
 int tmp=arr[i];
 arr[i]=arr[j];
 arr[j]=tmp;
}

int main(){
 int N;
 scanf("%d",&N);
 int arr[N];
 for(int i=0;i<N;i++) scanf("%d",&arr[i]);
 int bestCost=calcCost(arr,N),newCost,swaps=0;;
 while(bestCost>0){
  for(int i=0;i<N-1;i++){
   swap(arr,i,i+1);
   newCost=calcCost(arr,N);
   if(bestCost>newCost){
    printf("After swap %d: \n",++swaps);
    for(int i=0;i<N;i++) printf("%d ",arr[i]);
    printf("\n");
    bestCost=newCost;
   }
   else swap(arr,i,i+1);
  }
 }
 printf("Final Ans\n");
 for(int i=0;i<N;i++) printf("%d ",arr[i]);
 printf("\n");
 return 0;
}

gravatar

Blog # 43 : Minimax (Minmax) Search

Minimax (sometimes minmax) is a decision rule used in decision theory, game theory, statistics and philosophy for minimizing the possible loss for a worst case (maximum loss) scenario. Alternatively, it can be thought of as maximizing the minimum gain (maximin). Originally formulated for two-player zero-sum game theory, covering both the cases where players take alternate moves and those where they make simultaneous moves, it has also been extended to more complex games and to general decision making in the presence of uncertainty.

For more please refer Minimax

Code:


#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;

vector <int> vec;

int large(int a,int b)
{
 if(a>b)
  return a;
 else
  return b;
}

int small(int a,int b)
{
 if(a>b)
  return b;
 else 
  return a;
}

void max_min(int p,int q,int *max,int *min)
{
 if(p==q)
 {
  *max=vec[p];
  *min=vec[q];
 }
 
 else if(p==(q-1))
 {
  if(vec[p]>vec[q])
  {
   *max=vec[p];
   *min=vec[q];
  }
  else
  {
   *max=vec[q];
   *min=vec[p];
  }
 }
 
 else
 {
  int m=(p+q)/2;
  int max1,max2,min1,min2;
  
  max_min(p,m,&max1,&min1);
  max_min(m+1,q,&max2,&min2);
  *max=large(max1,max2);
  *min=small(min1,min2);
 }
}

int main()
{
 int a,n=0;
 int min=0,max=0;
 
 cout<<"enter the elements (enter -1 to quit) :  ";
 while(1)
 {
  cin>>a;
  if(a==-1)
   break;
  else
  {
   vec.push_back(a);
   n++;
  }
 }
 max_min(0,n-1,&max,&min);
 
 cout<<"MAX = "<<max<<"\t"<<"MIN = "<<min<<endl;
 
 return 0;
}

gravatar

Blog # 42 : Random Selection from a Linked List


Random Selection from a Linked List There is a linked list of numbers of length N. N is very large and you don’t know N. You have to write a function that will return k random numbers from the list. Numbers should be completely random. 
Conditions : 
  1. Use random number function rand() that returns a number between 0 and 1.
  2. It must be done in O(N) time
p.s. - For Remarks please hit the question name once, given in the question itself. For Hint, hit it twice and for the solution, hit it thrice.

gravatar

Blog # 41 : Can you Calculate properly?


Can you calculate properly?: Three people check into a hotel. They pay $30 to the manager, and go to their room. The manager finds out that the room rate is $25 and gives $5 to the bellboy to return. On the way to the room the bellboy reasons that $5 would be difficult to share among three people so he pockets $2 and gives $1 to each person. Now each person paid $10 and got back $1. So they paid $9 each, totaling $27. The bellboy has $2, totaling $29. Where is the remaining dollar ? 




p.s. - For Remarks please hit the question name once, given in the question itself. For Hint, hit it twice and for the solution, hit it thrice.

gravatar

Blog # 40 : Amazon Interview Questions

Following are the questions asked to one of the successful candidates in Amazon Interview :-


Round 1: 
 
     1. A Twin Prime number is a prime number which differs from other prime number by two. eg    (5,7), (11,13), (17,19), (29,31), (41,43), (59,61)........ Prove that number between twin primes is divisible by 6. 

     2. You have a binary tree with non-negative numeric values stored in its nodes, you need to find out the maximum possible sum of all the nodes. Selection of nodes for the sum follows following constraint: 
If you have selected any node for the sum, you can not select its immediate parent and its children for sum.

Hint : Answer does not include level order traversal for obvious reasons.

 
     3. Find all permutations of a string.


 

Round 2:

     1. For a given company, you need to maintain the stock prices (closing price of a day) for last "m" years. [By "m" years he meant, if the year say increases by 1 then database has data of "(m+1)" years, not that the data for "m"th year gets deleted]
Now suggest a data-structure for holding the stock prices of all the companies such that 

(a). The stock price (closing price of the day) of a given company on a given date can be searched easily.   
(b). The stock prices for all the companies can be printed for a given date. 
(By all companies he meant if a company say starts today, its data will also get added to the database and if a company gets closed today its data won't be deleted). 

     2. For compiling a java program you need a list of JARs as libraries but the given JARs have internal dependencies between them: 
eg. JAR1 can only be loaded after loading JAR2 and JAR3. JAR2 is also dependent on JAR3 and JAR4. 
Now write a program to load all the JAR files following their dependency rules.


 
 
Round 3:

     1. You are given an array, infinity on both the sides along with the current position of the pointer [Think of magnetic tape and the head of the reading machine].
Now the data stored in the array can be of length either of 1 byte or 2 bytes.
If the data is of 1 byte, then 1st bit will be 0.
If the data is of 2 bytes, 1st bit of 1st byte the data will be 1 and 1st bit of 2nd byte will be having a Don't Care condition. 
You are given the current position of pointer as the start of a new data. Find the starting position of data, previous to the current data. In other words, find the previous data.



Round 4:

     1. Database Question: 
The main aim was to ask how is a database implemented internally. [Answer : using B and B+ trees]


     2. Synchronization of threads:
You have an account and deposit & withdraw operations should be mutually exclusive, but the ReadAccountValue should not be blocked even if a thread is using deposit or withdraw method.
Account {
       Deposit();
       Withdraw();
        ReadAccountValue(); 
} 
For ReadAccountValue method, do not return an illegal value. (say a thread uses ReadAccountValue while other thread uses Withdraw(), do not return the illegal previous value)

p.s. - For any kind of confusion, don't hesitate in asking.

gravatar

Blog # 39 : Product Array

Devise an algorithm :
There is an array A[N] of N numbers. Find a Product Array P[N] of an array A[N] which is defined such that for all i<N, P[i] = (product of all elements of A except A[i]).
For example, P[0] will be multiplication of A[1] to A[N-1] and P[1] will be multiplication of A[0] and from A[2] to A[N-1].
Solve this without using division operator and in O(N) time.



Solution :
  1. Calculate backward product in product array P[i] = Product(A[i+1]*...*A[N])
  2. Take a variable p=1
  3. For each element of input, multiply it by p and multiply P[i] by p
Complexities :
  • Time : O(N)
  • Space : O(1)
Code : 

void product_array(int[] input, int[] product, int N){
product[N-1] = 1;

for(int i=N-1; i>-1; i--){
product[i] = product[i+1]*input[i+1];
}

int p = 1;
for(int i=0; i<N; i++){
if(i > 0){
p *= input[i-1];
}

product[i] *= p;
}
}


Courtesy : Vibhaj

gravatar

Blog # 38 : Passengers and Random Seats

100 passengers are boarding an airplane with 100 seats.
Everyone has a ticket with his seat number. These 100 passengers boards the airplane in order.
However, the first passenger lost his ticket so he just took a random seat.
For any subsequent passenger, he either sits on his own seat or, if the seat is taken, he takes a random empty seat.
What's the probability that the last passenger would sit on his own seat ?



Solution:

Let us say that everyone is sitting except for the 100th passenger. Consider where can he sit - he can sit in either seat numbered 100 or 1. There cannot be any other seat vacant for him.

We can prove this using contradiction. Lets say that a seat numbered n=55 is vacant for 100th passenger. Since passenger 55 came earlier he should be sitting in his seat if its vacant. So seat 55 cant be vacant. This logic can be applied to all seats except for seat 1 and 100.

So all permutations of the seating arrangement would result in last person sitting in either seat 1 or seat 100. Both the options are equally likely.


So answer = 1/2.
 


Courtesy : Vibhaj  

gravatar

Blog # 37 : Common node in two Linked Lists

Given the heads of two linked lists, find whether they have any common node. If yes, find the common node.
Try to solve it as elegantly as possible.



Solution:

  1. Subtract the length of smaller list from the larger one.
  2. Move a pointer ahead on larger list by the difference of lengths.
  3. Now put a pointer on head of smaller list.
  4. More two pointers together.
  5. The point at which they meet is the point where they short.
Code:
 
Node *getShortedNode(Node *list1, Node *list2){

int d = length(list1) - length(list2);

if(d < 0){
   d = d * (-1);
   Node *tmp = list1;
   list1 = list2;
   list2 = tmp;
}

Node *ptr1 = list1;
for(int i=0; i<d; i++)
{
   ptr1=ptr->next;
}

Node *ptr2 = list2;
while(ptr1 != NULL){
 if(ptr1 == ptr2)
   break;
 ptr1 = ptr1->next;
 ptr2 = ptr2->next;
}
return ptr1;
}

int length(Node *list){
int count = 0;
while(list != NULL){
 list = list->next;
 count++;
}
return count;
}

gravatar

Blog # 36 : Facebook Interview Questions

Following are the interview questions asked by Facebook to one of the successful candidates Mr. Saket Jalan, CSE, IT-BHU as told by him :

Complete process was of 5 technical rounds and then 1 HR round:

Online Round Question

Given a dictionary consisting of n 3 letter words, with n<100. We need to compute all possible 3*3 grids such that 3 letter words lying on each row, each column and each diagonal is in dictionary. 

Interview Round 1:

write a code that prints the tree level wise. Then he asked to reduce space in cost of time.

Interview Round 2:

Given n distinct numbers from 1 to n. Write a code that prints all the k-element subsets. for eg: for n=4, k=2: (1,2), (1,3), (1,4), (2,3), (2,4), (3,4). Then I was asked to write the equation of its complexity. 

Interview Round 3:

It was elimination round, everyone was given below Q and had to write code within 45 minutes along with test cases.
Given a structure, with data members as string and number. A list consists of structure data, sorted in dictionary order by strings. Now, write a function, that takes a prefix, and returns all the numbers corresponding to the string that have this prefix in dictionary. Also write the test cases.
They judged it based upon coding style, time and space complexity.

Interview Round 4:

Last round. In a game a player can score either 2,3 or 7 runs. A player has just entered the ground and he sees "score" on the board. Write a program that returns number of ways in which this score can be obtained. eg: 10 can be obtained by (3+7), (7+3), (2+2+2+2+2), (2+2+3+3), (2+3+2+3), (2+3+3+2), (3+2+2+3), (3+2+3+2), (3+3+2+2)
Then he asked to reduce space complexity. 

HR:Usual Questions like why Facebook? why not other companies? and many things from CV.

Almost every interviewer asked about some of my projects from the CV. and yes STL was allowed except in round 3.
 
Enhanced by Zemanta