Popular Posts

Showing posts with label Algos. Show all posts
Showing posts with label Algos. Show all posts

Monday, February 13, 2012

Maximum number of nested envelopes

You are given an unlimited number of each of n different types of envelopes. The dimensions of envelope type i are xi × yi. In nesting envelopes inside one another, you can place envelope A inside envelope B if and only if the dimensions A are strictly smaller than the dimensions of B.


Algorithm to determine the largest number of envelopes that can be nested inside one another.?

Solution:
1. Sort all the xi's in ascending order -> nlog(n)
2. Then find the longest increasing sequence of yi's -> nlog(n) 
3. complexity will be nlog(n).

Wednesday, July 27, 2011

Nuts and Bolts problem

You are given a collection of nuts of different size and corresponding bolts. You can choose any nut & any bolt together, from which you can determine whether the nut is larger than bolt, smaller than bolt or matches the bolt exactly. However there is no way to compare two nuts together or two bolts together. Suggest an algorithm to match each bolt to its matching nut.


http://tech-queries.blogspot.com/2011/01/nuts-and-bolts-algorithm.html
Refer : http://valis.cs.uiuc.edu/~sariel/teach/2004/b/webpage/lec/15_rand_notes.pdf

Sunday, May 29, 2011

PaintFill function

Implement the “paint fill” function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color.


First, let’s visualize how this method works. When we call Paint Fill (eg, “click” paint fill in the image editing application) on, say, a green pixel, we want to “bleed” outwards. Pixel by pixel, we expand outwards calling PaintFill on the surrounding pixel. When we hit a pixel that is not green, we stop. Surrounding green pixels may still be painted if they are touched by another Paint Fill operation.
We can implement this algorithm recursively:
enum Color {
Black, White, Red, Yellow, Green
}
boolean PaintFill(Color[][] screen, int x, int y, Color ocolor,
Color ncolor) {
if (x < 0 || x >= screen[0].length ||
y < 0 || y >= screen.length) {
return false;
}
if (screen[y][x] == ocolor) {
screen[y][x] = ncolor;
PaintFill(screen, x - 1, y, ocolor, ncolor); // left
PaintFill(screen, x + 1, y, ocolor, ncolor); // right
PaintFill(screen, x, y - 1, ocolor, ncolor); // top
PaintFill(screen, x, y + 1, ocolor, ncolor); // bottom
}
return true;
}

boolean PaintFill(Color[][] screen, int x, int y, Color ncolor) {
return PaintFill(screen, x, y, screen[y][x], ncolor);
}

print all valid combinations of n-pairs of parentheses


Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))

We can solve this problem recursively by recursing through the string. On each iteration, we have the index for a particular character in the string. We need to select either a left or a right paren. When can we use left, and when can we use a right paren?
»»Left: As long as we haven’t used up all the left parentheses, we can always insert a left paren.
»»Right: We can insert a right paren as long as it won’t lead to a syntax error. When will we get a syntax error? We will get a syntax error if there are more right parentheses than left.
So, we simply keep track of the number of left and right parentheses allowed. If there are left parens remaining, we’ll insert a left paren and recurse. If there are more right parens remaining than left (eg, if there are more left parens used), then we’ll insert a right paren and recurse.

public static void printPar(int l, int r, char[] str, int count) {
if (l < 0 || r < l) return; // invalid state
if (l == 0 && r == 0) {
System.out.println(str); // found one, so print it
} else {
if (l > 0) { // try a left paren, if there are some available
str[count] = ‘(‘;
printPar(l - 1, r, str, count + 1);
}
if (r > l) { // try a right paren, if there’s a matching left
str[count] = ‘)’;
printPar(l, r - 1, str, count + 1);
}
}
}

public static void printPar(int count) {
char[] str = new char[count*2];
printPar(count, count, str, 0);
}


Wednesday, May 25, 2011

How to check reason for application slowing down?

What will be the three things you will look into when your java system.application goes slow suddenly. Means one day you notice application is running very slow and till yesterday it was fine, so what three things you will see first or debug first.


