Tuesday, June 21, 2011

Given an array of integers, find out number of ways in which you can select increasing subsequences of length k(k<=n).

eg array is 1 4 6 2 5 & k=3
Output: 3
Sequences: 1 4 6, 1 4 5, 1 2 5


Question is a variant of longest increasing sub sequence problem(LIS Problem) or longest consecutive elements

See http://en.wikipedia.org/wiki/Longest_increasing_subsequence

Data Structure: Array
Algorithm:LIS


Working Code:By Manu

import java.io.*

class LISOfLengthK
{

private static void lisOfLengthK(Integer [] inputArray, int k) {
int n = inputArray.length, temp, count;
Integer [] best = new Integer[n];
Integer [] last = new Integer[n];
Integer [] outputArray = new Integer[k];
for(int i=0;i inputArray[i]) {
best[j] = best[i]+1;
last[j] = i;
if(best[j] == k) {
temp = j;
count =0;
outputArray[count++] = inputArray[temp];
while(last[temp] != -1) {
outputArray[count++] = inputArray[last[temp]];
temp = last[temp];
}
for(int index=k-1;index>=0;index--)
System.out.print(outputArray[index] + " ");
System.out.println();
}
}
}
}
}

public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Integer [] inputArray = new Integer[n];
for(int i=0;i inputArray[i] = Integer.parseInt(br.readLine());
int k = Integer.parseInt(br.readLine());
lisOfGivenLength(inputArray, k);
}

}


Time Complexity O(N^2)
Space Complexity O(1)
https://ideone.com/Jbtw0

WAP Convert Set of Nodes of Binary Tree where each node contains two value i, j & i value follow BST property , j value follow Heap Property, Build BST form these Nodes.

A rooted binary tree with keys in its nodes has the binary search tree
property (BST property) if, for every node, the keys in its left
subtree are smaller than its own key, and the keys in its right
subtree are larger than its own key. It has the heap property if, for
every node, the keys of its children are all smaller than its own key.
You are given a set of n binary tree nodes that each contain an
integer i and an integer j. No two i values are equal and no two j
values are equal. We must assemble the nodes into a single binary tree
where the i values obey the BST property and the j values obey the
heap property. If you pay attention only to the second key in each
node, the tree looks like a heap, and if you pay attention only to the
first key in each node, it looks like a binary search tree.Describe a
recursive algorithm for assembling such a tree

Indirectly They Asked to Implement Treap

Data Structure: Treap( Heap + Binary Search Tree)

Algorithm:
1.Sort the nodes in decreasing order of their j values and then simply build the
2.BST according to the i values starting from the first node in the obtained sorted
list. The first node will be the root. For example, let the given nodes (i,j
pairs) be:

so our structure of node will looks like this

struct node
{
int i;
int j;
struct node *left;
struct node *right;
};



For Example:
(12,6) (18,25) (19,10) (17,5) (19,10) i.e. 5 nodes
nodes after sorting in decreasing order according to j values:
(18,25) (16,11) (19,10) (12,6) (17,5)
So the tree would be something like this:


(18,25)
|
| |
(16,11) (19,10)
|
| |
(12,6) (17,5)


Working Code:


#include
#include



struct node
{
int i;
int j;
struct node *left;
struct node *right;
};


void mySwap(struct node **n1, struct node **n2)
{
struct node *tmp;
tmp = *n1;
*n1 = *n2;
*n2 = tmp;
}


struct node *myInsert(struct node *root, struct node *nodeToInsert)
{
if(root == NULL)
{
return nodeToInsert;
}
else
{
if(nodeToInsert->i <= root->i)
{
root->left = myInsert(root->left,nodeToInsert);
}
else
{
root->right = myInsert(root->right,nodeToInsert);
}
return root;
}
}


void myFunc(struct node *arr[], struct node **resultTree, int size)
{
if(!size)
return;
int ind;
int maxInd = 0;
for(ind=0;indj > arr[maxInd]->j)
maxInd = ind;
*resultTree = myInsert(*resultTree,arr[maxInd]);//inserting node with maximum j value
mySwap(&arr[maxInd],&arr[size-1]);
myFunc(arr,resultTree,size-1);
}


