Monday, February 27, 2012

Write an algorithm that prints an unordered sets of k elements chosen from a set of size n.

Example, let the size of the give set be n and set = {0, 1, 2, 3, 4} and we need to find all the subsets of size 3, then there will be a total of 10 such subsets given as:

{0, 1, 2}
{0, 1, 3}
{0, 1, 4}
{0, 2, 3}
{0, 2, 4}
{0, 3, 4}
{1, 2, 3}
{1, 2, 4}
{1, 3, 4}
{2, 3, 4}


Sunday, February 26, 2012

Fastest Super Computer is From Japan Till Today :) ,its K Computer

 Japanese supercomputer becomes world’s fastest and first to clear 10 petaflops
The fastest got faster, as the K Computer topped its own record on the twice-yearly supercomputer speed test by scoring 10.51 quadrillion calculations per second
The performance of the fastest machine on the Top500 supercomputer list hasn't stopped surging since the list began in 1993. Here, it's measured with a linear scale. 
The performance of the fastest machine on the Top500 supercomputer list hasn't stopped surging since the list began in 1993. Here, it's measured with a linear scale.
(Credit: chart by Stephen Shankland; data from Top500.org)
The rankings of the 10 fastest machines didn't change at all on today's new version of the Top500 supercomputer list, but the top dog cleared the notable performance hurdle of 10 petaflops.
"Flops" stands for floating-point operations per second and is a measure of how fast a supercomputer can perform mathematical calculations using the Linpack benchmark. The K Computer, at the Riken Advanced Institute for Computational Science in Japan, moved up from 8.16 petaflops, the score it used to reach the top of the twice-yearly supercomputer ranking last June, to 10.51 petaflops.
It reached the new top speed through being fully assembled, with all 705,024 of its Fujitsu Sparc64 processor cores running.
The Tianhe-1A in China, a former No. 1 machine at 2.57 petaflops, remains No. 2. It uses a combination of Intel central processing units and Nvidia graphical processing units. The United States is the top market for supercomputers on the list, but China is in second place, list organizers said.
Intel remains king of the heap when it comes to processor designs, supplying chips for 384 of the systems.
Among other aspects of the November 2011 list:
• Even though the top 10 machines remained the same--a first since the Top500 list began in 1993--there was still plenty of flux elsewhere on the list. The bottom of the barrel for the November list ranked No. 305 in June, and the total performance of all 500 machines rose from 58.7 petaflops to 74.2 petaflops.
• It's now required 50.9 teraflops to get on the list at all. That score beats the top system from 2004. The scores, though somewhat simplify the broad range of computing work that researchers strive to accomplish on these massive systems.
• A total of 39 systems now us graphics chips as accelerators for some computing tasks. That's the approach employed by a forthcoming Cray-built system with AMD 16-core processors and Nvidia Tesla chips slated for shipment to the National Center for Supercomputing Applications.
• IBM supplied 223 of the 500 systems and Hewlett-Packard supplied 146.
• At least 29 of the systems gulp down more than 1 megawatt of power--enough to power 10,000 100-watt light bulbs. The K Computer consumes 12.66 megawatts, but it's "one of the most efficient systems on the list," with a performance of 830 megaflops per watt, the list organizers said.
The Top500 supercomputer list shows plenty of changes over the 
years, but one constant is surging performance. This chart at the 
top shows performance in calculations per second, with a logarithmic 
scale that makes the rate of change look steady--for example by 
making the jump from 1 teraflops to 10 teraflops look as significant 
as the jump from 10 teraflops to 100 teraflops.


(Credit: Top500.org)

Thursday, February 23, 2012

Complete the function getFirstLetterWord,

Complete the function getFirstLetterWord, which takes in a string text,consisting of only lowercase letters and spaces. A word is a maximal sequence of consecutive letters. There may be multiple spaces between words. Also, text may contain only spaces.
The function getFirstLetterWord is expected to return the word which is formed by concatenating the first letter from each word in text, in the order they appear.Return an empty string is no word is possible

Sample Test Cases:

Input #00:
the quick brown fox jumped over the lazy dog

Output #00:
tqbfjotld

Explanation:
Picking up the 1st character from each of the words in the sentence, we get, tqbfjotld


Input #01:
dice     gambling     las vegas

Output #01:
dglv

Explanation:
Ignore multiple spaces, picking the 1st character from dice, gambling, las and vegas results in dglv