1. checking logs.
2. checking memory usage and cpu usage, if behave exceptionally.
3. dump thread or think about what is recently config/code change, or what is the possible datasource change

4. low virtual memory

Tuesday, April 12, 2011

No of words in a language

There is a language with only two elements ie 'a' and 'bc'. How many words can be
made out of it if whose Length is n.

Let N(k) be the number of strings of length k. Since you can
make a string of length k by appending 'a' onto a string of length k-1
or by appending 'bc' onto a string of length k-2, it follows that

N(k) = N(k-1) + N(k-2)

Furthermore, there are no strings of length -1 and only one string of
length 0.

Friday, April 1, 2011

Prims's Algorithm


Prim's algorithm  finds a minimum-cost spanning tree of an edge-weighted, connected, undirected graph tex2html_wrap_inline71355. The algorithm constructs the minimum-cost spanning tree of a graph by selecting edges from the graph one-by-one and adding those edges to the spanning tree.
http://compprog.wordpress.com/2007/11/09/minimal-spanning-trees-prims-algorithm/

http://pages.pacificcoast.net/~cazelais/222/prim.pdf

Tuesday, March 29, 2011

Maximum Area Rectangle In 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.

http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html

Sunday, March 27, 2011

Card shuffle


To shuffle an array a of n elements:
for i from n - 1 downto 1 do
j
← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
Use Random class in java to generate random number.

http://techpuzzl.wordpress.com/2010/06/30/card-shuffle/

Wednesday, March 23, 2011

Avid TV Watcher

Here is a TV avid person. He wants to spend his max time on TV. There are N channels with different program of different length and diff times. WAP so that the person can spend his max time watching TV.Precondition: If that person watches a program, he watches it completely.

Ex:
Channel1: 

prog1 – 8:00- 8:30
prog2: 9:00 – 10:00
prog3: 10:15 – 12:00

channel2: 

prg1 – 8:15 – 10:00
prg2: 10:30 – 12:00

So in this case max time will be if he watches:

ch2/prg1 + ch1/prg3



http://tech-queries.blogspot.com/2011/03/avid-tv-watcher.html

Tuesday, March 22, 2011

Antipodal points

Given N points on a circle, centered at the origin, design an algorithm that determines whether there are two points that are antipodal, i.e., the line connecting the two points goes through the origin. Your algorithm should run in time proportional to N log N.


Algorithm :
1. Sort the points into increasing order by x
2. Set i = 0 and j = n-1
3. Loop while i < j:
     if x[i] + x[j] < 0, increment i
     else if x[i] + x[j] > 0, decrement j
     else if y[i] + y[j] == 0 return TRUE
4. return FALSE

Sunday, March 20, 2011

Word Suggest


This is general algorithm we use in search engines. Question is Given a dictionary suggest the words for a given misspelled word.

The word could be misspelled in either of the following 4 ways.

Transpositions: These are set of words where 2 adjacent characters in a word are trans positioned. Ex: hlelo –> hello . There are atmost n-1 trans positioned words for a given word.
Insertion: Word could be misspelled by inserting an extra character. Ex: helxlo –> hello There could be at the max n+1 words with this.
Substitution: Word could be misspelled by typing wrong character in place of another character. Ex: helxo –> hello . Max No. of Substituted words could 25 * ( n )
Omissions: These are set of words where a character is omitted Ex: hllo –> hello . Max No of omitted words could be 26*(n+1)

http://flexaired.blogspot.com/2011/03/word-suggest.html

Suffix Trees

Given a string s and an array of smaller strings T, design a method to search s for each small string in T.

ex : S = "ibabbsabs" ;
      T = { "ib", "bs" };

Ans :
ib: [0]
bs: [4, 7]

http://flexaired.blogspot.com/2011/03/suffix-trees.html

http://shashank7s.blogspot.com/2011/03/wap-for-given-string-s-and-array-of.html

Suffix Tree doc 

PPT : www.math.tau.ac.il/~haimk/seminar02/suffixtrees.ppt

Spell Checking Using Trie

