A rabbit sits at the bottom of a staircase with n stairs.rabbit can hop up only one or two stairs at a time.how many different ways are there two reach at top of stair.
Monday, March 12, 2012
Measure 9 minutes
You are given two hourglasses. One measures 4 minutes and one measures 7 minutes. How would you measure exactly 9 minutes?
consecutive sum is perfect square
Arrange numbers from 1 to 16 such that the sum of every two consecutive numbers in the arrangement is a perfect square (you can use a number only once).
Sunday, March 11, 2012
The Word Break Problem
Given an string and a dictionary of words, find out if the input string can be broken into a space-separated sequence of one or more dictionary words.
Find a string/pattern in a 2d character array
You are given a 2D array of characters and a character pattern. WAP to find if pattern is present in 2D array. Pattern can be in any way (all 8 neighbors to be considered) but you can’t use same character twice while matching. Return 1 if match is found, 0 if not.
Example: Find “microsoft” in below matrix.

We can see the read color character, which form “Microsoft” in above 2D array.
Strategy:
Manually finding the solution of this problem is relatively intuitive, we just need to describe an algorithm for it. Ironically, describing the algorithm is not the easy part.
How do we do it manually? First we match the first element; if it matched we matched the 2nd element in the 8 neighbors of first match; do this process recursively; when last character of input pattern matches, return true.
During above process, you take care not to use any cell in 2D array twice. For this purpose, you mark every visited cell with some sign. If your pattern matching fails at some place, you start matching from the beginning (of pattern) in remaining cells. While returning, you unmark visited cells.
Lets convert above intuitive method in algorithm. Since we are doing similar checks every time for pattern matching, a recursive solution is what we need here.
In recursive solution, we need to check if the substring passed is matched in the given matrix or not. The condition is not to use the already used cell. For finding already used cell, we need to have another 2D array to the function (or we can use an unused bit in input array itself.) Also, we need the current position of input matrix, from where we need to start. Since we need to pass a lot more information than actually given, we should be having a wrapper function to initialize that extra information to be passed
Algorithm:
If you are past the last character in pattern
Return true
If you got an used cell again
Return falseIf you got past the 2D matrix
Return false
If searching for first element and cell doesn’t match
findmatch with next cell in row-first order (or column first order)
otherwise if character matches
mark this cell as used
res = findmatch with next position of pattern in 8 neighbors
mark this cell as unused
Return res
Otherwise
Return false
Code:
#define MAX 100
bool findmatch_wrapper(char mat[MAX][MAX], char *pat, int nrow, int ncol)
{
if (strlen(pat) > nrow*ncol)
return false;
int used[MAX][MAX] = {{0,},};
return findmatch(mat, pat, used, 0, 0, nrow, ncol, 0);
}
//level: index till which pattern is matched
//x, y: current position in 2D array
bool findmatch(char mat[MAX][MAX], char *pat, int used[MAX][MAX], int x, int y, int nrow, int ncol, int level)
{
if (level == strlen(pat)) //pattern matched
return true;
if (nrow == x || ncol == y)
return false;
if (used[x][y])
return false;
if (mat[x][y] != pat[level] && level == 0)
{
if (x < (nrow - 1))
return findmatch(mat, pat, used, x+1, y, nrow, ncol, level); //next element in same row
else if (y < (ncol - 1))
return findmatch(mat, pat, used, 0, y+1, nrow, ncol, level); //first element from same column
else
return false;
}
else if (mat[x][y] == pat[level])
{
bool res;
//marking this cell as used
used[x][y] = 1;
//finding subpattern in 8 neighbours
res = (x > 0 ? findmatch(mat, pat, used, x-1, y, nrow, ncol, level+1) : false) ||
(res = x < (nrow - 1) ? findmatch(mat, pat, used, x+1, y, nrow, ncol, level+1) : false) ||
(res = y > 0 ? findmatch(mat, pat, used, x, y-1, nrow, ncol, level+1) : false) ||
(res = y < (ncol - 1) ? findmatch(mat, pat, used, x, y+1, nrow, ncol, level+1) : false) ||
(res = x < (nrow - 1) && (y < ncol -1) ? findmatch(mat, pat, used, x+1, y+1, nrow, ncol, level+1) : false) ||
(res = x < (nrow - 1) && y > 0 ? findmatch(mat, pat, used, x+1, y-1, nrow, ncol, level+1) : false) ||
(res = x > 0 && y < (ncol - 1) ? findmatch(mat, pat, used, x-1, y+1, nrow, ncol, level+1) : false) ||
(res = x > 0 && y > 0 ? findmatch(mat, pat, used, x-1, y-1, nrow, ncol, level+1) : false);
//marking this cell as unused
used[x][y] = 0;
return res;
}
else
return false;
}
Example: Find “microsoft” in below matrix.