import java.io.FileReader;
 
class WordCount 
{
 
public static void main(String args[]) throws Exception 
{
 
String text="dice       gambling       las    vegas";//"the quick brown fox jumped over the lazy dog";
 
char ch[]=new char[text.length()];
char c;
boolean lastWhite = true;
String whiteSpace = " \t";
int i=0;
 
   for(i=0;i<text.length();i++)
   {
        c=text.charAt(i);
 
        int index = whiteSpace.indexOf(c);
        if (index == -1)
        {
                  if (lastWhite == true)
                  {
                      ch[i]=c;
                  }
        
          lastWhite = false;
 
        }
 
        else
 
        {
 
                lastWhite = true;
 
        }
 
  }
 
    String ss = new String(ch);
    System.out.println(ss);
 
 }
 
}
Run Here http://ideone.com/zVquq 

WAP to Count Tottal number of Characters, Words and Lines in File Efficiently

Guys Think its Funny & Can be solved Easily..but when interviewer ask how u counts no of words when u have more then 1 spaces or tabs,line feeds or new lines , i mean white spaces ?? Its Asked Recently from one of the my friend in Amazon & Adobe Both

here is the solution i have taken car of such Scenario

import java.io.FileReader;

class WordCount {
public static void main(String args[]) throws Exception {
int words = 0;
int lines = 0;
int chars = 0;

FileReader fr = new FileReader("E:/ubuntu/tests.txt");
int c = 0;
boolean lastWhite = true;
String whiteSpace = " \t\n\r";
char sp=' ';
char tab=' ';
char lin='\n';
char ret='\r';

System.out.println(" " +(int)sp + " " + (int)tab + " " + (int)lin + " " + (int)ret);

while ((c = fr.read()) != -1)
{
chars++;

System.out.println(c);

if (c == '\n')
{
lines++;
}

int index = whiteSpace.indexOf(c);
//icrement word count when 1st time index of any spaces occurs -1 so set next
//using boolena value lastwhite time it to false

if (index == -1)
{
if (lastWhite == true)
{
++words;
}
lastWhite = false;
}
else
{
lastWhite = true;
}

System.out.println("chars" + chars + " words" + words + " lines " + lines);
}

/*if (chars != 0)
{
++lines;
}*/


}
}

WAP to Print a Binary tree in level order with a new line after every level.

Data Structure Used Queue

Algorithm Shown Below

printLevelorder(tree)
Initialize the global variable size=0
1) Create an empty queue q
2) temp_node = root /*start from root*/ & initialize the local variable cur_size=0
3) Loop while temp_node is not NULL
A) print temp_node->data.
B) Enqueue temp_node’s children (first left then right children) to q
C) After this check cur_size is equals to zero or not
if(cur_size==0)set cur_size=size of queue(no of elements at that time in queue
D) Dequeue a node from q and assign it’s value to temp_node
E) Decrement the cur_size until it become zero so that we can re-initialize it
again with new size of queue.


#include
#include
#define MAX_Q_SIZE 100

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/* frunction prototypes */
struct node** createQueue(int *, int *);
void enQueue(struct node **, int *, struct node *);
struct node *deQueue(struct node **, int *);

int size=0;

/* Given a binary tree, print its nodes in level order
using array for implementing queue */
void printLevelOrder(struct node* root)
{
int rear, front;
struct node **queue = createQueue(&front, &rear);
struct node *temp_node = root;
int nsize=0;

while(temp_node)
{
printf("%d ", temp_node->data);

/*Enqueue left child */
if(temp_node->left)
enQueue(queue, &rear, temp_node->left);

/*Enqueue right child */
if(temp_node->right)
enQueue(queue, &rear, temp_node->right);
if(nsize==0)
{
nsize=size;
printf( " \n ");
}

/*Dequeue node and make it temp_node*/
temp_node = deQueue(queue, &front);
nsize--;
}
}

/*UTILITY FUNCTIONS*/
struct node** createQueue(int *front, int *rear)
{
struct node **queue =
(struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE);

*front = *rear = 0;
return queue;
}

void enQueue(struct node **queue, int *rear, struct node *new_node)
{
queue[*rear] = new_node;
(*rear)++;
size++;
}

struct node *deQueue(struct node **queue, int *front)
{
(*front)++;
size--;
return queue[*front - 1];
}

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
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);
}