int main()
{
int n;
struct node *arr[100];
scanf("%d",&n);
int ind;
int ival,jval;
struct node *result = NULL;
for(ind=0;indi = ival;
arr[ind]->j = jval;
arr[ind]->left = NULL;
arr[ind]->right = NULL;
}
myFunc(arr,&result,n);
//levelOrderTraversal(result);
//PreOrderTraversal(result);
for(ind=0;ind free(arr[ind]);
return 0;
}

Solution Given BY Vipul

Time Complexity O(N^2)
Space Complexity O(logn)
Run Here https://ideone.com/o7dfU

WAP to Find Two Leaf Nodes in Binary Tree such that F(x,y) is maximum

Given a binary tree, find 2 leaf nodes say X and Y such that F(X,Y) is maximum where F(X,Y) = sum of nodes in the path from root to X + sum of nodes in the path from root to Y - sum of nodes in the common path from root to first common ancestor of the Nodes X and Y


Data Structure: Binary Tree

Algorithm:


Working Code:




Time Complexity
Space Complexity

WAP to Find Number of Pairs of Intersecting Disc ,Given Array of N Integers .

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius A[i]. We say that k-th disc and j-th disc intersect, if k! =j and k-th and j-th discs have at least one common point.

Write a function

class Solution { public int number_of_disc_intersections(int[] A); }

which given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and

A[0]=1 A[1]=5 A[2]=2 A[3]=1 A[4]=4 A[5]=0

there are 11 pairs of intersecting discs:

0th and 1st
0th and 2nd
0th and 4th
1st and 2nd
1st and 3rd
1st and 4th
1st and 5th
2nd and 3rd
2nd and 4th
3rd and 4th
4th and 5th

so the function should return 11.

The function should return -1 if the number of intersecting pairs exceeds 10,000,000. The function may assume that N does not exceed 10,000,000

Hint & Algorithms: Use HashTable , Linear Probing Based, in Case of Collision increment Corresponding Counter,if i am correct ,coding part is very easy, still if get time, will surely put running code here as usual :) Happy Coding

Time Complexity O(N) Where N is Size of Array
Space Complexity O(N)

WAP to Find equilibrium index in Unsorted Array of Size N, Efficiently

The equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:

A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0

3 is an equilibrium index, because:
A[0]+A[1]+A[2]=A[4]+A[5]+A[6]

6 is also an equilibrium index, because:
A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0

(The sum of zero elements is zero) 7 is not an equilibrium index - because it is not a valid index of sequence A. If you still have doubts, here is a precise definition: The integer k is an equilibrium index of a sequence A[0],A[1]..,A[n-1] if and only if 0<= k and sum(A[0..(k-1)])=sum(A[(k+1)..(n-1)]). Assume the sum of zero elements is equal to zero.

Write a function
int equi(int A[], int n)

that, given a sequence, returns its equilibrium index (any) or -1 if no equilibrium index exists. Assume that the sequence may be very long.

The problem can be solved by using various approaches, the most common being simply to follow the equilibrium definition:

int equi ( int A[], int n ) {
int k, m, lsum, rsum;
for(k = 0; k < n; ++k) {
lsum = 0; rsum = 0;
for(m = 0; m < k; ++m) lsum += A[m];
for(m = k + 1; m < n; ++m) rsum += A[m];
if (lsum == rsum) return k;
}
return -1;
}

Time Complexity o(N^2)
Space Complexity O(1)
Run Here https://ideone.com/fThsV

Unfortunately, this approach has two disadvantages:

* it fails on large input data sets, since the time complexity is O(n2)
* it fails on large input values (for example if the input array contains values like MIN/MAX_INT) due to the arithmetic overflows

The solution analysis will detect such problems in submitted code:

Optimized Solution

We can fix the first problem with a better algorithm, and the second problem with a better data-type (for example, using long long type instead of int for sum computations). The key observation for better running time is to update the left/right sums in constant time instead of recomputing them from the scratch.

