Thursday, October 11, 2012

Count the number of words in a string


Count the number of words in a string, where a word is defined to be a contiguous sequence of non-space characters.

eg, “Hello, my name is John.” -> 5

Strategy:

The key is to note when it is in a word and when it is not; When it changes from not-in-word to in-word, increment wordCount by one.

int countNumWords(const char *str) {
  bool inWord = false;
  int wordCount = 0;
  while (*str) {
    if (!inWord && isalpha(*str)) {
      inWord = true;
      wordCount++;
    }
    else if (inWord && *str == ' ') {
      inWord = false;
    }
    str++;
  }
  return wordCount;
}

Tuesday, October 9, 2012

Find sum in stream of numbers

Find first two numbers whose sum equals a given number in infinite length of stream of numbers.

Check whether a given string is an interleaving of two other given strings

Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. 
C is said to be interleaving A and B, if it contains all characters of A and B and order of all characters in individual strings is preserved.

Strategy:

Pick each character of C one by one and match it with the first character in A. If it doesn’t match then match it with first character of B. If it doesn’t even match first character of B, then return false. If the character matches with first character of A, then repeat the above process from second character of C, second character of A and first character of B. If first character of C matches with the first character of B (and doesn’t match the first character of A), then repeat the above process from the second character of C, first character of A and second character of B. If all characters of C match either with a character of A or a character of B and length of C is sum of lengths of A and B, then C is an interleaving A and B.



#include<stdio.h>

// Returns true if C is an interleaving of A and B, otherwise
// returns false
bool isInterleaved (char *A, char *B, char *C)
{
    // Iterate through all characters of C.
    while (*C != 0)
    {
        // Match first character of C with first character of A,
        // If matches them move A to next 
        if (*A == *C)
            A++;

        // Else Match first character of C with first character of B,
        // If matches them move B to next 
        else if (*B == *C)
            B++;
  
        // If doesn't match with either A or B, then return false
        else
            return false;
         
        // Move C to next for next iteration
        C++;
    }

    // If A or B still have some characters, then length of C is smaller 
    // than sum of lengths of A and B, so return false
    if (*A || *B)
        return false;

    return true;
}

int main()
{
    char *A = "AB";
    char *B = "CD";
    char *C = "ACBG";
    if (isInterleaved(A, B, C) == true)
        printf("%s is interleaved of %s and %s", C, A, B);
    else
        printf("%s is not interleaved of %s and %s", C, A, B);

    return 0;
}
Output:

  ACBG is not interleaved of AB and CD
Time Complexity: O(m+n) where m and n are the lengths of strings A and B respectively.

Note that the above approach doesn’t work if A and B have some characters in common. For example, if string A = “AAB”, string B = “AAC” and string C = “AACAAB”, then the above method will return false.

Monday, October 8, 2012

Permutations of BST


Given an array of integers arr = [5,6,1].
When we construct a BST with this input in the same order, we will have "5" as root, "6" as the right child and "1" as left child.
Now if our input is changed to [5,1,6], still our BST structure will be identical.
So given an array of integers, how to find the number of different permutations of the input array that results in the identical BST as the BST formed on the original array order?

Startegy:
Your question is equivalent to the question of counting the number of topological orderings for the given BST.
For example, for the BST
  10
 /  \
5   20
 \7 | \
    15 30
the set of topological orderings can be counted by hand like this: 10 starts every ordering. The number of topological orderings for the subtree starting with 20 is two: (20, 15, 30) and (20, 30, 15). The subtree starting with 5 has only one ordering: (5, 7). These two sequence can be interleaved in an arbitrary manner, leading to 2 x 10 interleavings, thus producing twenty inputs which produce the same BST. The first 10 are enumerated below for the case (20, 15, 30):
 10 5 7 20 15 30
 10 5 20 7 15 30
 10 5 20 15 7 30
 10 5 20 15 30 7
 10 20 5 7 15 30
 10 20 5 15 7 30
 10 20 5 15 30 7
 10 20 15 5 7 30
 10 20 15 5 30 7
 10 20 15 30 5 7