/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->left->left = newNode(41);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->right->right = newNode(71);


printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);

getchar();
return 0;
}

Time Complexity O(n)
Space Complexity O(1)
Run Here
https://ideone.com/FLgSI

Write a method to shuffle a deck of cards. It must be a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.


Thursday, February 16, 2012

Design The Algorithm for AutoComplete Feature of Google

Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s


Input text- 
next

select output from 
nextelement       ---- Answer
nextpermutation






Wednesday, February 15, 2012

Device An Algorithm to Find minimal number of moves the to pegs to transform from the initial to final configuration. .

There are K pegs. Each peg can hold discs in decreasing order of radius when looked from bottom to top of the peg. There are N discs which have radius 1 to N; Given the initial configuration of the pegs and the final configuration of the pegs, output the moves required to transform from the initial to final configuration. You are required to do the transformations in minimal number of moves.
  • A move consists of picking the topmost disc of any one of the pegs and placing it on top of anyother peg.
  • At anypoint of time, the decreasing radius property of all the pegs must be maintained.

Tuesday, February 14, 2012

Convert Given Message Sequence in to Corrsponding Digits

The Latin alphabet contains 26 characters and telephones only have ten digits on the keypad. We would like to make it easier to write a message to your friend using a sequence of keypresses to indicate the desired characters. The letters are mapped onto the digits as shown below. To insert the character B for instance, the program would press 22. In order to insert two characters in sequence from the same key, the user must pause before pressing the key a second time. The space character ' ' should be printed to indicate a pause. For example, 2 2 indicates AA whereas 22 indicates B.



Example

hi      Case #1: 44 444
yes     Case #2: 999337777
foo bar Case #3: 333666 6660 022 2777
hello world   Case #4: 4433555 555666


Follow Up-Now Think if Question asked reverse e.g.
Given a telephone number print or produce all the possible telephone words or combinations of letters that can represent the given telephone number, then can you device an algorothm that will solve this problem efficiently. This is More Simple Then Previous One.

How fast can robots can complete the given sequence

Blue and Orange are friendly robots. An evil computer mastermind has locked them up in separate hallways to test them, and then possibly give them cake.
Each hallway contains 100 buttons labeled with the positive integers {1, 2, ..., 100}. Button k is always k meters from the start of the hallway, and the robots both begin at button 1. Over the period of one second, a robot can walk one meter in either direction, or it can press the button at its position once, or it can stay at its position and not press the button. To complete the test, the robots need to push a certain sequence of buttons in a certain order. Both robots know the full sequence in advance. How fast can they complete it?
For example, let's consider the following button sequence:
   O 2, B 1, B 2, O 4
Here, O 2 means button 2 in Orange's hallway, B 1 means button 1 in Blue's hallway, and so on. The robots can push this sequence of buttons in 6 seconds using the strategy shown below:
Time | Orange           | Blue
-----+------------------+-----------------
  1  | Move to button 2 | Stay at button 1
  2  | Push button 2    | Stay at button 1
  3  | Move to button 3 | Push button 1
  4  | Move to button 4 | Move to button 2
  5  | Stay at button 4 | Push button 2
  6  | Push button 4    | Stay at button 2
Note that Blue has to wait until Orange has completely finished pushing O 2 before it can start pushing B 1.

Thursday, February 9, 2012

catalan number pdfs

http://mathcircle.berkeley.edu/BMC6/pdf0607/catalan.pdf
http://www-math.mit.edu/~rstan/ec/catadd.pdf

How many paths from one corner to the diagonally opposite corner in an n x n matrix do not cross the diagonal?


A sequence of n numbers, 1 thru n, is processed as follows: we either drop the next number into a stack, or we pop the topmost number of the stack. In 2n operations, all numbers would have been processed and the stack would also be empty. The output is the sequence of elements that were popped. How many output sequences are possible?


In how many ways may we pick a subset from 1, 2, 3, 4, … n so that no two successive numbers are picked?