int equi(int arr[], int n) {
if (n==0) return -1;
long long sum = 0;
int i;
for(i=0;i
long long sum_left = 0;
for(i=0;i long long sum_right = sum - sum_left - (long long) arr[i];
if (sum_left == sum_right) return i;
sum_left += (long long) arr[i];
}
return -1;
}


Using this solution, you can obtain a perfect answer:

To return all equilibrium index we can print instead of returning the single index

Time Complexity O(N)
Space Complexity O(1)
Run Here https://ideone.com/OKM8d

Construct Binary Tree From Ancester Matrix Efficiently

You are given a matrix M[n, n] for a tree with n nodes. In the given matrix M, M[i, j] is true iff node j is an ancestor of node i. Construct the tree from the given matrix.

For example, you are given below matrix.

1 2 3 4
1 0 1 1 0

2 0 0 1 0

3 0 0 0 0

4 0 1 1 0

You need to construct the below tree. In the constructed tree ancestor relationship should be correct. A node can come on left or right of its parent as you cannot determine this information from the ancestor matrix

Node numbers used in matrix are in bracket
5(3)
/
/
10(2)
/ \
/ \
12(1) 13(4)


Data Structure Used: 2-D Array , Binary Tree

Algorithm


Time Complexity
Space Complexity

Given an array and an integer k, find the maximum for each and every contiguous sub array of size k.

Sample Input :
1 2 3 1 4 5 2 3 6
3 [ value of k ]

Sample Output :
3
3
4
5
5
5
6

This Question is Asked By Google Indirectly for Maximum in window or subarray of size k in array of size n, yes it is sliding window problem, as window slides we need to find out the maximum in each window. is it ??

Input: A long array A[], and a window width w
Output: An array B[], B[i] is the maximum value of from A[i] to A[i+w-1]
Requirement: Find a good optimal way to get B[i]

Solution: It Can Solved By Two Ways in This Question Data Structure Plays Important Role

The obvious solution with run time complexity of O(nw) is which is not efficient enough. Every time the window is moved, we have to search for the maximum from w elements in the window. where w is size of window & n is size of array

1st Method(Naive Approach)

Data Structure Used : Array
Algorithm: A.for all i=0 to n-w+1 (we should have at-least w elements in window)
B.for all j=i to i+w (keep incrementing windows size form left to right)
C find maximum inn each window & print it or put in array (Auxiliary)

#include

void printMaxInSlidingWindows(int a[],int n,int w)
{

int max=0;
int i=0,j=0;

for (i = 0; i max)
}
max=a[j];

}

}
printf( " %d ", max);
}

}

int main()
{
int a[]={1,3,-1,-3,5,3,6,7};
printMaxInSlidingWindows(a,8,3);
}

TC O(nw)
SC O(1)
Run Here http://ideone.com/7o3Ta


2nd Method

Data Structure Used: Queue(More Efficient)

We need a data structure where we can store the candidates for maximum value in the window and discard the element, which are outside the boundary of window. For this, we need a data structure in which we can edit at both the ends, front and back. Deque is a perfect candidate for this problem.

We are trying to find a way in which, we need not search for maximum element among all in the window. We will make sure that the largest element in the window would always appear in the front of the queue.
While traversing the array in forward direction if we find a window where element A[i] > A[j] and i > j, we can surely say that A[j], will not be the maximum element for this and succeeding windows. So there is no need of storing j in the queue and we can discard A[j] forever.
For example, if the current queue has the elements: [4 13 9], and a new element in the window has the element 15. Now, we can empty the queue without considering elements 4, 13, and 9, and insert only element 15 into the queue.

Every time, we move to a new window, we will be getting a new element and leave an old element. We should take care of:
Popping elements outside the window from queue front.
Popping elements that are less than new element from the queue.
Push new element in the queue as per above discussion.

Note:Optimization Done In Done so that we can Find The Maximum of Each Window in O(1)

Here Is Tunning Code

import java.util.*;