The case (20, 30, 15) is analogous --- you can check that any one of the following inputs produces the same BST.
This examples also provides a recursive rule to calculate the number of the orderings. For a leaf, the number is 1. For a non-leaf node with one child, the number equals to the number of topological orderings for the child. For a non-leaf node with two children with subtree sizes |L| and |R|, both having l and r orderings, resp., the number equals to
  l x r x INT(|L|, |R|)
Where INT is the number of possible interleavings of |L| and |R| elements. This can be calculated easily by (|L| + |R|)! / (|L|! x |R|!). For the example above, we get the following recursive computation:
  Ord(15) = 1
  Ord(30) = 1
  Ord(20) = 1 x 1 x INT(1, 1) = 2  ; INT(1, 1) = 2! / 1 = 2
  Ord(7) = 1
  Ord(5) = 1
  Ord(10) = 1 x 2 x INT(2, 3) = 2 x 5! / (2! x 3!) = 2 x 120 / 12 = 2 x 10 = 20
Useful Link:
http://stackoverflow.com/questions/1701612/permutations-of-bst?rq=1

Sunday, October 7, 2012

Print Ancestors of a node in a Binary Tree:

Print Ancestors of a node in a Binary Tree


Strategy:


#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *left;
    struct node *right;
};

int isAncestor(struct node* root, int n)
{
    if(root == NULL)
        return 0;

    if(root->data == n)
        return 1;

    if(isAncestor(root->left, n) || isAncestor(root->right, n))
    {
        printf("%d\n", root->data);
        return 1;
    }

    return 0;
}

struct node* newnode(int data)
{
  struct node* node = (struct node*)
                       malloc(sizeof(struct node));
  node->data = data;
  node->left = NULL;
  node->right = NULL;
//  node->nextRight = NULL;

  return(node);
}

int main()
{

    /* Constructed binary tree is
              10
            /   \
          8      2
        /         \
      3            90

       \
        14
    */
    struct node *root = newnode(10);
    root->left        = newnode(8);
    root->right       = newnode(2);
    root->left->left  = newnode(3);
    root->right->right       = newnode(90);
    root->right->right->left       = newnode(14);

    isAncestor(root, 14);
    getchar();
    return 0;
}

Time Complexity: O(n) where n is the number of nodes in the given Binary Tree

Find the First Duplicated Integer in an Array Without Using Extra Memory

There is a size-N array of integers whose values range from 1 to N. Some integers are duplicated. Find the first duplicate and its index without using any extra memory.

Strategy:

To solve this problem, we must keep track of elements in order to figure out which one is duplicate. However, regardless of method, we must not use any extra memory. Here is where we must depend on the information given by the problem.
We know that each element's value is between 1 and N, so if we increase that value by (N + 1), the modulus of that value and N + 1 is still the same. For example, modulus of 2 and (N + 1) is 2 and modulus of 2 + N + 1 is still 2. Thus, we can mark a visited element by adding N + 1 into its value or any element's value in the array because that doesn't change its modulus with N + 1 at all!
Furthermore, we know that each element's value is between 1 and N. Hence, we can use each element's value as a key and the element at array[key] as the mark. For example, if the current element is 4 then we can check if its value has been visited, and thus a duplicate, by looking at the value of the element at index 4 in the array, if the current element is 2 the we check the value of the element at index 2 in the array, and so on.
One final point, we need to traverse the array and check each element, so we need a loop that run till we find the duplicate or till we reach the end of the array. The problem with such loop is that it needs additional counter / sentinel value as the loop's termination condition! That requires memory allocation. Fortunately, we know that the first element is not a duplicate because there is no other element in front of it. Thus, we can use the first element in the array as our counter.

Example:
Lets take the given array as   1  3  2  1  1 3

Alternative Method:
Keep one pointer at first index and swap the value at first index with the value at index=value at first position.That means 1 will be swapped with 1 only.If a[i]==i then move the pointer forward.Then at index 2 we get the value as 3.So swap 3 with 2.Now again a[2]=2 So move the pointer forward.In this manner if an elemnt i is already there at a[i] then that is first duplicate.

Find minimum trees to cut

Find minimum trees to cut so that we will be getting at least k units of wood

Given array contains heights of trees in ascending order

2  5  7  8  11  13  17

If we cut a tree of height x then all the trees above height x will be cut and will add to the total units of wood.So for each tree of height say y we will get y-x units of wood.We need to find minimum number of trees to cut to make k units of wood

