Saturday, March 27, 2010

Problems solvable using Hashtable

Hashtable are extremely useful data-structure as they provide storage and retrieval in O(1) time (amortized). Several problems of algorithms can be very efficiently solved using hashtables which otherwise turn out to be quite expensive. In this post, we consider some of these problems:

Problem 1: Remove duplicate elements from an unsorted array of size N.
Solution: show

Problem 2: Find intersection of K unsorted array of N elements each. Intersection consists of elements that appear in all the K arrays.

Problem 3: How to make a linked list support operations in O(1) time. The operations on linked list can be insertion after any arbitrary valued node, deletion of any arbitrary valued node.

Problem 4: Find all unique pairs of element in an array that sum to S. For ex. If array = {2,4,6,4,6} and S = 8 then answer is {<2,6>, <4,4>}

Problem 5: Consider an array containing unique elements. Find a triplet of elements in the array that sum to S (extension of problem 4). Can hashtables improve the running time of your algorithm.

Problem 6: Consider two strings of size M, N. Perform string matching in size O(M+N).

Problem 7: Find top K most frequent elements in an array of size N.

Problem 8: Given a file with N integers. Find top K most frequent integers. Assume N to be very large such that all the N numbers cannot fit into memory. Design for the worst case.

Solution: show

Friday, March 19, 2010

Dragon and Knight

Problem: A dragon and knight live on an island. This island has seven poisoned wells, numbered 1 to 7. If you drink from a well, you can only save yourself by drinking from a higher numbered well. Well 7 is located at the top of a high mountain, so only the dragon can reach it.

One day they decide that the island isn't big enough for the two of them, and they have a duel. Each of them brings a glass of water to the duel, they exchange glasses, and drink. After the duel, the knight lives and the dragon dies.

Why did the knight live? Why did the dragon die?

Solution: show

Problem: Now consider that Dragon and Knight are equally intelligent then who is expected to die.

Answer: Both survive the battle.

Solution: show

Thursday, March 18, 2010

Number and Age of David's Kids

Problem: The product of the ages of David's children is the square of the sum of their ages. David has less than eight children. None of his children have the same age. None of his children is more than 14 years old. All of his children is at least two years old. How many children does David have, and what are their ages?

Answer: (2,4,6,12)

Solution: show

Thursday, March 11, 2010

Largest Sum of Consecutive Numbers

Problem: Given an array of N integers (both positive and negative), find the sub-sequence with largest sum.

For ex: Let A = {1 2 -5 4 5 -1 2 -11} then largest sum is 10 (start index = 4, end index = 7)

Solution: show

Problem: Given an array of N integers (both positive and negative), find the sub-sequence with largest absolute sum. This problem differs from the one at the top as we want the absolute sum (taking mod)

For ex: Let A = {1 2 -5 4 5 -1 2 -11} then largest absolute sum is 11.

Solution: show

Wednesday, February 3, 2010

Polynomial Evaluation

Problem: Given a polynomial with degree bound of n=m^r. How do we evaluate the polynomial at n different points such that the polynomial can be recovered from these n points (i.e. the coefficients can be calculated back using the points).

Note: We do not want to recover the coefficients but cleverly choosing the points as that impacts the running time of the algorithm.

Solution: show

Sunday, February 15, 2009

Longest Monotone Sequence and Palindromes

Problem: Given an array of integers, find the longest subsequence of elements which monotonically increases. for ex. array = {1 4 8 2 5 7 3 4 6}, the longest subsequence = {1 2 3 4 6}

Solution: show

Problem: Given a string, find the longest size palindrome in the string. for ex. string = "aaabbccaccbaaa", solution = "bccaccb"

Solution: show

Saturday, January 31, 2009

Loops in Linked List

Problems with linked lists occur mainly while building or using a bad memory manager. Let us discuss two well known linked list problems.

Problem: Find if two linked lists short at some node. Find the node at which the two lists short.

Solution: show

Problem: A linked list might contain a loop. How do we detect existence of the loop and find the node from which loop starts. Propose an O(n) time algorithm that doesn't take extra space and doesn't modify the linked list.

