Showing posts with label Adobe Question. Show all posts
Showing posts with label Adobe Question. Show all posts

Wednesday, May 22, 2013

Given a sequence of n real numbers A(1) ... A(n), determine a contiguous subsequence A(i) ... A(j) for which the sum of elements in the subsequence is maximized


#include<stdio.h>
#define MAX(a,b) ((a>b)?(a):(b))
main()
{
  int arr[]={-2, -3, 4, -1, -2, 1, 5, -3};
  int len,i;
  int max=0;
  len = sizeof(arr)/sizeof(arr[0]);
  max=arr[0];
  int finalmax=0;
  int start=0,end=0;
  for(i=1;i<len;i++)
  {
    max = MAX(max+arr[i], arr[i]); 
      
        finalmax=MAX(max,finalmax);
    
  }
 
    
      printf("MAX:%d %d %d \n",finalmax, start ,end);
 
   
   
}
Example if you want to print array http://codepad.org/BhYxSlp4

Monday, September 24, 2012

You have N computers and [Ca, Cb] means a is connected to b and this connectivity is symmetric and transitive. then write a program which checks that all computers are interconnected and talk two each other

I Believe there are multiple way to solve this problem 1. Here is my approach since graph is connected there will be path from each source to destination vertex , isn't it ? so we can simply run a dfs or bfs for all computers to check if all such path exist , finally we can return & of all operation that means all computer are inter connected and can talk to each other . PS.Since graph is undirected if there exist path from u to v then vice-verse also true so we wont calculate it again.

Sunday, September 23, 2012

Maximum Sum Subsequence in an unsorted array of size n


We are given an array A having n integers. What we want to find is a contiguous subseqnence (A[i], A[i+1], …, A[j]) such that the sum of the elements in that subsequence is maximized. (Note that, in general, there may be more than one such optimal subsequence.)
Note that if all elements in A are non-negative, we could directly return the entire array as the required optimal subsequence.
APPROACH 1
A simple brute-force method could be to compute the sums of all possible subseqnences in A. How many subsequences are there? There are n+ (n-1) + (n-2) + ... + 1 = O(n^2) possible subsequences. Computing the sum of a subsequence takes O(n) in the worst-case. Hence, the running time of the algorithm would be O(n^3).
In C++, we could write the following function to do what was explained above:
// start and end are the starting and ending indices of an optimal subsequence.
void f ( int* A, int n, int &start, int& end)
{
int sum, max = A[0];
for (int i = 0; i < n ; i++)
for (int j = i; j < n; j++)
{
sum = 0;
for (int k = i; k <=j; k++)
sum+= A[k];
if (sum >= max)
{
start = i;
end = j;
max = sum;
}
}
}
————
APPROACH 2:
We can improve the running time to O(n^2) by being a bit more clever in computing the sums of different subsequences. We observe that the sum of the subsequence A[i ... j+1] = A[j+1] + sum of the subsequence A[i ... j].
In C++, we could write as follows:
void f (int *A, int n, int &start, int &end)
{
int sum, max = A[0];
for (int i = 0; i < n; i++)
{
sum = 0;
for (int j = i; j < n; j++)
{
sum + = A[j];
if (sum >= max)
{
start = i;
end = j;
max = sum;
}
}
}
}
———–
APPROACH 3:
Using dynamic programming, we can solve the problem in linear time.
We consider a linear number of subproblems, each of which can be solved using previously solved subproblems in constant time, this giving a running time of O(n).
Let S[k] denote the sum of a maximum sum contiguous subsequence ending exactly at index k.
Thus, we have that:
S[k+1] = max \{S[k] + A[k+1], A[k+1] \} (for all 1 \leq k \leq n-1)
Also, S[0] = A[0].
——–
Using the above recurrence relation, we can compute the sum of the optimal subsequence for array A, which would just be the maximum over S[i] for 0 \leq i \leq n-1.
Since we are required to output the starting and ending indices of an optimal subsequence, we would use another array T where T[i] would store the starting index for a maximum sum contiguous subsequence ending at index i.
In prseducode form, the algorithm would look thus:
Create arrays S and T each of size n.
S[0] = A[0];
T[0] = 0;
max = S[0];
max_start = 0, max_end = 0;
For i going from 1 to n-1:
// We know that S[i] = max { S[i-1] + A[i], A[i] .
If ( S[i-1] > 0)
S[i] = S[i-1] + A[i];
T[i] = T[i-1];
Else
S[i] = A[i];
T[i] = i;
If ( S[i] > max)
max_start = T[i];
max_end = i;
max = S[i];
EndFor.
Output max_start and max_end.
———–
The above algorithm takes O(n) time and O(n) space.
——–
We can however improve upon the space requirements, reducing it to O(1). The key idea is this: for computing S[i] and T[i], all we need are the values of S[i-1] and T[i-1] apart from the given array A. Hence, there is no need to store all n values of the S and T arrays.
We could proceed as follows:
max = A[0];
max_start = 0;
max_end = 0;
S = A[0];
T = 0;
For i going from 1 to n-1:
// S = max { S + A[i], A[i] )
if ( S > 0)
S = S + A[i];
Else
S = A[i];
T = i;
If ( S > max)
max_start = T;
max_end = i;
max = S;
End For.
Output max_end and max_start.
———–
The above algorithm takes O(n) time and O(1) space.

