Tag Archives: brain teaser

C++ interviews questions on algorithm like Fibonacci,brain teaser, probability

Mutable
What is the (C++) keyword mutable used for? Give an example.

Algorithm:
C++ contains numerous algorithm functions that accept function objects as a parameter.

Referring to the statement above, which one of the following is another name for function objects?
Choice 1

Use Case
Choice 2

Operators
Choice 3

Actions
Choice 4

Iterators
Choice 5

Predicates
The answer is Iterators
I thought it was functors, but who cares for such stupid questions?

implement a function to_dollar(int a) that takes in an int, say ‘10200’, and prints $10,200.
this is the solution not only for the intergers but also for double values (using cents)

public class ConvertDolar {
public static void main(String[] args) {
double amount = 1234567.99222229292929d;
System.out.println(prinDollar(amount));
}

static String prinDollar(double number) {
int cents = (int) (number % 1 * 100); // saving the cents
int num = (int) number; // eliminating the cents
StringBuffer dollar = new StringBuffer();
int count = 0;
while (num > 0) {
if (count == 3) {
dollar.append(“,”);
count = 1;
} else {
count++;
}
dollar.append(num % 10);
num /= 10;
}
return “$” + dollar.reverse().toString() + “.” + (cents < 10 ? "0" + cents : cents); } } Result: $1,234,567.99 Reply to Comment intelliplay on March 26, 2010 |Edit | Edit And here is one using the STL: #include
#include
#include
#include

using namespace std;

void to_dollar(int a);

int main()
{
int userInput;

cout << "Please enter an integer-:> ” << endl; cin >> userInput;
to_dollar(userInput);

return (0);
}

void to_dollar(int a)
{
stringstream inString;
string strTemp;
long double intTemp;

inString << a; // convert integer to string for easier handling inString.str(inString.str()+"00"); // concatenate two zeos to denote currency fractional digits inString >> intTemp; // convert back to integer

locale loc(“english_USA”); // set the locale
cout.imbue(loc);

cout.setf(cout.flags() | ios::showbase); // turn on currency sign printing
const money_put& m_put = use_facet >(loc); // get the money_put facet
m_put.put(cout, false, cout, ‘ ‘, intTemp); // show me the money. Note to use fractionally adjusted value.
cout << endl; } Oh, I seem to have messed up the spacing. Hope you can still read the code. This is my first post so... Let me know your comments. With the STL, the solution is really simple. Just a matter of knowing which library objects/functions to call. int my_number_format(int num) { int idx; char buffer[64]; idx = sizeof(buffer)-1; buffer[idx--] = 0; // end zero int count = 0; while (num > 0) {
if (0 == idx)
return -1;
if (count > 2) {
buffer[idx–] = ‘,’;
if (0 == idx)
return -1;
count = 0;
}
count++;
buffer[idx–] = ‘0’+(num % 10);
num /= 10;
}

buffer[idx] = ‘$’; // currency sign
return printf(“%s\n”, &buffer[idx]);
}
Reply to Comment
dullboy on April 21, 2010 |Edit | Edit

We may code it using stack

void _dollar(int x)
{
char s[64];
stack stk;

*s = ‘\0′;

while(x/1000 > 0)
{
if(!stk.isFull())
stk.push(x%1000);

x = x/1000;
}
if(!stk.isFull())
stk.push(x);

while(!stk.isEmpty())
{
sprintf(s, “%s%d,”, s, stk.pop());
}

int i = 0;
while(s[i++]!=’\0’);

*(s+i-2) = ‘$’;

printf(s);
}

int main()
{
_dollar(12800900);
return 0;
}

Class Design:
Using char*,
design an CString implementation.
List the functions that are supported,
Implementation of “operator=”.
1

You simply count the number “l”s in the paragraph.

“iving numbers 2,3,5,7,11 ,
1.multiply each number by 2,
2.if the result is bigger than 25 , then go to next step, otherwise repeat the 1st step.
3. multipy the result by 3.
4. add XX
5. divide with XX.

question: which number will produce maximun output
2 will.
Steps 3,4,5 are useless, just check steps 1 and 2.
I believe the correct answer is 3 because 3*2*2*2 = 24 so *2 = 48 while 2*2*2*2*2 = 32…
yes, the correct answer is 3.
Given deck of cards + joker, what is the probability you see the joker before all four aces?
consider only 5 cards, 4aces and 1 joker