Strategy:

In the given array lets say we want to make 18 units

We will start from 13.So sum=17-13=4 units only <18
So we move left to 11 and find again sum as sum= previuos sum+ difference between current & next element * number of elements after curent element

So sum= 4+ (13-11) * 2=8 units <18

Again we move to 8 & find sum as sum= 8+ (11-8) * 3 [ as 11,13,17 --3 elements are there towards right]
                                                           =17 <18

So we move to 7 and sum= 17 + 1*4=21>18 So 7 is my answer

Saturday, October 6, 2012

Minimum path sum from top to bottom in a Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

http://www.programcreek.com/2013/01/leetcode-triangle-java/

Maximum number divisible by 2,3 and 5

 An array of size n is given. The array contains digits from 0 to 9. I had to generate the maximum number using the digits in the array such that it is divisible by 2, 3 and 5

Clock Teasers

Question 1:
Find the angle between the hands of a clock.

Question 2:
The hour and minute hands are at equal distance from the 6 hour, what time will it be exactly?

Question 3:
Find out how many times the minute hand and hour hand exactly match over a 12-hour cycle.How often the second hand and minute hand match each other exactly
  
Solution 1:
Minutes Angle = (360 * m) / 60 = 6m where m is the minutes.
Hour Angle = ((360 * h) / 12) + (360 * m / 12 * 60)
Hour Angle - Minutes Angle = 30h - 11m/2

Solution 2:

Say answer is "8 hour X minute". According as proposition, the angle between the minute hand and "mark 4" of the watch is equal to the angle between the hour hand and "mark 8" of the watch. 
We know in 60 minutes the minute hand makes 360 degrees (360/60=6 degrees per minute) and the hour hand makes 360/12=30 degrees (30/60=1/2 degrees per minute). 

Therefore, (20-X) minutes corresponds to 6(20-X) degrees (this is the angle between the minute hand and "mark 4"). 

And in X minutes the hour hand makes X/2 degrees with "mark 8". 

Thus, X/2=6(20-X) gives X=18 minutes 27 and 9/13 second. 
So, the answer is 8 hour, 18 minutes, 27 9/13 second.

Solution 3:

Between 12:00 and 1:00, the minute hand is always ahead of the hour hand. Then somewhere slightly past 5 minutes after 1:00, the hour and minute hands are in the exact same position. If you have a clock or watch on which you can manipulate the time, try this for yourself.
In this way, the minute hand will pass over the hour hand ten more times, once each hour between 1 and 2, 3 and 4, and so on, until the hour between 10 and 11. Between 11 and 12, the minute hand never catches up to the hour hand until exactly 12:00, when the hands line up again. The hands match up 12 times in a complete cycle, including both the starting and ending positions.

Wednesday, October 3, 2012

Find max sub-square whose border values are all 1

Imagine you have a square matrix, where each cell is filled with either black or white. Design an algorithm to find the maximum subsquare such that all four borders are filled with black pixels.

Maximum sub-matrix sum in a matrix

Tuesday, October 2, 2012

50 Trucks with Payload

 Given a fleet of 50 trucks, each with a full fuel tank and a range of 100 miles, how far can you deliver a payload? You can transfer the payload from truck to truck, and you can transfer fuel from truck to truck. Assume all the payload will fit in one truck.

Monday, October 1, 2012

Binary Tree to BST Conversion


Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree.

Example 1--------------
Input:
          10
         /  \
        2    7
       / \
      8   4
Output:
          8
         /  \
        4    10
       / \
      2   7


Example 2---------------
Input:
          10
         /  \
        30   15
       /      \
      20       5
Output:
          15
         /  \
       10    20
       /      \
      5        30

http://www.geeksforgeeks.org/binary-tree-to-binary-search-tree-conversion/

Correct the BST !


Two nodes of a BST are swapped, correct the BST
September 14, 2012
Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST.

Input Tree:
         10
        /  \
       5    8
      / \
     2   20

In the above tree, nodes 20 and 8 must be swapped to fix the tree.
Following is the output tree
         10
        /  \
       5    20
      / \
     2   8

Strategy:

The inorder traversal of a BST produces a sorted array. So a simple method is to store inorder traversal of the input tree in an auxiliary array. Sort the auxiliary array. Finally, insert the auxiilary array elements back to the BST, keeping the structure of the BST same. Time complexity of this method is O(nLogn) and auxiliary space needed is O(n).