The Britney Spears Problem ,Tracking who's HOT and who's not , presents an algorithmic challenge ?

 By Brian Hayes
  • Back in 1999, the operators of the Lycos Internet portal began publishing a weekly list of the 50 most popular queries submitted to their Web search engine. Britney Spears—initially tagged a "teen songstress," later a "pop tart"—was No. 2 on that first weekly tabulation. She has never fallen off the list since then—440 consecutive appearances when I last checked. Other perennials include ­Pamela Anderson and Paris Hilton. What explains the enduring popularity of these celebrities, so famous for being famous? That's a fascinating question, and the answer would doubtless tell us something deep about modern culture. But it's not the question I'm going to take up here. What I'm trying to understand is how we can know Britney's ranking from week to week. How are all those queries counted and categorized? What algorithm tallies them up to see which terms are the most frequent?
                                  
  • One challenging aspect of this task is simply coping with the volume of data. Lycos reports processing 12 million queries a day, and other search engines, such as Google, handle orders of magnitude more. But that's only part of the problem. After all, if you have the computational infrastructure to answer all those questions about Britney and Pamela and Paris, then it doesn't seem like much of an added burden to update a counter each time some fan submits a request. What makes the counting difficult is that you can't just pay attention to a few popular subjects, because you can't know in advance which ones are going to rank near the top. To be certain of catching every new trend as it unfolds, you have to monitor all the incoming queries—and their variety is unbounded.
  • In the past few years the tracking of hot topics has itself become a hot topic in computer science. Algorithms for such tasks have a distinctive feature: They operate on a continuous and unending stream of data, rather than waiting for a complete batch of information to be assembled. Like a worker tending a conveyor belt, the algorithm has to process each element of the stream in sequence, as soon as it arrives. Ideally, all computations on one element are finished before the next item comes along.
  • Much of the new interest in stream algorithms is inspired by the Internet, where streams of many kinds flow copiously. It's not just a matter of search-engine popularity contests. A similar algorithm can help a network manager monitor traffic patterns, revealing which sites are generating most of the volume. The routers and switches that actually direct the traffic also rely on stream algorithms, passing along each packet of data before turning to the next. A little farther afield, services that filter spam from e-mail can use stream algorithms to detect messages sent in thousands or millions of identical copies.
  • Apart from the Internet, stream algorithms are also being applied to flows of financial data, such as stock-market transactions and credit-card purchases. If some government agency wanted to monitor large numbers of telephone calls, they too might have an interest in stream algorithms. Finally, the designers of software for some large-scale scientific experiments adopt a stream-oriented style of data processing. Detectors at particle-physics laboratories produce so much data that no machine can store it all, even temporarily, and so preliminary filtering is done by programs that analyze signals on the fly....................................................to be contd. :)
Interested People Can Read Full Article Here
http://amsciadmin.eresources.com/libraries/documents/2008631225466814-2008-07Hayes.pdf

Identify the ‘Bottleneck Spanning Tree’ of an undirected graph

Given an undirected graph, identify the ‘Bottleneck Spanning Tree’ of an undirected graph, which is defined to be any spanning tree that minimizes the weight of the heaviest edge used in the tree. In the usual ‘Minimum Spanning Tree’ problem, the sum of weights is minimized.

Identify if a given graph is a scorpion or not.

A scorpion is an undirected graph with 3 special vertices: the sting, the tail, and the body. The sting has degree one and is connected to the tail. The tail has degree two and is connected to the sting and the body. The body has degree n – 2 and is connected to all vertices except the sting. The other vertices may be arbitrarily connected with each other. Identify if a given graph is a scorpion or not.

Gray Code for Fibonacci Sequences: identify the starting string and then enumerate these positions in time proportional to the number of strings.

The number of binary strings of length k such that two 1′s are never adjacent in any string equals the k-th Fibonacci number. Further, these strings can be ordered to form a Gray code, which means that successive strings differ in only one position. For example, a Gray code for 3-bit strings is 100 101 001 000 010. The goal is to identify the starting string and then enumerate these positions in time proportional to the number of strings.

Working Computer Problem :discover an undamaged computer in as few queries as possible.

A room has n computers, less than half of which are damaged. It is possible to query a computer about the status of any computer. A damaged computer could give wrong answers. The goal is to discover an undamaged computer in as few queries as possible.

Monday, February 6, 2012

implement procedure find(N,X) that returns 1 if there exists a sensor at height X and returns 0 otherwise.

Animal behavior researchers would like to get information on animal movements in a valley. They have placed N motion sensors along a straight line crossing the valley at various heights. For 0 <= i <= N-1, the i-th sensor's height is hi (0 <= hi <= 1 000 000 000). No two sensors are on the same height.
Since the line is on a valley, the heights of sensors satisfy these constraints:
  • there is an integer k (0 <= k <= N-1), such that the k-th sensor has the minimum height,
  • for all 0 <= i < k, hi > hi+1, and
  • for all k <= i < N-1, hi < hi+1.
