Sunday, December 11, 2011

Algorithm to Generate the permutations of the array containing number in lexicographical order.

Approach & Description:

Generation in lexicographic order

There are many ways to systematically generate all permutations of a given sequence. One classical algorithm, which is both simple and flexible, is based on finding the next permutation in lexicographic ordering, if it exists. It can handle repeated values, for which case it generates the distinct multiset permutations each once. Even for ordinary permutations it is significantly more efficient than generating values for the Lehmer code in lexicographic order (possibly using the factorial number system) and converting those to permutations. To use it, one starts by sorting the sequence in (weakly) increasing order (which gives its lexicographically minimal permutation), and then repeats advancing to the next permutation as long as one is found.


The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
  1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
  2. Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l.
  3. Swap a[k] with a[l].
  4. Reverse the sequence from a[k + 1] up to and including the final element a[n].
After step 1, one knows that all of the elements strictly after position k form a weakly decreasing sequence, so no permutation of these elements will make it advance in lexicographic order; to advance one must increase a[k]. Step 2 finds the smallest value a[l] to replace a[k] by, and swapping them in step 3 leaves the sequence after position k in weakly decreasing order. Reversing this sequence in step 4 then produces its lexicographically minimal permutation, and the lexicographic successor of the initial state for the whole sequence.

Final Algorithm:

1) From the end, keep decrementing till A[i] < A[i+1]..
2) Now, find the closest element , greater than equal, to A[i] in 
A[i+1 ... n]. Say, the index of the found element is "j".
3) Swap (A[i], A[j])
4) Reverse array A[i+1 .. n]

Example:
Input 14532
output  15234..

1) 4 is the value where A[i] < A[i+1] when scanned from the end.
2) The closest element grater than equal to 4 in the subarray 532 is 5.
3) Swap (4,5) : 14532 -> 15432
4) Now, as we have identified in step 1 the index of i, we need to
reverse the array from A[i+1, n] i.e. in 15(432) (432) needs to be
reversed and hence we will get 15234...

Working Code

#include < iostream>
#include < algorithm>
#include < time.h>
using namespace std;
  
// Swap function
template < class T>
void swap(T *i, T *j)
{
    T temp = *i;
    *i = *j;
    *j = temp;
}
  
// function to reverse a range of values
template < class T>
void reverse(T *start, T *end)
{
    while(start < end)
    {
        swap(start,end);
        start++;
        end--;
    }
}
// array_end does not point to a valid element of the array
// it is beyond the last element
template < class T>
bool permute(T* array_start,T* array_end)
{
    // array does not contain any element
    if(array_start == array_end)
        return false;
     
    // array contains only 1 element
    if(array_start+1 == array_end)
        return false;
         
    T *i,*i1,*j;
     
    // Make the pointers point to last and the second last elements
    i = array_end - 2;
    i1 = array_end - 1;
     
    // find two elements a,b such that a < b and index of a
    // is less than the index of b
    while(true)
    {
        // If such a pair is found, find an element c such that
        // c > a, then swap them and reverse the list from b till
        // the end
        if(*i < *i1)
        {
            j = array_end -1;
                 
            // worst case is that j == i1
            while(!(*i < *j))
                j--;
                 
            // This step implements the lexicographic order by
            // bringing the larger element in the front
            swap(i,j);
             
            // Reverse the list so that we have a weak decreasing
            // order in the remainder of the list
            reverse(i1,array_end-1);
            return true;
        }
         
        // Now the list is in strictly decreasing order
        // no more permutations are possible, return the
        // list as it was originally received
        if(i == array_start)
        {
            reverse(array_start,array_end-1);
            return false;
        }
         
        // decrement the two pointers
        i--;
        i1--;
    }
     
}
template< class T>
void display(T *array,T *end)
{
    T* i = array;
    while(i < end)
    {
        cout << *i << "-";
        i++;
    }
    cout << endl;
}
  