class Maximumin_SlidingWindow
{

public static void main(String ar[])
{

Integer a[]=new Integer[]{1,3,-1,-3,5,3,6,7};
int w=3,i=0;
int size=a.length;
Integer b[]=new Integer[size-w+1];

maxSlidingWindow(a,size,w,b);

for(i=0;iQ=ar[0];

//Initilize deque Q for first window
for (int i = 0; i < w; i++) { while (!Q.isEmpty() && A[i] >= A[Q.peekLast()])
Q.pollLast();
Q.offerLast(i);
}

for (int i = w; i < n; i++) { B[i-w] = A[Q.peekFirst()]; //update Q for new window while (!Q.isEmpty() && A[i] >= A[Q.peekLast()])
Q.pollLast();

//Pop older element outside window from Q
while (!Q.isEmpty() && Q.peekFirst() <= i-w)
Q.pollFirst();

//Insert current element in Q
Q.offerLast(i);
}
B[n-w] = A[Q.peekFirst()];
}

}

TC O(n)n Since Eacj Array Element is Inserted & deleted At-Most Once
SC O(1)
Run Here http://ideone.com/KLIpO
http://ideone.com/TftYg

Which is the Best Data structure which is supposed to log number of user requests per second.

Make a Data structure which is supposed to log number of user requests per second. At any point of time your boss can ask you the number of hits for the last 60 seconds. It can be at any time for example he will say at 71st second that tell me how many hits for past 30 seconds or something, but this window can go maximum upto 60 seconds to in the previous example 11 to 71.


Data Structure Used: Queue(Basic Approach),Circuler Queue,Binary Index Tree(Most Efficient)

Algorithm & Solution

Take a queue of length 60. Each second do a Deque() and enque(#of users logged this second). For query traverse from tail of the queue to that many seconds as asked and sum all of those.

Algorithm: (Optimized with array)

N <- 60
A is an array of length N. holds the queue. Initialized to 0.
p is the pointer to head of the queue
tick is the system clock whose value increases by 1 each second

enque (n) // does a simultaneous deque()
{
p <- (p+N-1) mod N
A[p] <- n
}

update()
{
n <- 0
t <- tick
while true
{
if( t == tick && new user has logged in)
{
n <- n+1
}

else if (t < tick)
{
enque(n)
n <- 0
t <- tick
}

}
Query(t)
{
sum <- 0
for i <- 0 to t-1
{
sum <- sum + A[ (p+i) mod N]
}

return sum
}

where tick is the memory/register where system keeps track of each second passed by incrementing its value by 1 every second. tick can be read by any program in the system but can be written only by system clock hw/sw. Now, in the 'while' loop, eventually tick will be incremented by system clock hw/sw each second behind the scene, while, t will remain at previous value and an enque() will happen along with update of t.
This algorithm is optimized for enque() since this happens every second while a Query happens asynchronously and its frequency might be too less than frequency of enque() operations.

Time Complexity
Space Complexity

Optmization

We can use Binary Indexed Tree/ Fenwick Tree. Updating the array as well cumulative sum will be of O(log n) complexity.

Of course we have to put a limit to after which time(i/p) we cant query as we cant store infinite amount of data, or if yes partioning of data would be needed(if thats the intention the above is not efficient).

Feel Free to Comment or Optimize The Solution

Monday, June 20, 2011

WAP to Find Maximum Windows of Matching Character , You Given two Sequences

Given two sequences of length N, how to find the max window of matching patterns. The patterns can be mutated.

For example, seq1 = "ABCDEFG", seq2 = "DBCAPFG", then the max window is 4. (ABCD from seq1 and DBCA from seq2)

Data Structure :Hash Table

Algorithm:

INDEX:01234567
SEQ1 = "ABCDEFGK";
SEQ2 = "ZGEDFBAP";

here the expected answer is window of size 4
DEFG
GEDF

we use a map to store the characcters indices of SEQ1
then we search for windows of matching characters from SEQ2
only when the window size is >1, we need to use an temporary array...
we push the indices of the matchin chars from SEQ1 into this array...
here we hav arr = 6 4 3 5 1 0
sort this array, 0 1 3 4 5 6
test for maximum window in this array
3 4 5 6 of size 4


Working Code:

#include
#include
#include
#include
#include

using namespace std;

int main()
{
char seq1[] = "ABCDEFGK";
char seq2[] = "ZGEDFBAP";

map m;
map::iterator iter;
vector arr;
int n1,n2;
n1 = strlen(seq1);
n2 = strlen(seq2);

for(int i = 0;isecond);

}
if(count > 0 && (iter==m.end() || i==n2-1))
{

window = 1;
if(count >1)
{
sort(arr.begin(),arr.end());

//check if the characters in SEQ1 lie in the window of size = count
for(int j=1;j maxwindow) maxwindow = window;
}
}
else maxwindow = 1;
count =0;
arr.empty();

}
}
cout<<"Window of max size is "< getchar();
return 0;
}


Time Complexity O(N^2*logn)
Space Complexity O(1)
Source http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-strings-11
Given two sequences of length N, how to find the max window of matching patterns. The patterns can be mutated.

For example, seq1 = "ABCDEFG", seq2 = "DBCAPFG", then the max window is 4. (ABCD from seq1 and DBCA from seq2)