now there are 5 positions – – – – – and the joker can take any of the 4 positions except the last one, so the P = 4! / 5!

Suppose there is a rectangular map where you can only travel up or right to go from a start location in the bottom left corner to the top right corner, and each move is discrete. Write a program that prints all possible solutions to get from the start to finish.
Suppose you need 5 R (right moves) and 5 T (top moves) to reach the upper right corner. Then you can do a permutation of the string, “RRRRRTTTTT” to get all the possible paths.

give you 3L bottle and 5L bottle, to get 4L water.
1. Fill the 5L can.
2. Pour the 5L in 3L.
3. Empty 3L.
4. So, 2 litres remaining in 5L.
5. Pour 2 litres from 5L to 3L.
6. Fill 5L.
7. Pour 5L into 3L, so that only 1 litres goes from the 5L into 3L and 5L now has 4 litres.
by Anil:
Fill 3L and empty it by pouring all in 5L bucket.
Fill 3L again and pour water into 5L from 3L. 3L will be left with 1 litre of water.
Empty 5L and put the 1L into it. Again fill 3L and pour it into 5L.
Total water in 5L will be 4 litres.

“Given 5 prices of a share for 5 days i.e. from Monday-Friday share prices for a perticular share are $1, $4, $5, $2, $3. Find the max profit you could make in a given week. You are not allowd to do multiple trading in a day and its not mandatory to do trading on each day. Write a C code for this.”
“How would you reverse the digits of an integer? (say from 123456 to 654321)”
“string manipulation”

“Given a sequence of shape rotation steps, find the missing step that would transform the shape from initial to final phase.”
Write a function to convert First Name, Last Name to Last Name, First Name.

You can do it inplace my swapping the last and first char and then shifting the start index and rest string by one place each time.

If I arrange the numbers 1 to 100 in a random order and remove one number from this group – give me an algorithm to find the missing number?
Describe how you would rearrange a word and then a sentence in C!
Count # of times character ‘s’ appear in one paragraph
“Count the number of i’s in the paragraph.”
he wanted me to speak a lookup table
Suppose there is a rectangular map where you can only travel up or right to go from a start location in the bottom left corner to the top right corner, and each move is discrete. Write a program that prints all possible solutions to get from the start to finish.
Suppose you need 5 R (right moves) and 5 T (top moves) to reach the upper right corner. Then you can do a permutation of the string, “RRRRRTTTTT” to get all the possible paths.

give you 3L bottle and 5L bottle, to get 4L water.
1. Fill the 5L can.
2. Pour the 5L in 3L.
3. Empty 3L.
4. So, 2 litres remaining in 5L.
5. Pour 2 litres from 5L to 3L.
6. Fill 5L.
7. Pour 5L into 3L, so that only 1 litres goes from the 5L into 3L and 5L now has 4 litres.
by Anil:
Fill 3L and empty it by pouring all in 5L bucket.
Fill 3L again and pour water into 5L from 3L. 3L will be left with 1 litre of water.
Empty 5L and put the 1L into it. Again fill 3L and pour it into 5L.
Total water in 5L will be 4 litres.

“Given 5 prices of a share for 5 days i.e. from Monday-Friday share prices for a perticular share are $1, $4, $5, $2, $3. Find the max profit you could make in a given week. You are not allowd to do multiple trading in a day and its not mandatory to do trading on each day. Write a C code for this.”
“How would you reverse the digits of an integer? (say from 123456 to 654321)”
“string manipulation”

“Given a sequence of shape rotation steps, find the missing step that would transform the shape from initial to final phase.”
Write a function to convert First Name, Last Name to Last Name, First Name.

You can do it inplace my swapping the last and first char and then shifting the start index and rest string by one place each time.

If I arrange the numbers 1 to 100 in a random order and remove one number from this group – give me an algorithm to find the missing number?
Describe how you would rearrange a word and then a sentence in C!
Count # of times character ‘s’ appear in one paragraph
“Count the number of i’s in the paragraph.”
he wanted me to speak a lookup table
Given deck of cards + joker, what is the probability you see the joker before all four aces?
consider only 5 cards, 4aces and 1 joker