int main()
{
    srand(time(NULL));
     
    // You can declare any type here of any size
    int size = 4;
    char array[size];
     
    cout << "Enter four numbers" << endl;
    for(int i=0;i < size;i++)
        cin>>array[i];
     
    // C++ sort function so that the permutation
    // function receives the elements in the sorted order
    // in order to create a lexicographic order
    sort(array,array+4);  
     
    // First permutation
    display(array,array+4);
    int count=1;
     
    // Call the function while you get valid permutations
    while(permute(array,array+4))
    {
        count++;
        display(array,array+4);
    }
     
    cout << "Total permutations are " << count << endl;
     
    system("pause");
    return 0;
}

Run Here http://ideone.com/sK8JH
The complexity of the approach is O(n*n!)
http://en.wikipedia.org/wiki/Permutation
http://marknelson.us/2002/03/01/next-permutation/

Saturday, December 10, 2011

Write an efficient C program to find the maximum average of contiguous elements inside an array of integers.

Example: [10, 4, -2, 7, 8, -1, -5] Maximum average of continuous elements 7+8=15/2 =7.5

Construct a BST where each node has 3 pointers instead of 2. the structure is struct node { int data; struct node *left; struct node *right; struct node *inordersuccessor; } write a code to add nodes in a binary search tree . inordersuccessor pointing to inorder successor.


Write An Efficient Program to Clone a Graph ?


Given a network of the employees of a company such that edges are between those employees who are friends to each other. Divide the employees into two teams such that no two people who are friends to each other are in the same team


give an algorithm for finding duplicate parenthesis in a expression. (( a + b ) * (( c + d )))


Thursday, December 8, 2011

You are Reciving the infinite number of stream , you to retun k random elemnts ,if you query at time t , in those k elements then proababilty of choosing should be 1 e.g. they should have equal probality


Reverse the direction of each pointers of Linked List which haveing next & random pointer with it.

Consider a Linked List with each Node, in addition to having a 'next' pointer also has a 'random' pointer. The 'random' pointer points to some random other Node on the linked list. It may also point to NULL. To simplify things, no two 'random' pointers will point to the same node, but more than 1 Node's random pointer can point to NULL.
Now we are required to reverse the direction of all the pointers (both the 'next' and 'random') of the Linked list. The constraint is the solution MUST be O(1) space complexity (A constant number of new nodes can be created but not proportional to the length of the list)

Wednesday, December 7, 2011

Find The Largest Binary Search Tree in GIven Tree . Its Should be the Subtree.


Very Faq. Asked Question All Tech Giants :) Will Post The Solution Soon :) Meanwhile You Can Try & Post the approach . 

Prerequisite  : Most Efficient Solution to Check if Given Tree is BST or not ? !st Try it or Search Archives :)

Basic Idea :

 
Traverse the tree. From each node to the parent, return the following
set of values.

1) If BST, size of the current BST or -1 if the tree is not.
2) Minval & Maxval of the subtree and maxbstsize seen so far (
probably using references)

So in each node check the following:

If( leftmax < node->data && node->data < rightmin)  // Means it is a BST
{
  new size = rightsize+leftsize+1
  update size if greater than max
  return size
}
else
{
  return -1;
} 
 
 Working Code:
 
/* Largest Binary search tree inside a binary tree -- O(n)*/

#include <stdlib.h>
#include <stdio.h>
using namespace std;

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

struct node* insert_bst(struct node* root, int num){
  if(root == NULL){
    root = (struct node*)malloc(sizeof(struct node));
    root->data = num;
    root->left = NULL;
    root->right = NULL;
    return root;
  }else{
    if(num == root->data){
      return root;
    }

    if(num > root->data){
      root->right=insert_bst(root->right,num);
    }else{
      root->left=insert_bst(root->left,num);
    }
  }
  return root;
}

void inorder_traverse(struct node* root){
  if(root == NULL) return;

  inorder_traverse(root->left);
  printf("%d ",root->data);
  inorder_traverse(root->right);
}

struct node* bst_root = NULL;

