Popular Posts

Thursday, February 3, 2011

Foldable Binary trees

Given a binary tree,find whether it can be foldable or not :
A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable.
Algorithm : we can do this using recursion.
1.If the root is null,then it is foldable.
2.else check left and right branches recursively.
recursion function :
if left and right both are null,then return true.
if one branch is null while other branch is not null,return false.(asymmetric)
bool isFoldable (node* root) {
if (!root) return true;
return areMirrorImages(root->left, root->right);
}

bool areMirrorImages (node* leftTree, node* rightTree) {
if (!leftTree && !rightTree)
return true;
if (!leftTree && rightTree)
return false;
if (!rightTree && leftTree)
return false;

return areMirrorImages (leftTree->left, rightTree->right) && areMirrorImages (leftTree->right, rightTree->left);
}
Do the same thing for left and right branches.
Refer : http://geeksforgeeks.org/?p=7956

Convert Binary tree into Linked list

Structure of nodes in both doubly linked list and binary search tree are same.So we need to arrange the pointers among the nodes.We can use recursive algorithm to convert BST to doubly linked list.

Algorithm :


An ordered binary tree looks like below:




a circular/doubly linked list looks like this.
if we remove the link in first node and last node of a circular linked list,t will become a doubly linked list.


Recursive algorithm which takes BST and rearranges the internal pointers to make a circular doubly linked list.The list should be arranged so that the nodes are in increasing order. Return the head pointer to the new list.






Algorithm:

If tree is not empty
Convert left subtree to List, let hLeft points to it
Convert right subtree to List, let hRight points to it
Append hLeft with root and then hRight
For detailed explanation have a look at this link :
http://www.rawkam.com/?p=1139


Convert linked list into binary search tree:
If it sorted list,we can do the reverse engineering from conversion of tree to linked list.

If the list is not empty.
 Middle element of the list will become root of the element.
Recursively construct the BST from left and right parts of the linked list.Left and right parts of list will become left and right branches of tree.

In place conversion of sorted doubly linked list to balanced BST : http://www.geeksforgeeks.org/archives/17629

Sorted linked list to balanced BST : http://www.geeksforgeeks.org/archives/17063

Wednesday, February 2, 2011

Java virtual machine

To get better understanding about internal architecture of Java virtual machine,go through below link:
http://www.artima.com/insidejvm/ed2/jvmP.html

Combination of a string

Algorithm :