We can see the read color character, which form “Microsoft” in above 2D array.
Strategy:
Manually finding the solution of this problem is relatively intuitive, we just need to describe an algorithm for it. Ironically, describing the algorithm is not the easy part.
How do we do it manually? First we match the first element; if it matched we matched the 2nd element in the 8 neighbors of first match; do this process recursively; when last character of input pattern matches, return true.
During above process, you take care not to use any cell in 2D array twice. For this purpose, you mark every visited cell with some sign. If your pattern matching fails at some place, you start matching from the beginning (of pattern) in remaining cells. While returning, you unmark visited cells.
Lets convert above intuitive method in algorithm. Since we are doing similar checks every time for pattern matching, a recursive solution is what we need here.
In recursive solution, we need to check if the substring passed is matched in the given matrix or not. The condition is not to use the already used cell. For finding already used cell, we need to have another 2D array to the function (or we can use an unused bit in input array itself.) Also, we need the current position of input matrix, from where we need to start. Since we need to pass a lot more information than actually given, we should be having a wrapper function to initialize that extra information to be passed
Algorithm:
If you are past the last character in pattern
Return true
If you got an used cell again
Return falseIf you got past the 2D matrix
Return false
If searching for first element and cell doesn’t match
findmatch with next cell in row-first order (or column first order)
otherwise if character matches
mark this cell as used
res = findmatch with next position of pattern in 8 neighbors
mark this cell as unused
Return res
Otherwise
Return false
Code:
#define MAX 100
bool findmatch_wrapper(char mat[MAX][MAX], char *pat, int nrow, int ncol)
{
if (strlen(pat) > nrow*ncol)
return false;
int used[MAX][MAX] = {{0,},};
return findmatch(mat, pat, used, 0, 0, nrow, ncol, 0);
}
//level: index till which pattern is matched
//x, y: current position in 2D array
bool findmatch(char mat[MAX][MAX], char *pat, int used[MAX][MAX], int x, int y, int nrow, int ncol, int level)
{
if (level == strlen(pat)) //pattern matched
return true;
if (nrow == x || ncol == y)
return false;
if (used[x][y])
return false;
if (mat[x][y] != pat[level] && level == 0)
{
if (x < (nrow - 1))
return findmatch(mat, pat, used, x+1, y, nrow, ncol, level); //next element in same row
else if (y < (ncol - 1))
return findmatch(mat, pat, used, 0, y+1, nrow, ncol, level); //first element from same column
else
return false;
}
else if (mat[x][y] == pat[level])
{
bool res;
//marking this cell as used
used[x][y] = 1;
//finding subpattern in 8 neighbours
res = (x > 0 ? findmatch(mat, pat, used, x-1, y, nrow, ncol, level+1) : false) ||
(res = x < (nrow - 1) ? findmatch(mat, pat, used, x+1, y, nrow, ncol, level+1) : false) ||
(res = y > 0 ? findmatch(mat, pat, used, x, y-1, nrow, ncol, level+1) : false) ||
(res = y < (ncol - 1) ? findmatch(mat, pat, used, x, y+1, nrow, ncol, level+1) : false) ||
(res = x < (nrow - 1) && (y < ncol -1) ? findmatch(mat, pat, used, x+1, y+1, nrow, ncol, level+1) : false) ||
(res = x < (nrow - 1) && y > 0 ? findmatch(mat, pat, used, x+1, y-1, nrow, ncol, level+1) : false) ||
(res = x > 0 && y < (ncol - 1) ? findmatch(mat, pat, used, x-1, y+1, nrow, ncol, level+1) : false) ||
(res = x > 0 && y > 0 ? findmatch(mat, pat, used, x-1, y-1, nrow, ncol, level+1) : false);
//marking this cell as unused
used[x][y] = 0;
return res;
}
else
return false;
}
Check if Array elements are consecutive
Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers.
Examples:
a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.
b) If array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.
c) If the array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive.
d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.
http://algorithms.tutorialhorizon.com/check-if-array-is-consecutive-integers/
http://www.geeksforgeeks.org/check-if-array-elements-are-consecutive/
Approach:
Method 1:Visited Array
Examples:
a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.
b) If array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.
c) If the array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive.
d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.
http://algorithms.tutorialhorizon.com/check-if-array-is-consecutive-integers/
http://www.geeksforgeeks.org/check-if-array-elements-are-consecutive/
Approach:
Method 1:Visited Array
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[].
Method 2:Mark Negative
This method is O(n) time complexity and O(1) extra space, but it changes the original
array and it works only if all numbers are positive. We can get the original array by
adding an extra step though. It is an extension of method 2 and it has the same two steps.
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.
In this method, the implementation of step 2 differs from method 2. Instead of creating a
new array, we modify the input array arr[] to keep track of visited elements.
The idea is to traverse the array and for each index i (where 0 <= i < n),
make arr[arr[i] – min]] as a negative value. If we see a negative value again then there
is repetition.
Largest Area Rectangle in a Histogram
Find the maximum rectangle (in terms of area) under a histogram in linear time. I mean the area of largest rectangle that fits entirely in the Histogram.
Given:A histogram with integer heights and constant width 1. I want to maximize the rectangular area under a histogram. e.g.:
http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
Given:A histogram with integer heights and constant width 1. I want to maximize the rectangular area under a histogram. e.g.:
_
| |
| |_
| |
| |_
| | The answer for this would be 6, 3 * 2, using col1 and col2.
Method 1: Using Stack: O(n)1) Create an empty stack. 2) Start from first bar, and do following for every bar ‘hist[i]’ where ‘i’ varies from 0 to n-1. ……a) If stack is empty or hist[i] is higher than the bar at top of stack, then push ‘i’ to stack. ……b) If this bar is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater. Let the removed bar be hist[tp]. Calculate area of rectangle with hist[tp] as smallest bar. For hist[tp], the ‘left index’ is previous (previous to tp) item in stack and ‘right index’ is ‘i’ (current index). 3) If the stack is not empty, then one by one remove all bars from stack and do step 2.b for every removed bar. Variation:
http://www.programcreek.com/2014/05/leetcode-maximal-rectangle-java/ C++ implementation http://tech-queries.blogspot.in/2011/03/maximum-area-rectangle-in-histogram.htmlMethod 2: Using Divide and Conquer : Range Minimum Query: O(nlogn)Java implementationhttp://www.programcreek.com/2014/05/leetcode-largest-rectangle-in-histogram-java/
http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
Saturday, March 10, 2012
Maximum possible sum of Non-consecutive elements
There is an integer array consisting positive numbers only. Find maximum possible sum of elements such that there are no 2 consecutive elements present in the sum.
Example: If given array is (6, 4, 2, 8, 1), the answer will be 14 (8+6). This is the maximum sum we can obtain without taking two consecutive elements.
Method 1:
Example: If given array is (6, 4, 2, 8, 1), the answer will be 14 (8+6). This is the maximum sum we can obtain without taking two consecutive elements.
Method 1:
To solve these type of question, first thing is to find a recurring relation. In this case our recurring relation will tell the max sum till a given length. It means that we will get the max sum for running length of the array. If we denote the ith element as T(i) and max sum till ith element of the array as S(i), then
S(i) = MAX {S(i-1), S(i-2) + T(i) }
S(-1) = 0;
if i=0, S(i) = T(0);
S(-1) = 0;
if i=0, S(i) = T(0);
Note: while developing this relationship, I assume array index is starting from 0.
This is a problem of Dynamic Programing and similar to longest increasing sub-sequence with the restriction that the sub-sequence cannot contain adjacent elements. The only difference is that in that problem, for an index j all the indices i, such that i < j were considered. But here we will consider i, such that i < j-1sum2 = 0; sum = sum1 = array[0]; for(i=1; i<len; i++) { sum = MAX(sum2 + array[i], sum1); sum2 = sum1; sum1 = sum;}Method 2:Dynamic Programming
The problem (and the longest sub-sequence as well) can be solved by modeling the array as a graph with an edge between (i,j) if j>i where j and i are the indices of the numbers but not when i = j-1 i.e. the two numbers are adjacent.
Pseudo Code:
Create an array L[N]
for j = 1 to N:
L(j) = a(j) + max{L(i) : (i; j) belongs to E}
return max L(j)
the base case will be when j=1
max{ L(i): (i,j) belongs to E}= 0
The solution has O(N2) time complexity and O(N) space complexity.
Elephant and Bananas
There are 2 cities A and B, 1000 Kms apart. We have 3000 bananas in city A and a elephant, which can carry max 1000 bananas at any given time. The elephant needs to eat a banana every 1 Km.
How many maximum number of bananas can be transferred to city B?
Note: The elephant cannot go without bananas.
Generalized Question:
There are 2 cities A and B, ‘D’ Km apart. We have ‘N’ bananas in city A and a elephant, which can carry max ‘C’ bananas at any given time. The elephant needs to eat ‘F’ banana every 1 Km.
Write a program that will compute ‘X’, the maximum amount of bananas that can be transported from city A to city B.
Strategy:
First, realize that if you take 1000 bananas and walk 1000 kilometers, you arrive with no banana at all. And the elephant is stuck in city B as there is no banana left for return journey. So the elephant needs to travel shorter distances or we can say that we need to subdivide distances.
How can we subdivide distances?
If we subdivide distances for each kilometer. Notice if elephant wants to shift all the bananas 1 km, you will loose 5 bananas every km. Lets see how.
- In 1st trip, elephant will pick 1000 bananas, eat one at 1 km mark, leave 998 bananas at 1 km mark and keep 1 with him for return journey.
- In 2nd trip, elephant will pick next 1000 bananas, eat one at 1 km mark, leave 998 bananas at 1 km mark and keep 1 with him for return journey.
- In 3rd trip, elephant will pick next 1000 bananas, eat one at 1 km mark, leave 999 bananas at 1 km mark. This time, he doesn’t need to keep anything for return journey.
So we transferred 2995 (998+998+999) to one km distance. This process (loosing 5 bananas per km) will continue until we reach a point where we have one less round trip. In this example, that transit point will come after 200 km, when we will have 2000 bananas left with remaining distance of 800 km.
Also note that the rate of consumption remains constant no matter how we subdivide the distance, as long as the number of trips required is the same.
So in place of shifting bananas every km, we can transferred the banans 200 kilometers at once.
- In 1st trip, elephant will pick 1000 bananas, eat 200 till 200 km mark, leave 600 bananas at 200 km mark and keep 200 with him for return journey.
- In 1st trip, elephant will pick next 1000 bananas, eat 200 till 200 km mark, leave 600 bananas at 200 km mark and keep 200 with him for return journey.
- In 3rd trip, elephant will pick next 1000 bananas, eat 200 till 200 km mark and leave 800 bananas at 200 km mark. This time, he doesn’t need to keep anything for return journey.
In this way, we are now left with 2000 bananas and 800 kms to go.
Now if you calculate, we will consume 3 bananas per km till next transit point. And what will be the next transit point. It should be when we are left with just 1000 bananas. This means that it will come after 333.33 (1000/3) kms.
Finally, we have 1000 bananas and 466.67 kms left. Since elephant can carry 1000 bananas at once, it will pick all 1000 bananas and reach the end with 533.33 (1000 - 466.67) bananas left. (Assumed that elephant eats the banana evenly in fractions of 1km as well.)
Generalized Answer:
So we have seen that if we have (Cn + y) where n is an integer and 0<y<=C at any point in time, our cost of walking each km is (2n+1). And from next transit point this rate will become (2n-1). We need to choose transit points such that we reduce one round time every time. In this manner, transit point will come when remaining bananas are integer multiple of C. Now you have a subset of bananas and distance left. You can apply the same process on remaining values.
This recursion will converge, when remaining bananas are less then or equal to C. (So that we can transfer all of them in single trip.)
Code:
double transferBananas(double N, double D, double C, double F) {
// base case: remaining bananas <= C,
// so carry all the bananas in one trip
// at this point if distance is more than N/F,
// elephant can never reach destination, return 0
if (N <= C) {
double nutsAtDestination = N - D*F;
return (nutsAtDestination >= 0.0) ?
nutsAtDestination : 0.0; // out of bananas!
}
// # trips you would travel back and forth
int numTrips = 2*(ceil(N/C) - 1) + 1;
// how many bananas you consume per km
double costPerKm = numTrips * F;
// remaining number of bananas after consumption, we want it
// as an integer multiple of C.
double remainingNuts = C*(ceil(N/C) - 1.0);
// this is the distance you are able to travel before you
// reach ONE LESS round trip fetching nuts
// derived from eq: N - costPerKm * traveled = remaining bananas
double traveled = (N - remainingNuts) / costPerKm;
// we are able to travel greater (or equal) than the remaining
// distance, so fetch the bananas right to the destination
if (traveled >= D)
return N - D*costPerKm;
// calculate recursively as we travel ONE less round trip now.
return transferBananas(remainingNuts, D-traveled, C, F);
}
mkdir Utility
How can we implement mkdir utility
Code:
Code:
int mkdirp(const char *dir, mode_t mode) { const char *p = dir + 1; while(*p) { if(*p == '/') { *((char*)p) = '\0'; if(mkdir(dir, mode) == -1 && errno != EEXIST) return -1; *((char*)p) = '/'; } p++; } if(*(p-1) != '/') if(mkdir(dir, mode) == -1 && errno != EEXIST) return -1; return 0; }
Friday, March 9, 2012
Honest Man and single Question
An honest man holds a card with one of the three possible numbers on it “1”, “2” or “3”. You can ask one question and the man allowed to answer only “Yes”,”No” and “I don’t know”. The honest man obviously never lies. Which question would you ask to say with 100% certainty which number is on the card the honest man holds?
Quadtree / Locate a tower
Discuss the Quadtree data structure and its application.
http://en.wikipedia.org/wiki/Quadtree
Question:
Given a city in form of a square. There are various cell towers located at various points in the square city (say (x,y)). The distribution
of towers is totally random. Now given an (x,y) point, design a data structure that will help you tell whether the cell tower is present at that
location or not.(of course optimal)
http://en.wikipedia.org/wiki/Quadtree
Question:
Given a city in form of a square. There are various cell towers located at various points in the square city (say (x,y)). The distribution
of towers is totally random. Now given an (x,y) point, design a data structure that will help you tell whether the cell tower is present at that
location or not.(of course optimal)
Quadtree
Discuss the Quadtree data structure and its application.
http://en.wikipedia.org/wiki/Quadtree
Question:
Given a city in form of a square. There are various cell towers located at various points in the square city (say (x,y)). The distribution
of towers is totally random. Now given an (x,y) point, design a data structure that will help you tell whether the cell tower is present at that
location or not.(of course optimal)
http://en.wikipedia.org/wiki/Quadtree
Question:
Given a city in form of a square. There are various cell towers located at various points in the square city (say (x,y)). The distribution
of towers is totally random. Now given an (x,y) point, design a data structure that will help you tell whether the cell tower is present at that
location or not.(of course optimal)
Polite Numbers
In number theory, a polite number is a positive integer that can be written as the sum of two or more consecutive positive integers.
The first few polite numbers are
3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17,...
for instance, 15 = 1 + 2 + 3 + 4 + 5 = 4 + 5 + 6 = 7 + 8. The number of ways that a number can be written as the sum of two or more consecutive numbers is its politeness. Any number that is a power of 2 cannot be written as the sum of two or more consecutive numbers; such a number has a politeness of 0, and is thus impolite.
write a program that calculates all the ways that a number can be written as the sum of two or more consecutive numbers and generate those sets.
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,sum,i,j,k,q=0,count=0;
scanf("%d",&n);
for( i=n/2+1; i > 1; i-- )
{
sum=i;
for( j=i-1; j > 0; j-- )
{
sum=sum+j;
if( sum==n )
{
count++;
if( j==1 ) q=1;
for( k=j; k <= i; k++ ) printf("%d ",k);
printf("\n");
break;
}
else if( sum > n ) break;
}
if( q ) break;
}
printf( "total no. of ways: %d",count );
system("pause");
return 0;
}
How many time function gets called
void foo1()
{
if(A < B)
Then { }
else
if(C < D)
then foo2()
A < B 25% of the times and C < D 75% of the times and foo1 () is called
5000 times
{
if(A < B)
Then { }
else
if(C < D)
then foo2()
}
How many time foo2 () would get called givenA < B 25% of the times and C < D 75% of the times and foo1 () is called
5000 times
Subscribe to:
Posts (Atom)