int getmaxbst(struct node* root, int& subtreemin, int &subtreemax, int& max)
{
  if(root == NULL) return 0;

  int leftsubtreemin = -32767, rightsubtreemin = -32767;
  int leftsubtreemax = 32767, rightsubtreemax = 32767;
  int x,y;

  x = getmaxbst(root->left, leftsubtreemin, leftsubtreemax, max);
  y = getmaxbst(root->right, rightsubtreemin, rightsubtreemax, max);

  if(x==-1 || y ==-1)
    return -1;
  if(x==0) { leftsubtreemax = root->data; leftsubtreemin = root->data;}
  if(y==0) { rightsubtreemin = root->data; rightsubtreemax = root->data;}

  if(root->data < leftsubtreemax ||
     root->data > rightsubtreemin){
    return -1;
  }

  subtreemin = leftsubtreemin;
  subtreemax = rightsubtreemax;

  if(x+y+1 > max){
    max = x+y+1;
    bst_root = root;
  }

  return x+y+1;

}

int main()
{
  struct node* root=NULL;

  root=insert_bst(root,5);
  root=insert_bst(root,3);
  root=insert_bst(root,9);
  root=insert_bst(root,7);
  root=insert_bst(root,4);
  root=insert_bst(root,1);
  root=insert_bst(root,14);
  root=insert_bst(root,11);

  root->data = 0;

  int a,b,c,max=-32767;
  c = getmaxbst(root,a,b,max);
  printf("\nmax is %d\n",max);

  inorder_traverse(bst_root);
  return 1;
} 
 
TC O(N)
SC O(1) 

Tuesday, November 29, 2011

Find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.


How do you find a shortest connection between two persons on Facebook(if the same exists)? You are provided with an API which returns the list of friends of a particular persons


Given an array of n integers having elements 1-n. By mistake one element repeated twice in the array and one element got missed. Need to find out the missing and repeated element. Time=O(n),space=O(1)


GIven a string "RGBBGBGR". we have to eliminate the couple (two same chars adjacent to each other) recursively. For example RGBBGBGR --> RGGBGR-->RBGRG


Given a number 123456789 and two opearators + and *. You have also given value k , You have to find all the such expressions that evaluates and value is equal to the given value.

Given a number 123456789 and two opearators + and *. You can use this two operators as many times u want. But you cant change the sequence of the number given there. The evaluated value is 2097.
e.g. 1+2+345*6+7+8+9=2097
You have to find all the such expressions that evaluates and value is
equal to the given value. You can use concatenation of numbers like 345 is concatenated there.

e.g. some more example
1+2+345*6+7+8+9 = 2097
12*3*45+6*78+9 = 2097
12*34+5*6*7*8+9 = 2097

Given an image that is represented by Nx1000 matrix of binary numbers. 1 represents black(image ink) and 0 represents white(blank).,Return all the positions of the pixels where you break the page and the number of pages, so that the image can be printed in the minimum number of pages.

Given an image that is represented by Nx1000 matrix of binary numbers. 1 represents black(image ink) and 0 represents white(blank).
The page breaks are applied in two ways:
1.)Find the row with all the white pixels.
(But this selection should be efficient as we want to print in minimum no. of pages.
For example: if we get a white line on 200th row, 600th row and 900th row, we should choose 900th line to break page).
2.) If no such row exists, break on the 1000th line.

Return all the positions of the pixels where you break the page and the number of pages, so that the image can be printed in the minimum number of pages.


Devise an algorithm for maximizing the sum of the randomly selected elements from the k subarrays. Basically means that we will want to split the array in such way such that the sum of all the expected values for the elements selected from each subarray is maximum.

You have an array with *n* elements. The elements are either 0 or 1. You
want to *split the array into kcontiguous subarrays*. The size of each
subarray can vary between ceil(n/2k) and floor(3n/2k). You can assume that
k << n. After you split the array into k subarrays. One element of each
subarray will be randomly selected.

Devise an algorithm for maximizing the sum of the randomly selected
elements from the k subarrays. Basically means that we will want to split
the array in such way such that the sum of all the expected values for the
elements selected from each subarray is maximum.

You can assume that n is a power of 2.

Example:

Array: [0,0,1,1,0,0,1,1,0,1,1,0]
n = 12
k = 3
Size of subarrays can be: 2,3,4,5,6

Possible subarrays [0,0,1] [1,0,0,1] [1,0,1,1,0]
Expected Value of the sum of the elements randomly selected from the
subarrays: 1/3 + 2/4 + 3/5 = 43/30 ~ 1.4333333