Step 1: Add the String to the combination results.
Step 2: If the String has just one character in it,
then stop the current line of execution.
Step 3: Create new sub-words from the String by removing one letter at a time.
If the String is "ABCD", form sub-words like "BCD", "ACD", "ABD", "ABC"
Step 4: For each of the sub-word, go to Step 1


    Java program :
     import java.util.HashSet;
    import java.util.Set;

    /**
    * A simple program that generates all possible combinations for a given String
    * using recursion.
    */
    public class StringCombinations {
    // A set to hold the generated combination results.
    private Set<String> combinations = new HashSet<String>();

    /**
    * The constructor.
    *
    * Simply makes a call to the generate method to generate all the possible
    * combinations of the String "wxyz"
    */
    public StringCombinations(String sInputString) {
    generate(sInputString);
    System.out.println("*** Generated " + combinations.size()
    + " combinations ***");
    System.out.println(combinations);
    }

    /**
    * The recursive method does the work of generating all the possible
    * combinations for a given String.
    */
    public void generate(String word) {
    // Add this word to our combination results set
    combinations.add(word);

    // If the word has only one character we break the recursion
    if (word.length() == 1) {
    combinations.add(word);
    return;
    }
    // Go through every position of the word
    for (int i = 0; i < word.length(); i++) {
    // Remove the character at the current position
    // all call this method with that String (Recursion!)
    generate(word.substring(0, i) + word.substring(i + 1));
    }
    }

    /**
    * Entry point to this program. Instantiates the StringCombinations program.
    *
    */
    public static void main(String args[]) {
    String sInputString = "abcd";
    new StringCombinations(sInputString);
    }

    }

    Tuesday, February 1, 2011

    Permutations of a given string

    In outline form,algorithm looks like :

    If you're past the last position
    Print the string
    Return
    Otherwise
    For each letter in the input string
    If it's marked as used, skip to the next letter
    Else place the letter in the current position
    Mark the letter as used
    Permute remaining letters starting at current position + 1
    Mark the letter as unused

    Recursive Implementation :
    Java code:
    public class Permutations {

    public static void main(String[] args) {
    permutation("", "abc");
    }

    private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0)
    System.out.println(prefix);
    else {
    for (int i = 0; i < n; i++)
    permutation(prefix + str.charAt(i), str.substring(0, i)
    + str.substring(i + 1, n));
    }
    }
    }


    Method 2:
    import java.util.ArrayList;
    import java.util.List;

    public class Permutations {

    public static void main(String[] args) {
    List<String> permutations = getPermutations("abcd");
    System.out.println(" size " + permutations.size());
    for (int i = 0; i < permutations.size(); i++) {
    System.out.println(permutations.get(i));
    }
    }

    public static List<String> getPermutations(String word) {
    if (word == null || word.length() == 0)
    throw new NullPointerException();
    ArrayList<String> result = new ArrayList<String>();
    if (word.length() == 1) {
    result.add(word);
    return result;
    }
    List<String> temp = getPermutations(word
    .substring(0, word.length() - 1));
    for (String s : temp) {
    List<String> joined = joinCharToString(s, word
    .charAt(word.length() - 1));
    result.addAll(joined);
    }
    return result;
    }

    public static List<String> joinCharToString(String ori, char aChar) {
    if (ori == null || ori.length() == 0)
    throw new NullPointerException();
    List<String> result = new ArrayList<String>();
    StringBuilder sb;
    for (int i = 0; i < ori.length() + 1; i++) {
    sb = new StringBuilder(ori);
    sb.insert(i, aChar);
    result.add(sb.toString());
    }
    return result;
    }
    }

    Print all permutations with repetition of characters : 
    Given a string of length n, print all permutation of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order
    Examples:
    Input: AB
    Ouput: All permutations of AB with repetition are:
          AA
          AB
          BA
          BB
    Java Code : 
    public class Permutations {
    public static void main(String[] args) {
    String str = "abc";
    char[] chars = str.toCharArray();
    getPermutations(chars, "", str.length());
    }

    private static void getPermutations(char[] chars, String target, int length) {
    if (length == 0) {
    System.out.println(target);
    return;
    }

    for (int i = 0; i < chars.length; i++) {
    getPermutations(chars, target + chars[i], length - 1);
    }
    }
    }

    Monday, January 31, 2011

    Gmail Multiple User Names...


    Many of you might not be knowing that if you have 1 gmail id … you have infinte gmail ids…
    Seems to be a joke.. It’s not actually…
    for e.g  if you have gmail id:
    venuhyd@gmail.com
    then the mail sent to following ids will also be received by your mailbox:
    venu+hyd@gmail.com  8char can be any valid charcter set of max 8 characters
    v.e.n.u.h.y.d@gmail.com
    venuhy.d@gmail.com
    As gmail ignores .’s in its username...
    An alias made by mixture of various such alias is also an alias for your id. 
    like  my.i.d+love@googlemail.com will alsodirect uts mail to your inbox.
    You can use it to filter your e-mails from some sources by giving them alias id and then using a filter with to field..
    Just Check this out...
    Regrads 
    Venu.

    Find Kth largest and smallest number in BST

    How to find kth smallest element in BST. you cannot use static/global variable and you cannot pass value of k to any function ?
    Solution : Make in order traversal and out put the kth element.
    Let each node in the BST have a field that returns the number of elements in its left and right subtree. Let the left subtree of node T contain only elements smaller than T and the right subtree only elements larger than or equal to T.
    Now, suppose we are at node T:
    1.       k == num_elements(left subtree of T), then the answer we're looking for is the value in node T
    2.       k > num_elements(left subtree of T) then obviously we can ignore the left subtree, because those elements will also be smaller than the kth smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T) smallest element of the right subtree.
    3.       k < num_elements(left subtree of T), then the kth smallest is somewhere in the left subtree, so we reduce the problem to finding the kth smallest element in the left subtree.
    This is O(log N) on average (assuming a balanced tree).

    Java code:

    public int ReturnKthSmallestElement1(int k)
    {
    Node node = Root;

    int count = k;

    int sizeOfLeftSubtree = 0;

    while(node != null)
    {

    sizeOfLeftSubtree = node.SizeOfLeftSubtree();

    if (sizeOfLeftSubtree + 1 == count)
    return node.Value;
    else if (sizeOfLeftSubtree < count)
    {
    node = node.Right;
    count -= sizeOfLeftSubtree+1;
    }
    else
    {
    node = node.Left;
    }
    }

    return -1;
    }
    find(node, k) {
      if (count(node->left) + 1 == k) result = node;
      else if (count(node->left) < k) result = find(node->right, k - count(node->left) - 1);
      return find(node->left, k);
    For largest element use node->right
    struct tree* findkthsmallest(struct tree* t,int k)
    {
    int left_size=0;

    if(t->left!=NULL) left_size=t->left->size;

    if(left_size+1==k) return t;

    else if(k<=left_size) return findkthsmallest(t->left,k);

    else return findkthsmallest(t->right,k-left_size-1);//find k-left_size-1 smallest in right subtree.
    }

    struct tree* findkthlargest(struct tree* t,int k)
    {
    int right_size=0;

    if(t->right!=NULL) right_size=t->right->size;

    if(right_size+1==k) return t;

    else if(k<=right_size) return findkthlargest(t->right,k);

    else return findkthlargest(t->left,k-right_size-1);
    }