Thursday, February 23, 2012

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;
}*/


}
}

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) 

Sunday, August 28, 2011

find the minimum number of platforms so that all the buses can be placed as per their schedule.

At a bus-station, you have time-table for buses arrival and departure. You need to find the minimum number of platforms so that all the buses can be placed as per their schedule.


Example
 
Bus         Arrival         Departure 
BusA        0900 hrs        0930 hrs
BusB        0915 hrs        1300 hrs
BusC        1030 hrs        1100 hrs
BusD        1045 hrs        1145 hrs
 
Algorithm
 
Its simple dynamic programming question that calculate the 
number of buses at station at any time(when a bus comes or 
leaves). Maximum number in that pool will be nothing but 
the maximum number of buses at the bus-station at any time
,which is same as max number of platforms required.

So first sort
all the arrival(A) and departure(D) time in an int array. 
Please save the corresponding arrival or departure in the 
array also.Either you can use a particular bit for this 
purpose or make a structure. After sorting our array will
look like this: 
 
0900    0915    1930    1030    1045    1100    1145    1300
A       A       D       A       A       D       D       D


Now modify the array as put 1 where you see A and -1 where you see D.
So new array will be like this:
1              1            -1              1               1            -1            -1              -1


And finally make a cumulative array out of this:
1            2              1               2                3            2               1                0


Your solution will be the maximum value in this array. Here it is 3.


I think that code for this will not be complex so I am skipping that part.
The complexity of this solution depends on the complexity of sorting.


Also we don not need to create a cumulative array or an array with 1 and -1;
you just need a counter (cnt) initialized at '0'. Whenever, you find an 'A' in
arrival-departure array, increment cnt by 1. Compare it with maximum value (max);
if it is greater than max, make max equal to cnt. If you get a 'D' in arrival-departure
array, decrement cnt by 1. At the end, return 'max'.
 
Time Compelxity O(nlogn)
Space Complexity O(1) 

Thursday, August 25, 2011

find at what time the maximum number of people will be in the party .

Found This Question on One of the Forum :D & posting here as thought it  seems to be something interesting :) There is a list containing the checkin and checkout time of every person in a party . The checkin time is in ascending order while the checkout is random .
Eg:
                       Check_in                Check_out
Person 1             8.00                          9.00
Person 2             8.15                          8.30
Person 3             8.30                          9.20

and so on ...Now , give an optimized solution to find at what time the maximum number of people will be in the party . 

Algorithm

It has the same Algorithm  That  We have been used to solve Bus-Station Problem :)

Time Compelxity O(nlogn)
Space Complexity O(1) 

Saturday, August 6, 2011

Coin Denomination Problem

Let us say we have an amount we have to pay someone: say $97. The given currency has notes worth $1, $5, $10 and $50. Now, what is the minimum number of currency notes with which the amount can be made? In this case, its eight: two $1 notes, a $5 note, four $10 notes and a $50 notes - eight in all.

If a computer had to solve the same problem, how would it do it? Let us see below. ‘Denomination’ refers to the list of available currency notes: $1, $5, $10 and $50 in this case - each note is a denomination.

In General

Problem: We are given a set of denominations d1,d2,d3,...,dn in increasing order. (Without loss of generality) we assume also that d1=1 (that is, there is always a $1 note, and that is the first denomination) so that it is always possible to produce all amounts from the given denominations. We are also given an amount of money amt. We must use a minimum number of coins (or currency notes) of the given denominations to produce amt.