Optimal split: [0,0,1,1,0,0][1,1][0,1,1,0]
Expected value of optimal split: 1/3 + 1 + 1/2 = 11/6 ~ 1.83333333


Source -> http://stackoverflow.com/questions/8189334/google-combinatorial-optimization-interview-problm

Saturday, November 26, 2011

Given a set of numbers [1-N] . Find the number of subsets such that the sum of numbers in the subset is a prime number.


SMS Problem

1 - NULL, 2 - ABC, 3 - DEF, 4 - GHI, 5 - JKL, 6 - MON, 7 - PQRS, 8 - TUV, 9 - WXYZ, * - <Space>, # - <Break>
We must convert the numbers to text.
Eg
I/P - O/P
22 - B
23 - AD
223 - BD
22#2 - BA (# breaks the cycle)
3#33 - DE
2222 - 2
2222#2 - 2A
22222 - A (cycle must wrap around)
222222 - B

Convert Binary Tree into Doubly Linked List Such That Each Node of Doubly Linked List Contains The Vertical Sum of Binary Tree . We Can't Modify The Orginal Linked List

P.S. Its Extension of Vertical Sum & BT to DLL Problem . Will Take Some Time to Think About The Solution .
Please Search Previous Threads for above two problems .Although I Will Try to Pust Exact Working Code ASAP i will finish it .


Sunday, November 20, 2011

Algorithm to output for a length m of a number stream, the value of the element j appearing in the s


Devise a small memory streaming algorithm to determine if |A| = 1.


For a stream of insertions and deletions, recall that x[j] = #insertions - #deletions of element j.
Given such a stream satisfying x[j] >= 0 for all elements j, let

A = { j : x[j] > 0 }

Determining whether A is empty is easy: just check if the sum of all x[j]'s equals 0 (which is easily doable in a stream).

Problem: devise a small memory streaming algorithm to determine if |A| = 1.

Extensions: What about higher sizes of A? What if the promise is not satisfied and we define A to be the set of j's with x[j] not equal to 0.

Thursday, November 17, 2011

Why 11/11/11 Is Mathematically Amazing



You All Know Some Times Back We Had Data 11/11/11, is a once-in-a-century occurrence, adding to a November has been a very fun month for recreational mathematicians.
Last week, a rare eight-digit palindrome date — 11/02/2011, which reads the same frontward and backward — was found to have other mathematical qualities that made it a once-in-10,000-years date.Aziz Inan, a professor of electrical engineering at the University of Portland, Oregon, crunched the numbers and found that when the date was expressed as a number, 11,022,011, it has very special properties.
"It is the product of 7 squared times 11 cubed times 13 squared. That is impressive because those are three consecutive prime numbers. No other palindrome date up to A.D. 10,000 is like that," Inan said. "Not only that, if you write it out as 72 x 113 x 132, you'll notice that even the superscript power numbers — 232 — are a palindrome."
A once-in-10,000-years date is hard to top, but 11/11/11 is no slouch. Some people believe that the date 11/11/11 is a mystical day of good luck, or that 11/11/11 is a good day to make money. Inan explained that when one looks closely at the date, it too has some interesting mathematical properties.
After today, 11/11/11 will next occur 100 years down the road, on Nov. 11, 2111. Interestingly, in 2111, 11/11/11 will be followed by an eight-digit palindrome day, 11/12/2111, which is quite exciting for palindrome fans like Inan.
If you consider today's date as a number — 111,111 — you can run some additional fun math tricks, Inan explained. 111,111 can be obtained from its largest prime number factor, 37, like so: First, subtract 37 from its reverse (73) and you get 36. (Inan added that 36 is equal to the square of the sum of the digits in 111,111.)
Then, split 36 into three consecutive numbers that add up to 36 (11, 12 and 13). Then, multiply 11, 13, 37 and the reverse of 12 (21). And what comes out? You guessed it: 111,111.




Source www.lifeslittlemysteries.com/

Tuesday, November 15, 2011

Given Table of Cities , Find Minimum Number of Hopes Required to Fly From One to Other City

There is a very Primitive Database and it has a table say "Travel". The content of table is as follows:
Source | Dest
--------------