Trie Tree:A trie (from retrieval), is a multi-way tree structure useful for storing strings over an alphabet. It has been used to store large dictionaries of English (say) words in spelling-checking programs and in natural-language "understanding" programs. Given the data:
an, ant, all, allot, alloy, aloe, are, ate, be
the corresponding trie would be:


The idea is that all strings sharing a common stem or prefix hang off a common node. When the strings are words over {a..z}, a node has at most 27 children - one for each letter plus a terminator.
The elements in a string can be recovered in a scan from the root to the leaf that ends a string. All strings in the trie can be recovered by a depth-first scan of the tree.

More explanation is here.

http://www.kakarak.com/dl/java/Trie2.java

http://shashank7s.blogspot.com/2011/03/wap-to-spell-checking-using-trie.html

Saturday, March 19, 2011

Levenshtein distance Or Edit Distance between Two Strings


   The words `computer' and `commuter' are very similar, and a change of just one letter, p->m will change the first word into the second. The word `sport' can be changed into `sort' by the deletion of the `p', or equivalently, `sort' can be changed into `sport' by the insertion of `p'.
    The edit distance of two strings, s1 and s2, is defined as the minimum number of point mutations required to change s1 into s2, where a point mutation is one of:
change a letter,
insert a letter or
delete a letter
The following recurrence relations define the edit distance, d(s1,s2), of two strings s1 and s2:
d('', '') = 0               -- '' = empty string
d(s, '')  = d('', s) = |s|  -- i.e. length of s
d(s1+ch1, s2+ch2)
  = min( d(s1, s2) + if ch1=ch2 then 0 else 1 fi,
         d(s1+ch1, s2) + 1,
         d(s1, s2+ch2) + 1 )
The first two rules above are obviously true, so it is only necessary consider the last one. Here, neither string is the empty string, so each has a last character, ch1 and ch2 respectively. Somehow, ch1 and ch2 have to be explained in an edit of s1+ch1 into s2+ch2. If ch1 equals ch2, they can be matched for no penalty, i.e. 0, and the overall edit distance is d(s1,s2). If ch1 differs from ch2, then ch1 could be changed into ch2, i.e. 1, giving an overall cost d(s1,s2)+1. Another possibility is to delete ch1 and edit s1 into s2+ch2, d(s1,s2+ch2)+1. The last possibility is to edit s1+ch1 into s2 and then insert ch2, d(s1+ch1,s2)+1. There are no other alternatives. We take the least expensive, i.e. min, of these alternatives.
The recurrence relations imply an obvious ternary-recursive routine. This is not a good idea because it is exponentially slow, and impractical for strings of more than a very few characters.


Java recursive code : 
public class LevenshteinDistance {

public static void main(String[] args) {
String src = "hippo";
String target = "elephant";

System.out.println(getMinimumEditDistnace_Recursion(src, target));

}

private static int getMinimumEditDistnace_Recursion(String src,String target) {
if (src == null || src.length() == 0)
return target != null ? target.length() : 0;

if (target == null || target.length() == 0)
return src != null ? src.length() : 0;

char ch1 = src.charAt(0);
char ch2 = target.charAt(0);

int addOne = 0;
if (ch1 != ch2)
addOne = 1;

String deleteCharFromsrc = "";
if (src.length() != 1)
deleteCharFromsrc = src.substring(1);

String deleteCharFromTarget = "";
if (target.length() != 1)
deleteCharFromTarget = target.substring(1);

return minimum(
getMinimumEditDistnace_Recursion(deleteCharFromsrc,
deleteCharFromTarget)
+ addOne, getMinimumEditDistnace_Recursion(src,
deleteCharFromTarget) + 1, getMinimumEditDistnace_Recursion(
deleteCharFromsrc, target) + 1
);
}

private static int minimum(int a, int b, int c) {
if (a <= b && a <= c) {
return a;
} else {
return (b <= a && b <= c) ? b : c;
}
}
}