However, because the sensor installation team forgot to measure the sensors' heights, the value of k, and all the heights hi's are not known.
You would like to find if there is a sensor at height X. This seems to be hopelessly impossible, but you recall that each sensor has a height meter and can report its height. To minimize the power usage, you would like to make only a small number of height queries.

Implement

You have to implement procedure find(N,X) that returns 1 if there exists a sensor at height X and returns 0 otherwise. Your procedure can call a procedure query(i) to get hi. However, you can make at most 50 calls, for each run of procedure find.
Note: In a single run, the sample grader, provided with the prototype, may perform many calls to find in one run. While the sample grader uses the same heights for all calls, the real grader may use different heights between each call to procedure find. Therefore, you should not assume that two different calls to procedure find share the same height information.

Example

Suppose that N=4 and the height of each sensor is:
sensorheight
010
17
29
315
Note that in this case, k=1. The following are the return values from procedure query:
callsreturns
query(0)10
query(1)7
query(2)9
query(3)15
The correct implementation of procedure find, when called by the grader, should return as in the following table.
callsreturns
find(4,10)1
find(4,2)0
find(4,9)1
find(4,15)1
find(4,100)0

find the maximum sum of temperatures of K consecutive days

Thailand is a tropical country. Thai people usually say that Thailand has 3 seasons: Hot Summer, Hotter Summer, and Hottest Summer. It especially feels very hot when you have many consecutive days with high temperatures.
You are planning a K-day trip to Thailand. Since you would like to experience the real Thai Summer, you want your stay to be as hot as possible.
You are given a list of forecasted temperatures of N consecutive days. You would like to find the maximum sum of temperatures of K consecutive days. It is guaranteed that 1 <= K <= N.

Implement 

You are to implement procedure maxk(N,T,K) that returns the maximum sum of temperatures of any K consecutive days, where N is the number of days and T is an array of positive integers where T[i], for 0 <= i < N, is the temperature of day i.

Example

Suppose that N=6, K=3 and T = 10 50 30 20 5 1.

There are 4 possible 3-day trips, starting from day 0, day 1, day 2, and day 3; and their sum of temperatures are 90, 100, 55, and 26. Therefore, procedure maxk should return 100.

Subtasks

Subtask 1

  • N <= 1 000, 0 < T[i] <= 1 000

Subtask 2

  • N <= 1 000 000, 0 < T[i] <= 1 000

you have to encode the data into a sequence of alphabets, transmit the encoded data, and decode it to obtain the original integer data.

You would like to transmit integer data through a special channel, i.e., this channel only supports transmission of alphabets a - z. In order to do so, you have to encode the data into a sequence of alphabets, transmit the encoded data, and decode it to obtain the original integer data.
The overall process is shown in the following figure.

       You have to implement:
  • Procedure encode(N,D) that encodes the data, where N denotes the length of data and D is an array of integers representing the data, where D[i] is the i-th integer in the data. (0 <= D[i] <= 255.) This procedure must call procedure send_data(c) for each character c in the sequence to transmit the encoded data. Each encoded character c must be lowercase English alphabets, i.e., alphabets a - z.

    Procedure decode(M) that decodes the data, where M denotes the length of the encoded data. To read the encoded data as a sequence of characters, this procedure must call procedure read_data() for each character in the sequence. It may call read_data for at most M times. To output the decoded data, it must call procedure output_data(y) for each integer y in the decoded data.

     Follow Up

    Subtask 1

  • N <= 100 and 0 <= D[i] <= 25.
  • The encoded data should not contain more than 100N characters, i.e., encode may not call send_data more than 100N times.

        Subtask 2

  • N <= 100.
  • The encoded data should not contain more than 100N characters, i.e., encode may not call send_data more than 100N times.

        Subtask 3 (40 points)

  • N <= 100.
  • The encoded message should not contain more than 2N characters, i.e., encode may not call send_data more than 2N times.

Sunday, February 5, 2012

You need to write a program that calculates the advanced edit distance of two given words.