Sea | LA
LA | FL
LA | MA
FL | Sea
Sea | FL
The ask is to find out all routes between (Sea) to (FL) with mininum hop.
the Result would be:
1. Sea -> FL
2. Sea -> LA - > FL
You have to write a Middle tier function to achieve above result. You can assume there is DBAPI that return the Destination city if you provide the source city.

Create Linked List From Leaf of Binary Tree


Thursday, October 20, 2011

Given two bst, print the output that would come if two bsts are merged and then an inorder traversal is performed. Of, course you can't merge trees here.

PS:Heard From One of The My Friend :

Given an integer N, there are 2^N binary codewords of length N. All of them are taken and sorted to create a sequence: Sort by the number of 1-bits in the codeword bit-string. If there is a tie, break tie so that the smaller number comes first in the output sequence

Example  and Testcases :You would be given 2 integers N (<=10) and K (1 <= K <= 2^N)
Output the codeword with index K into this sequence
The input is from stdin and output to stdout

Sample Testcases:
Input #00:
3 5
Output #00:
011
Explanation:
For N = 3, the sequence consists of {000,001,010,100,011,101,110,

111}. The 5th indexed number would be 011

Input #01:
7 127
Output #01:
1111110

An array of integers is given and you have to find the largest possible integer by concatenating all elements:

   Example:

array:  87  36  52
answer:  875236

array: 87 9 52
answer: 98752 

Provide an efficient algorithm to solve the question "Can I buy N items?

 A shop sells an item in packets of 6, 9, and 17. A customer can buy any number of packets, but a packet cannot be broken up. Provide an efficient algorithm to solve the question "Can I buy N items?". For example, is it possible to buy 29 items? What about 19? Your algorithm simply needs to return true or false.

Design Data Structure For Students-Courses Realtionship

In a university, students can enroll in different courses. A student may enroll for more than one course. Both students and courses can be identified by IDs given to them. Design a data structure to store students, courses, and the student-course relationships. You can use arrays, lists, stacks, trees, graphs, etc. or come up with your own data structures. Give the running times, in Big O notation, for the following operations for your data structure and justify the answers: a) Return all students in a list. b) Return all courses in a list. c) Return all courses in a list for a given student. d) Return all students in a list for a given course.



Thursday, October 13, 2011

Determine a user’s influence on the system by determining how many users he is responsible for


You Know Invitation Based System. on Google+, Gmail,Yahoo,Facebook etc...users can add their friends by emailing a . We want to determine a user’s influence on the system by determining how many users he is responsible for. A user’s influence is calculated by giving him 1 point for every user he’s added in addition to the sum of the influence scores of each user that he’s added.
Example: User 0 adds User 1 and User 2. User 1 adds User 3.
User 0’s influence score is 3. (He added two users and one of them added added a third user.)
User 1's is 1.
User 2’s is 0.
User 3’s is 0.

P.S.:One of The Question Asked By Google M.V.  From Me. :)
The above scenario is represented by the following input file. Line i is user ID i and position j within the line is marked with an X if user ID iadded user ID j. Both row and column indicies are 0-based:
 OXXO
 OOOX
 OOOO
 OOOO
      


-->

Sunday, October 9, 2011

How Google Won User's Heart :: Google Auto-Suggestion/Auto-Completion Algorithm Exposed

How Auto Suggestion Works e.g. How Google Won User's Heart
You've seen search engines suggest queries when you begin typing the first few letters of your search string. This is being done by Duck Duck Go as well as Google (to name a few). This is typically done by maintaining a list of past queries and/or important strings that the search engine thinks are worthy of being suggested to a user that is trying to find something similar. These suggestions are effective only if the search engine spits them out very fast since these should show up on the screen before the user has finished typing what he/she wanted to type. Hence the speed with which these suggestions are made is very critical to the usefulness of this feature.

Let us consider a situation (and a possible way of approaching this problem) in which when a user enters the first few letters of a search query, he/she is presented with some suggestions that have as their prefix, the string that the user has typed. Furthermore, these suggestions should be ordered by some score that is associated with each such suggestion.

Approach-1:

Our first attempt at solving this would probably involve keeping the initial list of suggestions sorted in lexicographic order so that a simple binary search can give us the 2 ends of the list of strings that serve as candidate suggestions. These are all the strings that have the user's search query as a prefix. We now need to sort all these candidates by their associated score in non-increasing order and return the first 6 (say). We will always return a very small subset (say 6) of the candidates because it is not feasible to show all candidates since the user's screen is of bounded size and we don't want to overload the user with too many options. The user will get better suggestions as he/she types in more letters into the query input box.

We immediately notice that if the candidate list (for small query prefixes say of length 3) is large (a few thousand), then we will be spending a lot of time sorting these candidates by their associated score. The cost of sorting is O(n log n) since the candidate list may be as large as the original list in the worst case. Hence, this is the total cost of the approch. Apache's solr uses this approach. Even if we keep the scores bound within a certain range and use bucket sort, the cost is still going to be O(n). We should definitely try to do better than this.


Approach-2:

One way of speeding things up is to use a Trie and store (pointers or references to) the top 6 suggestions at or below that node in the node itself. This idea is mentioned here. This results in O(m) query time, where m is the length of the prefix (or user's search query).

However, this results in too much wasted space because:
  1. Tries are wasteful of space and
  2. You need to store (pointers or references to) 6 suggestions at each node which results in a lot of redundancy of data

We can mitigate (1) by using Radix(or Patricia) Trees instead of Tries.


Approach-3:

There are also other approaches to auto-completion such as prefix expansion that are using by systems such asredis. However, these approaches use up memory proportional to the square of the size of each suggestion (string). The easy way to get around this is to store all the suggestions as a linear string (buffer) and represent each suggestion as an (index,offset) pair into that buffer. For example, suppose you have the strings:
  1. hello world
  2. hell breaks lose
  3. whiteboard
  4. blackboard

Then your buffer would look like this:
hello worldhell breaks losewhiteboardblackboard
And the 4 strings are actually represented as:
(0,11), (11,16), (27,10), (37,10)

Similarly, each prefix of the suggestion "whiteboard" is:
  1. w => (27,1)
  2. wh => (27,2)
  3. whi => (27,3)
  4. whit => (27,4)
  5. white => (27,5)
  6. whiteb => (27,6)
  7. and so on...

Approach-4:

We can do better by using Segment (or Interval) Trees. The idea is to keep the suggestions sorted (as in approach-1), but have an additional data structure called a Segment Tree which allows us to perform range searches very quickly. You can query a range of elements in Segment Tree very efficiently. Typically queries such as min, max, sum, etc... on ranges in a segment tree can be answered in O(log n) where n is the number of leaf nodes in the Segment Tree. So, once we have the 2 ends of the candidate list, we perform a range search to get the element with the highest score in the list of candidates. Once we get this node, we insert this range (with the maximum score in that range as the key) into the priority queue. The top element in the queue is popped and split at the location where the element with the highest score occurs and the scores for the 2 resulting ranges are computed and pushed back into the priority queue. This continues till we have popped 6 elements from the priority queue. It is easy to see that we will have never considered more than 2k ranges (here k = 6).

Hence, the complexity of the whole process is the sum of:
  1. The complexity for the range calculation: O(log n) (omitting prefix match cost) and
  2. The complexity for a range search on a Segment Tree performed 2k times: O(2k log n) (since the candidate list can be at most 'n' in length)

Giving a total complexity of:
O(log n) + O(2k log n)
which is: O(k log n)

Some Useful Links
http://en.wikipedia.org/wiki/Autocomplete
http://igoro.com/archive/efficient-auto-complete-with-a-ternary-search-tree/
http://stevedaskam.wordpress.com/2009/05/17/autocomplete-data-structures/
http://sujitpal.blogspot.com/2007/02/three-autocomplete-implementations.html
http://stackoverflow.com/questions/73095/how-to-implement-a-simple-auto-complete-functionality
http://code.google.com/p/autocomplete-server/
http://suggesttree.sourceforge.net/
http://www.quora.com/What-is-the-best-open-source-solution-for-implementing-fast-auto-complete
http://www.phpfreaks.com/forums/index.php?topic=240881.0
http://dhruvbird.blogspot.com/2010/09/very-fast-approach-to-search.html