now there are 5 positions – – – – – and the joker can take any of the 4 positions except the last one, so the P = 4! / 5!

I think the question is asked differently. the probability of seeing the joker after all 4 aces is 1/5. So the probability of seeing the joker in any other place is 1 – (1/5) = 4/5 which should be the right answer
Split the horses into 5 groups and race each of the 5 groups (5 races). After that, you have the horse placements for each group. I laid it out like this:

A B C D E
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

Five columns, one for each group of horses, lettered A-E. Each number represents a horse… say horse A1 is the one that came in first place from group A, C2 is the horse that placed 2nd in group C, and so on.

You can eliminate all 4’s and 5’s from the chart, since we know that there are at least 3 horses that are faster for each 4th and 5th place horse.

A B C D E
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3

Now race all the 1’s (race #6). This will give you the fastest horse from the initial 25. But what about 2nd and 3rd place?

Let’s say A1 got 1st, B1 got 2nd, C1 got 3rd, D1 got 4th and E1 placed last in race #6. A1 is definitely the fastest horse, but B1 may or may not be. Horse A2 can still be faster than B1- we have never raced them together before.

Approach it this way: which horses can we eliminate? Find all horses that we know have at least 3 horses faster than them. We can eliminate D1 and E1, because we know that A1, B1, and C1 are all faster than them. We can also eliminate all other horses in columns D and E below them. We can’t eliminate C1, but we can eliminate C2 and C3. We also eliminate B3, since B2, B1, and A1 were all proven to be faster.

A B C D E
1* 1 1
2 2
3

The only horses left to race are A2, A3, B1, B2, and C1. (Race #7). The 2nd and 3rd place finishers are then 2nd and 3rd fastest from the original 25.

A Fibonacci spiral created by drawing arcs connecting the opposite corners of squares in the Fibonacci tiling; this one uses squares of sizes 1, 1, 2, 3, 5, 8, 13, 21, and 34; see Golden spiral
In mathematics, the Fibonacci numbers are the numbers in the following sequence:

By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation

with seed values

: Describe how to implement a queue out of stacks. (no coding, just thought process)

Implementing queue using 2 stacks

You have three lightbulbs in one room and three switches in another room. You can play with the switches as much as you want to, but you can only visit the room withthe bulbs once. How can you determine which switch corresponds to which bulb?
Turn on two switches. Wait a while and turn off one of them. The bulbs will either be on, off, or off and still hot.
1. Turn on the 1st switch for sometime. Then turn it off. The bulb corresponding to this switch will be hot.
2. Turn on 2nd switch and then go to the room.
3. The bulb that will be on will correspond to the 2nd switch. The other 2 bulbs will be off. The one that will be hot among the 2 off bulbs will correspond to the first switch. And the other off bulb will correspond to the 3rd switch.
There are 20 floors in a building. I step into the elevator with 5 other people. What is the probability that I do not have to press my button? (ie someone else chooses the same floor as me)
Note the technicality that in a 20 floor building, people getting on the elevator have only 19 choices since they won’t get on the elevator to go to the current floor.

The number of combinations of floor choices for the 5 other people is

19^5

The number of these combinations that don’t include your choice is

18^5 (i.e. the number of combinations of the remaining 18 floors)

So the probability that someone will choose your floor is

1 – ( 18^5 / 19^5 ) ˜ .24 = 24%

STL:
What is the difference between a C++ array and an STL array type
one is a class and the other is just a memory block of a data type?

Specific questions on map functions (STL), on how to remove all elements that were <= 50 know STL , tell me what kind of containers are available , complexities of each ? how would you know if a map is corrupted? How about catching memory exception? if it's not sorted anymore. Why would map be sorted in the first place ? Its a key value association

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Programmer interview questions brain teaser and probability

Programmer interview questions brain teaser and probability
Probability/Brain Teaser
You have 4 bottles each containing pills that weigh 10 grams each and 1 bottle containing pills that weigh 9 grams each, How would you find out the lighter of the 5 bottles by using a Digital Scale just Once?

Hint: He asked to open the bottles and take the pills out, and also grouping them wont work.
Label the 4 bottles A,B,C and D. Take 1 tablet from A , 2 from B , 3 from C and 4 from D and weigh it. if the weight is 99 the lighter bottle is A , if its 98 its from B and so on..
Genius, I can’t come up with this bright answer
As there are 5 bottles instead of 4, so

Label the 5 bottles A,B,C,D and E. Take 1 tablet from A , 2 from B , 3 from C, 4 from D and 5 from E and weigh it. if the weight is 149 the lighter bottle is A , if its 148 its from B and so on..
what about the 5th bottle?
If the weight is 100, then it’s in the 5th.
I misread the question as 4 bottles.. Anyways as many would have guessed,the idea still remains the same as the answer I had first posted..

🙂

one q was about calculating the number of rabbits when each generate 2M and 2 F offsprings
Also few questions involved finding patterns after certain rotations. One was a comprehension question and one was on graph theory .
The online assessment test was sent to me a week after I submitted my resume. The questions consisted of analytical reasoning, process mapping, abstract thinking etc. There were a lot of questions involving turning shapes clockwise or counter clockwise in different angles , some other questions involved recognizing type of flowchart. I had one question to count the number of appearances of an alphabet and one counting written number denominations. Each questions took 3minutes. It is fairly okay and I was selected to go forward.

It takes 15 minutes to fill a tank from a tap and 40 minutes to enpty it from the sink . If both are open how long will it take to fill the tank . Capacity of tank is 400 gallons
Could probably assume that the tap flows at a constant volume per time. Can’t assume that for emptying it. That will depend on the water pressure at the outlet, which is dependent upon the geometry of the tank.

Since its a simple math problem, other parameter are supposed to be constant.
Tank capacity doesn’t matter. x/15 – x/40 = 1
i.e. x=24
multiply by 2
if less than 25 go back, else continue
divide by 3
subract 4
multiply by 3

Which will produce the greater result?

A. 2
B. 3
C. 4
D. 5
B. 3
How would you find the largest value in an array?
You will have to use a temp variable. Assign temp to -999 (assuming there is no negative 999 in the data set or use ascii for this. I am not familiar with ascii conversions). Go through the array comparing each variable with the temp. If array variable is higher, store it into temp. Keep doing this till you reach the end. Your temp has the largest value now.

Pramod’s answer is almost perfect. I would make one change: assign temp the first value of the array.
For a non- programmer, how would you search a linear array for a set of information?

It’s not 8, it’s 7. First group the horses into sets of 5. We can eliminate finishers 4 and 5 in each race. Now race the fastest from each previous heat against each other. Now we have used 6 races so far. We can eliminate all of the horses from the 4th and 5th place horses groups, all but the fastest from the 3rd, the fastest and the runner up from the 2nd and none of the remaining group from the 1st.

Thus we have 3 horses from the 1st place finishers heat, 2 from the 2nd, and 1 from the 3rd. However, we already know that the fastest of the 5 winners is the fastest overall and is in, leaving us with only 5 horses not eliminated.

Race them against each other and take the top 2. You have only used 7 races.
1,2,3,5,7…. what will be the next number in series
11…they are all prime numbers
1 is not prime. Question seems wrong
What if we view this series of number as “non-composite”? then 11 will be valid
How will you find out what has happened in the network if – initially the network speed is 10Mbps but suddenly it drops down to 10Kbps.
I told him we can use traceroute and explained how we can use it. He seemed satisfied with the answer.

They also asked those abstract problem solving type questions. I can’t remember exactly but he mentioned one about two pieces of string of variable cross sectional area and you have to burn them and you have to make it time something. The answer involves lighting both at one end at the start and then lighing the other end of the longer one when the first one finishes. When the long one burns to the middle it’s the time you want.
….
I guess the question you were referring to was:

You have 2 candles that burn from top to bottom in exactly 1 hr. How will you measure 45 minutes?

Ans: Burn one at both ends and the other at the top simultaneously. The first will burn off in 30 minutes and by that time, the second would be half burnt. When 1st is all gone, light the other end of 2nd too and it’ll take 15 more minutes to burn totally. So total = 30 + 15 = 45
the classic question about two eggs dropping from a 100-floor building

How would you structure the data inside a cell phone (i.e. contacts, emails, sms, etc)?

Books order on a shelf with some specific rules such as : Book A has to be in the middle of Book C and Book D. Which order listed below is not possible?

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!