The edit distance of two strings S and T is the minimum number of edit operations that need to be done to transform S into T . The valid edit operations are:
• Insert a single character at any position.
• Modify an existing character.
• Remove an existing character.
For example, the edit distance of “pantera” and “aorta” is 5, because the following chain of
edits is valid (and there is no shorter chain):
“pantera” >>> “antera” >>> “aotera” >>> “aoera” >>> “aora” >>> “aorta”.
We define the advanced edit distance in a similar way, but adding the swap of two adjacent characters as an extra valid operation. With this setting, the advanced edit distance of “pantera” and “aorta” is 4:
“pantera” >>> “antera” >>> “antra” >>> “aotra” >>> “aorta”.

You need to write a program that calculates the advanced edit distance of two given words.

Friday, February 3, 2012

In given array of elements like [a1,a2,a3,..an,b1,b2,b3,..bn,c1,c2,c3,...cn] Write a program to merge them like [a1,b1,c1,a2,b2,c2,...an,bn,cn]. We have to do it in O(1) extra space.

Transpose Algorithm 
Basically, we are converting rows into columns. E.g. a1 a2 a3 a4 b1 b2 b3 b4 c1 c2 c3 c4 should be changed to a1 b1 c1 a2 b2 c2 a3 b3 c3 a4 b4 c4.
a1 b1 c1 (i=1)
a2 b2 c2 (i=2)
a3 b3 c3 (i=3)
a4 b4 c4 (i= 4)

So we should write the array as a1 a2 a3 a4 b1 b2 b3 b4........, only this time, we are writiing column wise.
The program is recursive. The variable i is the number of groups
#include
#define SIZE 12 //multiple of 3
void arrange(int arr[], int n, int i)
{

if(i == 1)
{
arr[1] = arr[n];
arr[2] = arr[n <<1]
return;
}
int a = arr[i - 1];
int b = arr[n + i - 1];
int c = arr[2*n + i - 1];

arrange(arr, n, i - 1);

int x = 3 * (i - 1);
arr[x] = a;
arr[x + 1] = b;
arr[x + 2] = c;
}

int main()
{
int n = SIZE;
int a[SIZE], i;
printf("\nEnter %d numbers", SIZE);
for(i = 0; i <>
scanf("%d", a + i);
if(n != 0 && n % 3 == 0)arrange(a, n/3, n/3);
for(i = 0; i <n;i++)
printf(a[i]);

printf("\n");
}

Given a root and a node of a BST tree, write a function which print all the nodes which are a 'k' distance from the given nodes in sorted order. (distance can be upwards and downwards)


Given a function getInorderSuccessor which takes a BST (Binary Search Tree) as it's parameter. Every node has an extra pointer "next" , which is intialized to null, fill next with node pointers which represent Inorder Successor.


Design a Architecture of Online Movie Booking System . Find the possible issues and Idea to Resolve them. How do you optimize the Performance against all these issues.


We are interested to find out the number of Distinct customer visited at-least p distinct pages within exactly T days.

Suppose, Amazon have a Logging system Like This:
They Track all logs daily basis, stored in separate log file.Log contains a collection of tuples of Customer ID and Page ID. The length of Customer ID and Page ID is L1 and L2. Suppose We have a log of D-days , and size of each log fine can be Order of n , where n be the number of customer.
In a most generalized situation, you can assume that a customer can visit the same page multiple times in a day or any number of days.
We are interested to find out the number of Distinct customer visited at-least p distinct pages within exactly T days.
Propose a Data Structure to be use to solve this problem efficiently . Design an Algorithm to solve this problem and Find out the complexity of the algorithm.

Thursday, February 2, 2012

how many heaps can be created with complete binary tree of n nodes

Alex is curious about data structures. He is working on binary trees recently and particularly interested in complete binary trees.
A complete binary tree satisfies that all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.
Alex defines his own complete binary tree: each node has a weight, while father's is always less than or equal to its sons'. He names this complete binary tree as minimum heap.
Now he wants to know: With N nodes weighted from 1 to N (each appears once), how many heaps can be created. The answer (represented by Q) may be very large, so please output a number P while P = Q mod M.

Followed Up:
Consider a complete binary tree of height n, where each edge is a one Ohm resistor. Suppose all the
leaves of the tree are tied together. Approximately how much is the effective resistance from the root to thisbunch of leaves for very large n?

(a) Exponential in n
(b) Cubic in n
(c) Linear in n
(d) Logarithmic in n
(e) Of the order square root of n