We can solve this in O(n) time and with a single traversal of the given BST. Since inorder traversal of BST is always a sorted array, the problem can be reduced to a problem where two elements of a sorted array are swapped. There are two cases that we need to handle:

1. The swapped nodes are not adjacent in the inorder traversal of the BST.

 For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}.
 The inorder traversal of the given tree is 3 25 7 8 10 15 20 5
If we observe carefully, during inorder traversal, we find node 7 is smaller than the previous visited node 25. Here save the context of node 25 (previous node). Again, we find that node 5 is smaller than the previous node 20. This time, we save the context of node 5 ( current node ). Finally swap the two node’s values.

2. The swapped nodes are adjacent in the inorder traversal of BST.

  For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}.
  The inorder traversal of the given tree is 3 5 8 7 10 15 20 25
Unlike case #1, here only one point exists where a node value is smaller than previous node value. e.g. node 7 is smaller than node 8.

How to Solve? We will maintain three pointers, first, middle and last. When we find the first point where current node value is smaller than previous node value, we update the first with the previous node & middle with the current node. When we find the second point where current node value is smaller than previous node value, we update the last with the current node. In case #2, we will never find the second point. So, last pointer will not be updated. After processing, if the last node value is null, then two swapped nodes of BST are adjacent.

Code:

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *left, *right;
};

void swap( int* a, int* b )
{
    int t = *a;
    *a = *b;
    *b = t;
}

struct node* newNode(int data)
{
    struct node* node = (struct node *)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

// This function does inorder traversal to find out the two swapped nodes.
// It sets three pointers, first, middle and last.  If the swapped nodes are
// adjacent to each other, then first and middle contain the resultant nodes
// Else, first and last contain the resultant nodes
void correctBSTUtil( struct node* root, struct node** first,
                     struct node** middle, struct node** last,
                     struct node** prev )
{
    if( root )
    {
        // Recur for the left subtree
        correctBSTUtil( root->left, first, middle, last, prev );

        // If this node is smaller than the previous node, it's violating
        // the BST rule.
        if (*prev && root->data < (*prev)->data)
        {
            // If this is first violation, mark these two nodes as
            // 'first' and 'middle'
            if ( !*first )
            {
                *first = *prev;
                *middle = root;
            }

            // If this is second violation, mark this node as last
            else
                *last = root;
        }

        // Mark this node as previous
        *prev = root;

        // Recur for the right subtree
        correctBSTUtil( root->right, first, middle, last, prev );
    }
}

// A function to fix a given BST where two nodes are swapped.  This
// function uses correctBSTUtil() to find out two nodes and swaps the
// nodes to fix the BST
void correctBST( struct node* root )
{
    // Initialize pointers needed for correctBSTUtil()
    struct node *first, *middle, *last, *prev;
    first = middle = last = prev = NULL;

    // Set the poiters to find out two nodes
    correctBSTUtil( root, &first, &middle, &last, &prev );

    // Fix (or correct) the tree
    if( first && last )
        swap( &(first->data), &(last->data) );
    else if( first && middle ) // Adjacent nodes swapped
        swap( &(first->data), &(middle->data) );

    // else nodes have not been swapped, passed tree is really BST.
}

void printInorder(struct node* node)
{
    if (node == NULL)
        return;
    printInorder(node->left);
    printf("%d ", node->data);
    printInorder(node->right);
}

int main()
{
    /*   6
        /  \
       10    2
      / \   / \
     1   3 7  12
     10 and 2 are swapped
    */

    struct node *root = newNode(6);
    root->left        = newNode(10);
    root->right       = newNode(2);
    root->left->left  = newNode(1);
    root->left->right = newNode(3);
    root->right->right = newNode(12);
    root->right->left = newNode(7);

    printf("Inorder Traversal of the original tree \n");
    printInorder(root);

    correctBST(root);

    printf("\nInorder Traversal of the fixed tree \n");
    printInorder(root);

    return 0;
}
Output:

Inorder Traversal of the original tree
1 10 3 6 7 2 12
Inorder Traversal of the fixed tree
1 2 3 6 7 10 12
Time Complexity: O(n)

http://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/