Algorithm Questions
Algorithm Questions
Algorithm Questions
Thought Process:
Try the brute force method
Use data structures such as stack, queue, linked list, hashmap, binary tree
Try sorting to solve problems
Use << operator for multiplication
Sum of 1 to N integers is n (n+1)/2
To reverse digits, divide by 10 and print the modulus
Traverse lists with twice speed to detect loops
1. Given an array of characters which form a sentence of words, give an efficient algorithm to
reverse the order of the words (not characters) in it
Initialize two counters, front and back, to the end of the input string
While we haven’t reached the start of the string, move down front until we encounter a
space. Copy the part of the string from this point until back into the output.
Move back down by one character to account for the space. Set front to back, and repeat till
front is more than 0.
Alternative versions:
Push each word into a stack, checking for spaces. Then pop all of them and add spaces for each
word.
2. Given an array of size N in which every number is between 1 and N, determine if there are any
duplicates in it. You are allowed to destroy the array if you like
Sort the array in ascending order and then run through one pass of the array comparing of
any element is equal to the next one.
Create a bit vector/array of size N and set the bit of the index to true when the number is
encountered. If you read a bit which is already set, then duplicates are present. (This will
not work for any arbitrary numbers, other than 1 to N)
4. A real life problem - A square picture is cut into 16 sqaures and they are shuffled. Write a
program to rearrange the 16 squares to get the original big square.
This to me sounds like a sorting problem, you have something that is out of order and you pust put it in
order. Assuming you just have some way of knowing wheter a guess is correct or not, for example:
then you basically have to do an insert sort like this (because there is no partial ordering to exploit for a
better algo like heapsort) which runs in O(n^2):
5. Give me an algorithm and C code to find the subarray with the largest sum given an array
containing both positive and negative integers
Keep two sums – Sum until here and subarraySum
For each element in the array
Add the element to sumuntilhere. If sum is greater than subarraySum, then set subArraySum =
sumUntilHere.
If sumUntilHere is –ve number, then set sumUntilHereto 0
7. Write a function that computes the nth number in the Fibonacci sequence
The iterative version maintains variables to hold the last two values in the Fibonacci sequence,
and uses them to compute the next value. Again, boundary conditions and inputs are checked.
The 0th number in the Fibonacci sequence is defined as 0. The first number in the sequence is 1.
Return -1 if a negative number is passed.
The recursive version of the Fibonacci function works correctly, but is considerably more
expensive than the iterative version. There are, however, other ways to write this function
recursively in C that are not as expensive. For instance, you could maintain static variables or
create a struct to hold previously computed results.
9. Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and
finally create a clean S2 with the relevant characters deleted
We could iterate over the remove string and for each character, remove all occurrences from the
input string. Give input string of length ‘n’ and remove string of length ‘m’, this brute force
algorithm would lead to a complexity of O(mn).
Here’s a more efficient algorithm. Iterate over the remove string, and store each character in an
array. Later as we iterate over the input string, we lookup this array, and if that character is
present in this array, then we remove it from the input. This algorithm works if the array lookup
is a constant time operation. The net complexity of this algorithm would be O(m+n), much better
than the O(mn) brute force algorithm described earlier.
The detailed steps are as follows:
Create an array ‘flags‘ of 256 characters. Entries in this array serve as flags denoting whether
character ‘i’ is to be removed or not. Initialize all elements of this array to false.
Iterate over the remove string. For each character i in the string, mark flags[i] as true
Iterate over the input string. For each character in the string, if flags[i] is true, then copy it to
an output array. Otherwise continue to the next character.
At the end of this iteration, the output array will contain all characters of input minus all
letters of remove.
10. Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5,
5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9)
Compare element to next element and if not equal, extract it out.
12. Give a very good method to count the number of ones in a 32 bit number. (caution: looping
through testing each bit is not a solution).
Run a iterative loop.
While n,
Count = count + n & 0x1u;
N >> 1;
Alternative:
While (n)
Count++;
N = n & (n – 1);
13. How can you print singly linked list in reverse order? (it's a huge list and you cant use recursion)
Reverse the pointers till you reach the end and print-and-reverse as you return
while ( loop through list )
{
*List = temp1; //set the head to last node
temp2= temp1->pNext; // save the next ptr in temp2
temp1->pNext = temp3; // change next to privous
temp3 = temp1;
14. How can you find out if there is a loop in a very long list?
One possible answer is to add a flag to each element of the list. You could then traverse the list,
starting at the head and tagging each element as you encounter it. If you ever encountered an element
that was already tagged, you would know that you had already visited it and that there existed a loop
in the linked list.
Start with two pointers ptr1 and ptr2.
Traverse the linked list with ptr1 moving twice as fast as ptr2 (for every two elements
that ptr1 advances within the list, advance ptr2 by one element).
Stop when ptr1 reaches the end of the list, or when ptr1 = ptr2.
If ptr1 and ptr2 are ever equal, then there must be a loop in the linked list. If the linked list has no
loops, ptr1 should reach the end of the linked list ahead of ptr2
15. You are given a list of n numbers from 1 to n-1, with one of the numbers repeated. Devise a
method to determine which number is repeated
The sum of the numbers 1 to n-1 is (n)(n-1)/2. Add the numbers on the list, and subtract (n)(n-1)/2.
The result is the number that has been repeated
19. Given an array of characters. How would you reverse it. ? How would you reverse it without
using indexing in the array
20. Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if
there is any element in the second list that is an element of the first list (fixed list)
Put the first list in a hashmap, with the key as the number and the value as -1. For each number
in the second list, call contains in the hashmap.
21. How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant
amount of memory
22. Implement an algorithm to reverse a doubly linked list
23. Write a function and the node data structure to visit all of the nodes in a binary tree. (Breadth
first traversal)
Level by level traversal is known as Breadth-first traversal. Using a Queue is the proper way to do this. If you
wanted to do a depth first traversal you would use a stack.
First, the root (1) would be enqueued. The loop is then entered. first item in queue (1) is dequeued and
printed. 1's children are enqueued from left to right, the queue now contains {2, 3} back to start of loop first
item in queue (2) is dequeued and printed 2's children are enqueued form left to right, the queue now contains
{3, 4} back to start of loop
38. You have an unsorted array of some million random positive integers with no duplicates. Find two
integers from this array which add up to 50
Search for values less than or equal to 50. Suppose your value read is x. If x<= 50, store (key:50,value:x-50) into a
hash table.
Suppose you have the following array..70 60 20 35 90 30 20
for 20, the table will have (20,30).
table.getValues(20) gives you 30. table.getValue(30) is null.
for 35, insert (35,15)
table.getValues(35) gives you 15. table.getValue(15) is null.
for 30, insert (30,20)
table.getValue(30) gives you 20.
table.getValue(20) gives you 30. These give you 50.
39. Given a link list of chars find if the string is a palindrome w/o using extra memory
Reverse everything from the middle to the end of the linked list O(N/2).
Use two pointers. One pointing at the beginning and one at the middle then start comparing as
you are incrementing. If they are not equal, then it's not a palindrome. O(N/2).
Then reverse the linked list from the middle to the end again. This would put the linked list back
to its original state. O(N/2)
40. Write a function to find the nth item from the end of a linked list in a single pass.
1) have two ptrs. F_Ptr & S_Ptr.
2) Let the ptrs point to the START.
3) Take n as the offset.
4) Start traversing the S_Ptr after the F_Ptr after n.
Now when F_Ptr = Null, S_Ptr is just trailing behind right! it will be pointing to the n'th element
from the last.
41.
42.
2. How many points are there on the globe where by walking one mile south, one mile east and
one mile north you reach the place where you started
The answer is "many points". The set of such points is given as {North pole, special circle}.
From north pole, walking one mile south followed by one mile east still keeps you one mile south
of North pole.
The special circle consists of a set of points defined as follows. Let's say you were to locate a spot
near the South Pole where the circular distance "around" the Earth's North-South axis is 1 mile. The
path of such a journey would create a circle with a radius of approximately 840.8 feet (because
C=2.r.pi). Call this point X. Now consider another point Y one mile north of X. The special circle is
the circular path around North-South axis going through Y. If you begin you journey from any
point (say Y1) on this special circle, and travel one mile south, you get to a point (say X1) on the
circle of point X. Now one mile east will bring you back to X1, because circumference of circle of X
is 1 mile. Then one mile North brings you back to Y1. (Answer supplied by Kristie Boman)
3. There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner..
what is the probability that they don't collide
All three should move in the same direction - clockwise or anticlockwise. Probability is 1/4.
Total no. of movements: 8 A->B, B->C, C->A A->B, B->A, C->A A->B, B->A, C->B A->B, B->C,
C->B A->C, B->C, C->A A->C, B->A, C->A A->C, B->A, C->B A->C, B->C, C->B
Non-colliding movements: 2 A->B, B->C, C->A A->C, B->A, C->B
(i.e. the all ants move either in the clockwise or anti-clockwise direction at the same time)
P(not colliding) = 2/8 = 0.25
4. If you are on a boat and you throw out a suitcase, Will the level of water increase
5. There are 4 men who want to cross a bridge. They all begin on the same side. You have 17
minutes to get all of them across to the other side. It is night. There is one flashlight. A
maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people,
must have the flashlight with them. The flashlight must be walked back and forth, it cannot be
thrown, etc. Each man walks at a different speed. A pair must walk together at the rate of the
slower mans pace.
Man 1 (1 min), Man 2 (2 min), Man 3 (5 min), Man 4 (10 min)
1 and 2 cross together. 1 comes back. then 3 and 4 cross. 2 comes back. then 1 and 2 cross. Total time
is 2+1+10+2+2 = 17
6. You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in
one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the
contaminated pills in just one measurement?
Take one pill from first, two from second, three from third and so on. Total pills are n(n+1)/2 and
should weigh 10n(n+1)/2. If it weighs x gm less than that then the x'th jar is contaminated, since we
took x pills from that jar which weighed 1 gm less.
7. One train leaves Los Angeles at 15 MPH heading for New York. Another train leaves from New
York at 20mph heading for Los Angeles on the same track. If a bird, flying at 25mph, leaves
from Los Angeles at the same time as the train and flies back and forth between the two trains
until they collide, how far will the bird have traveled?
If distance is X miles between NY and LA, then it takes X/(15+20) hours for the trains to collide,
and bird will have travelled 25X/(15+20) = 5X/7 miles in that time.
8. Imagine that you have 26 constants, labelled A through Z. Each constant is assigned a value in
the following way: A = 1; the rest of the values equal their position in the alphabet (B
corresponds to the second position so it equals 2, C = 3, etc.) raised to the power of the
preceeding constant value. So, B = 2 ^ (A's value), or B = 2^1 = 2. C = 3^2 = 9. D = 4^9, etc., etc.
Find the exact numerical value to the following equation:
(X - A) * (X - B) * (X - C) * ... * (X - Y) * (X - Z)
Answer is 0, because (X-X) is present in the product
9. You have 12 balls. All of them are identical except one, which is either heavier or lighter than
the rest - it is either hollow while the rest are solid, or solid while the rest are hollow. You have
a simple two-armed scale, and are permitted three weighings. Can you identify the odd ball,
and determine whether it is hollow or solid.
10. Write an efficient algo and C code to shuffle a pack of cards.. this one was a feedback process
until we came up with one with no extra storage.
11. A real life problem - A square picture is cut into 16 sqaures and they are shuffled. Write a
program to rearrange the 16 squares to get the original big square.
12. Given a maze with cheese at one place and a mouse at some entrance, write a program to direct
the mouse to cheese correctly. (Assume there is a path). Following primitives are given:
moveforward, turnright, turnleft, iswall?, ischeese?, eatcheese.
13. Give an algorithm that calculates the distance between two text strings (only operations you can
have are: delete, add, and change, one by one)
14. Given the definition of a sequence (5 4 7 6 is, but 1 2 4 5 is not), write an algorithm to check if an
arbitrary array is a sequence or not. Once I figured out a solution, I was asked to do a space and
time complexity analysis
15. Given the time, devise an algorithm to calculate the angle between the hour and minute hands
of an analog clock.
The important realization for this problem is that the hour hand is always moving. In other
words, at 1:30, the hour hand is halfway between 1 and 2. Once you remember that, this
problem is fairly straightforward. Assuming you don't care whether the function returns the
shorter or larger angle, Example 4 shows a solution to this problem
16. Given an eight-bit bitmap graphics file, devise an algorithm to convert the file into a two-bit
ASCII approximation
17. Given a history of URLs, how would you determine if a particular URL had been seen before?
18. Given ships travel between points A and B, one every hour leaving from both ends
(simultaneously), how many ships are required (minimum), if the journey takes 1hr 40 mts.
How many ships does each ship encounter in its journey, and at what times?
4, 3 at 20 mts, 50 mts and 80 mts.
19. Given a number, describe an algorithm to find the next number which is prime.
20. How many golf balls can fit in a school bus?
21. Every man in a village of 100 married couples has cheated on his wife. Every wife in the village
instantly knows when a man other than her husband has cheated, but does not know when her
own husband has. The village has a law that does not allow for adultery. Any wife who can
prove that her husband is unfaithful must kill him that very day. The women of the village
would never disobey this law. One day, the queen of the village visits and announces that at
least one husband has been unfaithful. What happens?
22. In a country in which people only want boys, every family continues to have children until they
have a boy. if they have a girl, they have another child. if they have a boy, they stop. what is the
proportion of boys to girls in the country?
Pretty simple. Half the couples have boys first, and stop. The rest have a girl. Of those, half have a boy
second, and so on.
So suppose there are N couples. There will be N boys. There will be an "infinite" sum of girls equal
to N/2 + N/4 + N/8 + ... As any college math student knows, this sum adds up to N. Therefore, the
proportion of boys to girls will be pretty close to 1:1, with perhaps a few more boys than girls
because the sum isn't actually infinite.
23. If the probability of observing a car in 30 minutes on a highway is 0.95, what is the probability
of observing a car in 10 minutes (assuming constant default probability)?
24. If you look at a clock and the time is 3:15, what is the angle between the hour and the minute
hands? (The answer to this is not zero!)
25. You are at a party with a friend and 10 people are present including you and the friend. your
friend makes you a wager that for every person you find that has the same birthday as you, you
get $1; for every person he finds that does not have the same birthday as you, he gets $2. would
you accept the wager?
26. You have five pirates, ranked from 5 to 1 in descending order. The top pirate has the right to
propose how 100 gold coins should be divided among them. But the others get to vote on his
plan, and if fewer than half agree with him, he gets killed. How should he allocate the gold in
order to maximize his share but live to enjoy it? (Hint: One pirate ends up with 98 percent of the
gold.)
27. You’ve got a 10 x 10 x 10 cube made up
of 1 x 1 x 1 smaller cubes. The outside of
the larger cube is completely painted red.
On how many of the smaller cubes is there
any red paint?
28. First, note that the larger cube is made up of 1000 smaller cubes. The easiest way to think about this is how
many cubes are NOT painted? 8 x 8 x 8 inner cubes are not painted which equals 512 cubes. Therefore, 1000
– 512 = 488 cubes that have some paint. Alternatively, we can calculate this by saying that two 10 x 10 sides
are painted (200) plus two 10 x 8 sides (160) plus two 8 x 8 sides (128). 200 + 160 + 128 = 488.
29.
30.
1. Introduction
The technical interview is perhaps the most intimidating and mysterious event that job hunters
experience in the quest for that "killer offer." The rigor and format of the technical interview
varies from one company to the next, but there are some fundamental similarities. An interviewer
presents you with a problem to be solved. The interviewer may leave the room and give you
some time to work the solution out before returning. Or the interviewer may wait patiently while
you study the problem and figure it out. The interviewer may even start quizzing you right away
about aspects of the problem and approaches to solving it. Some of these problems can appear
quite challenging, especially if you've never been through a technical interview before. To make
matters worse, simply getting the answer to the problem may not be enough to land the job. On
the other hand, getting the correct answer may not even be necessary. What is an interviewer
looking for in candidates during the technical interview? Interviewers recognize that this setting
is, by its very nature, stressful. Otherwise competent candidates may be completely stumped by
an interview problem only to discover an elegant, simple solution later that night. Interviewers
may be interested in seeing how you work under stressful situations or how well you adapt. It is
worth noting that interviewers are more interested in seeing how you work than seeing whether
you can come up with the correct answer. In this article, I will deal with both how you can better
showcase your skills and experience, and what kinds of problems you can expect to be asked.