Solution: show

Monty Hall Problem

This is a very famous probability problem. This problem illustrates that probability is sometimes more convincing than "what we perceive as obvious". I'll post another problem that defeats "obvious reasoning".

Monty Hall problem: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?

Solution: show

Red Green Cards: A box has three cards. First card has both sides green, second card has both sides red, third card has one side green and one side red. A card is picked at random and its one side is observed to be green. What is the probability that the other side of the card is also green.

Solution: show

Friday, January 30, 2009

Finding Second Smallest Element

Jargon: Order Statistics problem is to find the kth smallest element in an unsorted array A[1..n]. This problem can be solved in O(n) time in average case using randomized select algorithm or in O(n) time in worst case time using an algorithm that chooses the pivot element carefully.

Problem: How to find second smallest element in an array A[1..n] of size n. We would like to do in much less than 2n comparisons.

Answer: Time Complexity = n + lg n - 2

Solution: show

Friday, January 23, 2009

String Permutations

Printing all permutations of a string is a very common interview question. We'll discuss this problem and some interesting variations of it. The original problem of string permutation says, "print all permutations of a string". As an example, if the string is "abc" there are 6 permutations {abc, acb, bac, bca, cab, cba}. Assume that string contains no duplicate elements.

Solution: show

Lets us assume that string can contain duplicates. How do we print all non-redundant permutations of the string. For ex. If string is "abab" the permutations are {baab, abba, abab, baba, bbaa, aabb}

Solution: show

Some other constraints could be added to make the problem more interesting. One such constrain could be of partial ordering of characters. For Ex. 'a' should appear before 'c', and 'b' should appear before 'c' in all permutations. There can exist ordering that leads to no permutation of the string such as 'a' precedes 'b', 'b' precedes 'c', 'c' precedes 'a'. Additionally implementing the permutation algorithm in these cases require checking for ordering violation at each permutation level or just at the leaf of recursion, depending on whether checking for ordering violations is more costly or generating all permutations.

An interesting problem, that talks of special kind of ordering and can be very efficiently computed is as follows: Assume that the string is made up of equal number of '{' and '}'. You need to print all permutations of this string which could satisfy a C compiler i.e. an ending bracket is balanced by an opening bracket. For ex. for '{{}}' the permutations are [{{}}, {}{}].

Solution: show

Thursday, January 22, 2009

Party Friends

Problem: In any party, there exists two people with same number of friends. Is is true or false. Assume that party has more than one people.

Solution: show

Sunday, January 18, 2009

Innocents and Criminals: Finding Minority Entitybb

Problem: There are two types of people in a particular city, innocents and criminals. All you know is that innocents are in majority and would like to get rid of criminals and criminals would like to protect themselves from persecution. You can ask any number of questions, with yes/no type answer, from any person in the city. Propose an algorithm which requires asking the minimum number of questions.

Hint: Trivial solution requires asking O(n^2) questions. You can do it in less than 2n questions.

Solution: show

Friday, January 16, 2009

Finding First Non-Zero Digit of N Factorial

Problem: Find the first non-zero digit of N!. Assume N! to be extremely large.

Solution: show

Tuesday, January 13, 2009

Count Trailing Zeros in N Factorial

Problem: How many trailing zeros does N factorial contain, for ex. 5! = 120 so ans is 1. Propose an algorithm to count trailing zeros. Assume that N! is very large and does not fit into word size of the computer.

Solution: show

Monday, January 12, 2009

Picking k Elements Randomly from Stream

Problem: Previously, I posted the problem of picking an element randomly from finite stream with unknown size. This problem is generalization of the previous problem. Here, instead of picking an element randomly from the stream, we need to pick k elements randomly from the stream. We can assume that k is less than the actual size of the stream.

Solution: show

Wednesday, January 7, 2009

Optimal Coin Change Problem

Problem: Given an unlimited supply of coins of denominations C1, C2, ..., CN we wish to make change for a value V. Give an algorithm for producing change with minimum number of coins.

Hint: Depending on denomination of coins, we can either use fast greedy algorithm or dynamic programming.
Solution: show