Above program creating string literals unnecessarly.We can do with out taking subString by tracking index positions.
public class LevenshteinDistance {

public static void main(String[] args) {
System.out.println(getMinimumEditDistnace_Recursion("", "",0,0));
System.out.println(getMinimumEditDistnace_Recursion("", "a",0,0));
System.out.println(getMinimumEditDistnace_Recursion("aaapppp", "",0,0));
System.out.println(getMinimumEditDistnace_Recursion("frog", "fog",0,0));
System.out.println(getMinimumEditDistnace_Recursion("fly", "ant",0,0));
System.out.println(getMinimumEditDistnace_Recursion("elephant", "happo",0,0));
System.out.println(getMinimumEditDistnace_Recursion("hippo", "elephant",0,0));
System.out.println(getMinimumEditDistnace_Recursion("hippo", "zzzzzzzz",0,0));
System.out.println(getMinimumEditDistnace_Recursion("hello", "hallo",0,0));
}

private static int getMinimumEditDistnace_Recursion(String src,String target,int srcIndex, int targetIndex) {

if (src == null || src.length() == 0 || srcIndex>=src.length())
return target != null ? target.length()- targetIndex : 0;

if (target == null || target.length() == 0 || targetIndex>=target.length())
return src != null ? src.length()- srcIndex : 0;

char ch1 = src.charAt(srcIndex);
char ch2 = target.charAt(targetIndex);

int addOne = 0;
if (ch1 != ch2)
addOne = 1;

return minimum(
getMinimumEditDistnace_Recursion(src,target,srcIndex+1,targetIndex+1)+addOne,
getMinimumEditDistnace_Recursion(src,target,srcIndex,targetIndex+1) + 1,
getMinimumEditDistnace_Recursion(src, target,srcIndex+1,targetIndex) + 1
);
}

private static int minimum(int a, int b, int c) {
if (a <= b && a <= c) {
return a;
} else {
return (b <= a && b <= c) ? b : c;
}
}
}

Algorithm_DP :

1)Set n to be the length of s.
  Set m to be the length of t.
  If n = 0, return m and exit.
  If m = 0, return n and exit.
  Construct a matrix containing 0..m rows and 0..n columns.
2)Initialize the first row to 0..n.
  Initialize the first column to 0..m.
3)Examine each character of s (i from 1 to n).
4)Examine each character of t (j from 1 to m).
5)If s[i] equals t[j], the cost is 0.
  If s[i] doesn't equal t[j], the cost is 1.
6)Set cell d[i,j] of the matrix equal to the minimum of:
  a) The cell immediately above plus 1: d[i-1,j] + 1.
  b) The cell immediately to the left plus 1: d[i,j-1] + 1.
  c) The cell diagonally above and to the left plus the cost: d[i-1,j-1] + cost.
7)After the iteration steps (3, 4, 5, 6) are complete, the distance is found in cell d[n,m].

A two-dimensional matrix, dp[0..|s1|,0..|s2|] is used to hold the edit distance values:

dp[i,j] = dp(s1[1..i], s2[1..j])
dp[0,0] = 0
dp[i,0] = i,  i=1..|s1|
dp[0,j] = j,  j=1..|s2|

dp[i,j] = dpin(dp[i-1,j-1]
             + if src[i]=target[j] then 0 else 1 fi,
             dp[i-1, j] + 1,
             dp[i, j-1] + 1 ),  i=1..|s1|, j=1..|s2|


Java Code : 
public class EditDistanceDp {
public static void main(String[] args) {

String src = "hippo";
String target = "elephant";

// Step 1
int srcLength = src.length();
int targetLength = target.length();
if (srcLength == 0) {
System.out.println(targetLength);
return;
}
if (targetLength == 0) {
System.out.println(srcLength);
return;
}
int[][] dp = new int[srcLength + 1][targetLength + 1];

// Step 2
for (int i = 0; i <= srcLength; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= targetLength; j++) {
dp[0][j] = j;
}

// Step 3
int cost;
for (int i = 1; i <= srcLength; i++) {
// Step 4
for (int j = 1; j <= targetLength; j++) {
// Step 5
if (src.charAt(i - 1) == target.charAt(j - 1)) {
cost = 0;
} else {
cost = 1;
}
// Step 6
dp[i][j] = Minimum(dp[i - 1][j] + 1, dp[i][j - 1] + 1,dp[i - 1][j - 1] + cost);
}
}
// Step 7
System.out.println(dp[srcLength][targetLength]);
}

private static int Minimum(int a, int b, int c) {
int temp = a;
if (b < temp) {
temp = b;
}
if (c < temp) {
temp = c;
}
return temp;
}
}