Great Info http://www.seeingwithc.org/topic1html.html

Tuesday, August 2, 2011

Fill the rectangle with squares

Given a rectangle with known width and height, design an algorithm to fill the rectangle using n squares(n is integer given) and make sure in the result the wasting area is minimized. Length of square doesn't have to be integer.
i.e, given width=3,height=2,n=5, one solution is that rectangle can be filled with five 1x1 squares and the wasting area is 1. Another solution could be filled with five 0.9x0.9 squares, but the wasting area is more than first solution.

Wednesday, July 20, 2011

Design a function getBits that gives x bits from a given position p of a given number n.

Approach

So we need mask for any bit set (10010011 etc). you want to generate a "mask" that pulls only the bits you want to see. So 10010011 or 0x03, I'm interested in xxxxx011. What is the mask that will extract that set ? 00000111 Now I want to be sizeof int independent, I'll let the machine do the work i.e. start with 0 for a byte machine it's 0x00 for a word machine it's 0x0000 etc. 64 bit machine would represent by 64 bits or 0x0000000000000000

Algorithm

Now apply "not" (~0) and get 11111111
shift right (<<) by n and get 11111000 and "not" that and get 00000111 it can be written as ~( ~ 0 << x )........(1) Okay we got our mask. 1. Now, we push the bits we want out of the number into the lowest order bits so we shift binary n by p+1-x ------(2) e.g. n >> p+1-x because so it's just a clever way to get n 1-bits in the least significant part of the number.

The "x bit" you describe has shifted the given number n right far enough so that the least significant x bits are the ones you want

take the and operation of above two you will that the number represented by that x bits or we can also return the bits if save that in to string or array

so we have to finally return ( ( n >> p+1-x ) & ~( ~ 0 << x )) so Here is Working Code for the same #include

unsigned int getbits(unsigned int x, int p, int n)
{
return (x >> (p + 1 - n)) & ~(~0 << n);
}
int main(void) {
int x = 182, p = 2, n = 5;
int z = getbits(x, p, n);
printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);
//% u for unsigned & %x for hexadecimal numbers


return 0;
}

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

Wednesday, July 13, 2011

Given two sorted arrays a[]={1,3,77,78,90} and b[]={2,5,79,81}. Merge these two arrays, no extra spaces are allowed. Output has to be a[]={1,2,3,5,77} and b[]={78,79,81,90}.

Data Structure Used: Array

Algorithm: Question is really tricky if we don't think smartly !!!! :)
use two pointer & points l to 1st & r to 2nd array
if elementb in 1st is smaller trhen 2nd arraye elemnt at index i then increment 1st pointer
else
swap element at index i in both array &b incerment 1st pointer & sort 2nd
array its not necessary only if we need sorted output in each array

Solution:

size of a=m size of b =n
a[]={1,3,77,78,90} and b[]={2,5,79,81}
l r