Monday, January 5, 2009

Picking an Element Randomly from Stream

Problem: Given a finite stream of data elements, develop an algorithm to pick an element from the stream, randomly. Algorithm should guarantee that, every element of the stream has equal probability of getting picked. Additionally, we don't know the size of the stream until the stream actually finishes. We also have constant space, so all the elements of the stream can not be stored.

Hint: Once we see an element from the stream, we either store it or discard it with some probability, p.

Solution: show

Thursday, January 1, 2009

Generating Random Numbers

Problem: How to generate random integer between A and B, using an unbiased coin. For ex. If A = 3 and B = 6 then your algorithm should generate 3, 4, 5, 6 with equal probabilities.

Hint: The solution is non-deterministic.

Solution: show

Monday, December 22, 2008

Finding Majority Element

Jargon: Majority Element is an element of an array that occurs more than half the number of times in the array. Also, [x] means smallest integer greater than x.

Easy Problem: Assume that an integer array A[1..n] has a majority element and elements other than majority element are distinct. How to find majority element. What's the space and time complexity of the algorithm ?

Answer: Time Complexity = n/2(comparisons), Space Complexity = O(1)

Solution: show

Hard Problem: Assume that an integer array A[1..n] has a majority element and elements other than majority element need NOT be distinct. How to find majority element. What's the space and time complexity of the algorithm?

Answer: Time Complexity=n(comparison), Space Complexity=O(1).

Solution: show

Sunday, December 21, 2008

Airplane Seating Problem

Problem: 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 take 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?

Answer: 1/2

Solution: show

Saturday, December 20, 2008

Tic Tac Toe

Source: Petr Mitrichev's Blog

Problem: Two players are playing a game and take alternating turns. There are 9 cards on the table with numbers from 1 to 9. On each turn, a player picks one card from the table. The first player to have 3 cards that total a sum of 15 wins. If no one can after all cards are distributed, then it's a draw. Can you tell who wins, assume both players are highly and equally intelligent and what is the winning strategy ?

Answer: Draw

Solution: show

Tuesday, June 17, 2008

Math Magician

Source: International Maths Olympiad 2000

Problem: A magician has one hundred cards numbered 1 to 100. He puts them into three boxes, a red one, a white one and a blue one, such that each box contains atleast one card. A member of audience draws two cards from two different boxes and announces the sum of the number on those cards. Given this information magician locates the box from which no card has been drawn. How many ways are there to put the cards in the boxes so that the trick works.

Answer: 12

Solution: show

Friday, April 11, 2008

Unbiased Coin Tossing

Given a biased coin, with probability of Heads equal to x. How to do unbiased coin tossing?
show

Try to find the expected number of coin toss that would be required to call heads or tails?
show

What is the probability that there wont be any outcome in e coin tosses (expected outcomes)?
show

How can we improve on the expected number of coin tosses?
show

How much expected coin tosses are we doing in this case?
show

Sunday, December 9, 2007

Cards Shuffling Problem

A common algorithmic problem of interest is Cards Shuffling Problem, which states that given a deck of cards shuffle it randomly. A naive algorithm for this problem can be written as:
for i <- 0 to cardLen
  r = random (0, cardsLen)
  exchange card[i] <-> card[r]
Assume there are two cards, we can see 4 possible combination of (i,r) namely (0,0), (0,1), (1,0), (1,1) leading to 2^2 outputs. If the two cards are {1,2} then probability of {1,2} after shuffling is 1/2 and of {2,1} is 1/2. Even though this algorithm looks correct, it is logically incorrect.

Actually there is a little bug in the above algorithm because of which it's incorrect. For N cards it generates N^N permutations, where as a card shuffle must generate N! permutations. Also N^N is not divisible by N!, hence a bias. A small change in above code makes it correct:
for i <- 0 to cardLen
  r = random (i, cardsLen)
  exchange card[i] <-> card[r]
Generating r randomly from between i and cardsLen ensures that once a card is swapped to a given i, it's position is fixed. Above algorithm, with iteration on cards in reverse order is Knuth-Fisher-Yates shuffle algorithm.