Skip Lists

Thursday, March 17, 2011

Remove all the nodes which have a greater value on right side in Linked list

Given a linked list, remove all the nodes which have a greater value on right side.
Eg :  the list 12->15->10->11->5->6->2->3
should be changed to 15->11->6->3
Algo : O(n)
1. Reverse the list.
2. Keep max till now. if next node < max then delete the node, otherwise max = next node.
3. Reverse the list again.



Refer : http://www.geeksforgeeks.org/archives/11604
http://geeksforgeeks.org/?p=3511

Wednesday, March 16, 2011

Find Square root using Babylonian method(Efficient)


Perhaps the first algorithm used for approximating \sqrt S is known as the "Babylonian method", named after the Babylonians, or "Heron's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first explicit description of the method. It can be derived from (but predates) Newton's method. This is a quadratically convergentalgorithm, which means that the number of correct digits of the approximation roughly doubles with each iteration. It proceeds as follows:
  1. Begin with an arbitrary positive starting value x0 (the closer to the root, the better).
  2. Let xn+1 be the average of xn and S / xn (using thearithmetic mean to approximate the geometric mean).
  3. Repeat step 2 until the desired accuracy is achieved.
It can also be represented as:
x_0 \approx \sqrt{S}.
x_{n+1} = \frac{1}{2} \left(x_n + \frac{S}{x_n}\right),
\sqrt S = \lim_{n \to \infty} x_n.
This algorithm works equally well in the p-adic numbers, but cannot be used to identify real square roots with p-adic square roots; it is easy, for example, to construct a sequence of rational numbers by this method that converges to + 3 in the reals, but to − 3 in the 2-adics.
Java Code :
public static double getSquareRoot(double s) {
double Xn = 2.0;
double lastXn = 0.0;
while (Xn != lastXn) {
lastXn = Xn;
Xn = (Xn + s / Xn) / 2.0;
}
return Xn;
}

 Refer : http://www.ardendertat.com/2012/01/26/programming-interview-questions-27-squareroot-of-a-number/

Josephsus Problem

Tthe Josephus problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.

There are people standing in a circle waiting to be executed. After the first person is executed, certain number of people are skipped and one person is executed. Then again, people are skipped and a person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom.
The task is to choose the place in the initial circle so that you are the last one remaining and so survive.

The easiest way to solve this problem in the general case is to use dynamic programming. This approach gives us the recurrence:
f(n,k)=(f(n-1,k)+k) \bmod n,\text{ with }f(1,k)=0,\,
This can be seen from the following arguments:
  • When starting from position k(mod n) instead of 0, the number of the last remaining person also shifts by k positions
  • After the first round of the n person problem one eliminates the person on position kmod n and is left with an n − 1 person problem. The person (k + 1)mod n (in the n person case) is the first of the nextk counts and thus has the label 1 in the n − 1 problem. We must therefore shift the outcome of then − 1 problem by (k + 1 − 1) positions to get the answer for the case with n persons.
This approach has running time O(n), but for small k and large n there is another approach. The second approach also uses dynamic programming but has running time O(klogn). It is based on considering killing k-th, 2k-th, ..., (\lfloor n/k \rfloor k)-th people as one step, then changing the numbering.
Refer : http://en.wikipedia.org/wiki/Josephus_problem

Ex : If n people are standing in a circle ,they start shooting the person standing next to their neighbour.If they start firing in this way , determine who will be alive after this sequence ??


f(n,k) = (f(n-1,k) + k)%n with f(1,k) = 0




public class JosephusProblem {
public static void main(String[] args) {
System.out.println(f(6, 1));
}

public static int f(int n, int k) {
if (n == 1)
return 0;
else {
return (f(n - 1, k) + k) % n;
}
}

}

Refer : http://ihaventyetdecided.blogspot.com/2010/10/josephus-problem.html