while(l<=m && r<=n)
{
if(b[r] {
swap(a[l],b[r]);
l++;
sort(b[]);
}
elseif(a[l] l++;



}

Time Complexity O(mlogm) sorting to 2nd array
Space Complexity O(1)

Monday, June 20, 2011

Given 3 arrays, pick 3 nos, one from each array, say a,b,c such that |a-b|+|b-c|+|c-a| is minimum

Data Structure Used: Arrays of Integer

Algorithm:
1.Sort all 3 arrays (Using Heap or Quick Sort) , take min = INFINITY
2.Take pointer to start of all the three arrays
3.compute sum = |a-b|+|b-c|+|c-a| where a,b,c are elements pointed to by d pointers
4.if sum < min then sum = min.save a,b,c too 5.increment the pointer of (min (a,b,c)) 6. if not the end of any array. repeat from step 3 Working Code:Java class QuickSort { static int min(int a, int b, int c) { int m = a; if (m > b) m = b;
if (m > c) m = c;
return m;
}


static int findMinof_abc(int a[],int m,int b[],int n,int c[],int l)
{

int min = Integer.MAX_VALUE;
int i = 0, j = 0, k = 0;

while( i < m && j < n && k < l) { n = Math.abs(a[i]- b[j]) + Math.abs(b[j] - c[k])+ Math.abs(c[k] - a[i]); min = n pivot)
j--;
if (i <= j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}

public int[] sort(int[] input)
{
quickSort(input, 0, input.length-1);
return input;
}

public static void main(String args[])
{

QuickSort mNew = new QuickSort();

int a[]={11,13,22,31};
int b[]={18,26,36};
int c[]={28,29,30,33};
mNew.sort(a);
mNew.sort(b);
mNew.sort(c);

int x=4,y=3,z=4;
System.out.println(findMinof_abc(a,x,b,y,c,z));

}


Time Complexity O(NlogN)
Space Complexity O(logN)
Run Here http://ideone.com/eCrlJ

Tuesday, June 14, 2011

WAP to Find Path of Minimum Sum in Binary Tree Efficiently

Data Structure Used:Binary Tree

Algorithm(Recursion)
For each node use two variable left & right for left & right subtree
find minimum in left & right sub tree & add root value to minimum
this algorithm requires two passes over binary tree with constant spaces.


#include
#include


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

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);
}

int minSuminBT(struct node* t, int print)
{
if(t == NULL)
return 0;

left=t->left->data;
right=t-right->data;

int lsum = minSuminBT(t->left, 0);
int rsum = minSuminBT(t->right, 0);

if(print)
printf("%d ", t->data);

int sum = t->data;

if(lsum <= rsum) sum += minSuminBT(t->left, print);
else
sum += minSuminBT(t->right, print);

return sum;

}

/* Driver program to test mirror() */
int main(void)
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(3);
root->left->right = newNode(2);
root->right->left = newNode(1);
root->right->right = newNode(2);

minSuminBT(root,1);//answer 1-2-2
getchar();
return 0;
}

Time Complexity O(N)
Space Complexity O(1)
Run Here http://ideone.com/RWbhP

Thursday, June 2, 2011

WAP Check Endianess of Machine & Converting From One Endians To Other

First of all, Do you know what Little-Endian and Big-Endian mean? Little Endian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address. That is, the little end comes first.
This Question Is Frequently Asked in Top Core Companies Interviews so you need to aware of Computer System Architecture

For example, a 4 byte, 32-bit integer
Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:

Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3
Intel processors use “Little Endian” byte order.

“Big Endian” means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.

Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0
Motorola, Solaris processors use “Big Endian” byte order.

In “Little Endian” form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision mathematic routines are easy to code. In “Big Endian” form, since the high-order byte comes first, the code can test whether the number is positive or negative by looking at the byte at offset zero. Its not required to know how long the number is, nor does the code have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.
Here is some code to determine what is the type of your machine

int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}

And here is some code to convert from one Endian to another.

int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;
byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;
return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}

Friday, May 27, 2011

WAP a function to determine the number of bits required to convert integer A to integer B.

Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2

class digit_prob
{

public static int bitSwapRequired(int a, int b)
{
int count = 0;
for (int c = a ^ b; c != 0; c = c >> 1) {
count += c & 1;
}
return count;
}

public static void main(String a[])
{
System.out.println(bitSwapRequired(10,9));

}

}


TC O(n)
Sc O(1)
Run Here https://ideone.com/VaBTS

Given integer n decide if it is possible to represent it.SPOJ Prob. 91 as a sum of two squares of integers.

In number theory, Pierre de Fermat's theorem on sums of two squares states that an odd prime p is expressible as
x^2+y^2=c
with x and y integers, if and only if

For example, the primes 5, 13, 17, 29, 37 and 41 are all congruent to 1 modulo 4, and they can be expressed as sums of two squares in the following ways:

On the other hand, the primes 3, 7, 11, 19, 23 and 31 are all congruent to 3 modulo 4, and none of them can be expressed as the sum of two squares.

More Info http://en.wikipedia.org/wiki/Fermat's_theorem_on_sums_of_two_squares


I used Above Fact to Solve the Question(to Solve SPOJ problem You have to Modify the program )

#include
#include

int isSquare(int c)
{
int a=0;int b=sqrt(c);
if(c%4==1)//remove this to solve spoj probelm
{
while(a<=sqrt(c))
{ int pows=pow(a,2)+pow(b,2);
if(a!=b && pows==c ) //a!=b means 1^1+1^1=2 not allowed
{ printf(" yes Possible \t %d %d ", a,b);
return 1;
}
else if(pows a++;
else b--;

printf( " %d %d %d \n", a,b,pows);
}

}
else
{ printf( "not Possible");
return 0;
}
return 0;
}

int main()
{
printf(" %d ", isSquare(29));
}


TC O(sqrt(n))
SC O(1)
Run Here https://ideone.com/nLGDs