Chear Seat

11
Strings  Finding an anagram[a word that is a permutation of the given word] of a word from a set of words. -- Sort given words individually and then do the matching.. you may sort these sorted words overall.  Given 2 strings of different l engths(suppose N and M). Find the maximum common substring. Complexity?  In previous problem, instead of 2 strings we are given a set of strings each with different lengths. What is the complexity?  Given a string of length N, find whether there exits an even length palindrome substring.  Find the first non-repeating character in a string:("ABCA" -> B ).  Find if a string is a substring of other in linear time......solution(KMP).  Given two strings S1 and S2, Find whether a string S3 is formed by interleaving S1 and S2.  Anagram of a string is defined as any string which is formed by jumbling the letters from that string. e.g. anagrams of ‘abc’ are ‘bac’, ‘bca’ etc. Given a dictionary of words, find all anagrams of a given query word. Once I came up with an algo, I was asked to determine and optimize the worst- case running time. Assume I can preprocess the di ctionary and that this preprocessing can take infinite time. Only algo, no coding. The second algo I came up with is to have a hashtable that maps the sorted version of a string to a set of anagrams.  Generate all strings of length ‘n’ which do not contain a given string as a substring.  String matching: Find if a string is a substring of another. Note that a mismatch of one character should be ignored. A mismatch is either an extra character (’dog’ matches ‘xxxdoogyyyy’), a missing char (’dog’ matches ‘xxxxdgyyyy’) or a different character (’dog’ matches ‘xxxdigyyyy’). Write code in a language of your choice.

Transcript of Chear Seat

Page 1: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 1/11

Strings

•  Finding an anagram[a word that is a permutation of the given word] of a word from a set of words.

-- Sort given words individually and then do the matching.. you may sort these sorted words

overall.

•  Given 2 strings of different lengths(suppose N and M). Find the maximum common substring.Complexity?

•  In previous problem, instead of 2 strings we are given a set of strings each with different lengths.

What is the complexity?

•  Given a string of length N, find whether there exits an even length palindrome substring.•  Find the first non-repeating character in a string:("ABCA" -> B ).

•  Find if a string is a substring of other in linear time......solution(KMP).

•  Given two strings S1 and S2, Find whether a string S3 is formed by interleaving S1 and S2.

•  Anagram of a string is defined as any string which is formed by jumbling the letters from that

string. e.g. anagrams of ‘abc’ are ‘bac’, ‘bca’ etc. Given a dictionary of words, find all anagrams of a

given query word. Once I came up with an algo, I was asked to determine and optimize the worst-case running time. Assume I can preprocess the dictionary and that this preprocessing can take

infinite time. Only algo, no coding.

The second algo I came up with is to have a hashtable that maps the sorted version of a string to a

set of anagrams.

•  Generate all strings of length ‘n’ which do not contain a given string as a substring.

•  String matching: Find if a string is a substring of another. Note that a mismatch of one character

should be ignored. A mismatch is either an extra character (’dog’ matches ‘xxxdoogyyyy’), a

missing char (’dog’ matches ‘xxxxdgyyyy’) or a different character (’dog’ matches ‘xxxdigyyyy’).Write code in a language of your choice.

Page 2: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 2/11

Array

•  Given a array of integers of size N and an integer k right rotate array k times. O(n) time. - Solution

in Programming Pearls

•  Given an array of size n wherein elements keep on increasing monotically upto a certain locationafter which they keep on decreasing monotically, then again keep on increasing, then decreasingagain and so on. Sort the array in place (ie. using only O(1) extra memory).

•  Given an array of size n, design an algorithm to find for each entry of the array the first number to

the right which is less than it. That is, for each entry A. This has to be done in O(n) time.

•  Given two sorted positive integer arrays A(n) and B(n), we define a set S = {(a,b) | a \in A and b\in B}. Obviously there are n2 elements in S. The value of such a pair is defined as Val(a,b) = a +b. Now we want to get the n pairs from S with largest values. The tricky part is that we need an

O(n) algorithm. --> Possible

•  Partitioning a given integer n into unique partitions of size m. like if n=10,m=4, 7111 is one such

 partition. Give all such partitions

•  You are given an array. One integer is in the array twice and others are unique. Find that no. O(n)Solution

•  Given an array t[100] which contains numbers between 1 and 99. Return the duplicated value. Tryboth O(n) and O(n^2)

•  Given 2 arrays of arbitrary sizes N and M each. Write a program for finding mutual exclusion of these two arrays.(copy the non-common elements into another array). -- Hash after finding min an

max range.. or straight O((m+n)logm) algorithm.

•  Unsorted array - Find i,j such that a[i]+a[j] is max. - O(n lgn ) algo -- better? -- find max andsecond max -- O(n).

•  Find a saddle point in matrix :A saddle point is an element of the matrix which is both the smallest element in its row and the largest element in its column. 

•  Given an array of size N and a Random no. generator function that can generate numbers in range0...N-1. You need to fill array with values between 0 and N-1(no duplicates) and there should not b

any pattern between values stored. Also there should not be any relation between value and theindex at which value is stored. Extra memory should not be used. O(n) solution.

How the program will change if the array of 2N elements has to be filled and no value should repea

more than twice.

•  An array A of size n is given.

Another array B needs to be created of size k which is defined as

B[ i ]= A[ i + 0 ] + A[i+1] +... +A[n-k+i];Constraints:1) addition of two elements A[j] and A[k] is expensive, so try to minimize the number of additions.

2) Subtract operation on A[j] and A[k] elements is not allowed.Find the time complexity to create array B and the number of additions in order of n for the creation

?

Answer:This problem seems like you create a window of size n-k and then slide it over the elements of A to

produce B.Now assuming n>>k, you will have a lot of common elements that the window will cover. For

example, if n=100 and k=10, A[10]...A[90] will be present in all elements of B.Hence, you need to sum A[k]...A[n-k] just once... and then for each element in B you will add k

more elements of to the above sum. This will reduce the add operations from k*(n-k) to (n-k) +

k*k. Now this will only be a gain if n-k>k ie. n>>k•  Given an array of N elements( consider distinct ) we have only one operation defined ie reverse(i,j)

which reverses all the elements at positions at i and j. so using the array given and the operationwe have to generate all the n! permutations and there is a constraint that only one reverse

operation is to be used between 2 permutations

•  Arrays of integers, a(i,j) with the following property. For all pairs of distinct rows i1,i2 and distinct

columns j1,j2 the diagonal sum a(i1,j1)+a(i2,j2) and the anti-diagonal sum a(i1,j2)+a(i2,j1) areunequal. We are interested in finding such arrays with the entries chosen from as narrow a range o

integers as possible. For example the following is an example of such a 3x3 array with entries

chosen from {0,1}0 0 1

0 1 0

1 0 0

Page 3: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 3/11

Find a 5x5 array with this property with entries chosen from {0,1,2}. If this is too easy try to find a

7x7 array with entries from {0,1,2,3,4}, a 11x11 array with entries from {0,1,...,6,7} and a 13x13arrays with entries from {0,1,...,7,8}. This will probably require computer assistance.

•  Given 2 sorted arrays, compute the combined median in O(lg n) time.

•  Given sorted array and an integer C, find 2 elements a[i] and a[j] such that their difference is C --

O(m)

•  WAP : Given a 2d array. Print the sequence you get if you unroll it from top-left elementanticlockwise.

•  Given a sorted array which is rotated left by some amount, find its smallest element in log n time.

e.g. 6 9 10 15 1 3 5 (Sorted array is rotated left by 3 numbers) Search an element in such an array

Page 4: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 4/11

Linked List

•  Cycle in linked list - two problems - (i) detect cycle (ii) Detect the intersection point and

mathematical proof. -- Standard Answer

•  Given a linked list of integers, delete all occurrences of the elements which are repeated. O(n)solution. One approach: Hash table implementation. -- sort and remove -> O(nlgn) wihtout extraspace

•  you are given 2 linked lists - A and B. write a function which gives you the intersection of A & B, A-

and B-A. try to reuse the nodes.

•  Merge two linked lists, one which is sorted in ascending order and one which is sorted in descendingorder.

•  Switch pairs of nodes in a linked list.

Page 5: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 5/11

Stack & Queues

•  Implement insert and delete operations of queue using stacks.

•  Program to reverse a stack “in place” using recursion ? You can only use the following ADT function

on Stack: IsEmpty IsFull Push Pop Top

Page 6: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 6/11

Tree

•  Merge two BSTs

•  A binary search tree is given and a pointer to a node X is given. Find the immediate successor of 

X.num, i.e. the inorder successor.

•  Given a n-tree whose definition is as - the tree has total n nodes and any node can have any

number of children. Give an array representation, to represent the tree. so that the tree can beeasily constructed from the array. The order of child in reconstruction is not important. i.e. following

trees are same. Then from the array find the height of the tree. -- If stored as heap, it will require2^(h-1) sized array and height computation is log size of array to base n. And ...

•  Given a pointer to a node in a binary tree, write a func to return its successor in inorder traversal.

•  A strict k-ary tree is a tree where each node has either 0 or k children. Assume there is no info in

the nodes; we’re interested only in the tree structure. A DFS search (think preorder traversal) of 

such a tree generates a string where each node is represented by the letter ‘l’ for a leaf and ‘p’ otherwise. For instance, for k=3, “plpllll” represents the following tree:

•  p

|

--+--

| | |

l p l

|

--+--

| | |

l l l

•  In a binary tree, you can think of nodes as balls or weights and the edges as strings. Then the tree

is a structure suspended from the root. You want to suspend it from a particular leaf. If that nodewere made the root, how does the structure of the tree change? (Some parent-child relationshipsget inverted.) First describe the logic and then write code to implement this.

Page 7: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 7/11

Graphs

•  find number of cycles in a directed graph. Complexity? -- O(n^3) Algo with recursion. For each nod

calculate the no of cycles it is part of. Then remove this node from graph and do it for other nodes

as well.

•  Given a graph of nodes of the type struct node { int ID; struct node ** refList; int size; }; Detect athe cycles in it. output should of the following form: Cycle detected : In reference from node 2 to 7 

Cycle detected : In reference from node 5 to 7 -- Recursive, backtracking solution with removing

each node once all the cycles starting-terminating at that node are detected. -- O(n^3) Solution.

•  Given a weighted directed graph G={V,E}. The goal is to obtain its spanning forest with maximumsum of weights of edges. The direction of each edge is from root to leave. Is this problem NP-Hard?

•  Find longest cycle in a graph? Is it NP-Complete? 

•  Given a connected graph G, prove that there are always 2 nodes with same degree. -- Proof by 

contradiction and pigeon hole principle. 

•  Given a DAG , how will you find number of paths from a node u to node v. Ans...(Start from allnodes from where there is a direct edge to v, update their couts. Then follow a procedure similar to

topological sort in reverse direction until node u is labelled)

Page 8: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 8/11

Others

•  In a document, find the 10 elements with max frequency in a given document -- Top K Methods

•  Given four points write a program for finding whether the points form a square or not. -- Angles,

Sides, diagonal three aspects of looking at it.

•  What is the most efficient way to compute the intersecting area of 2 rectangles? -- Sides parallel toaxes : Assumed

•  Given N sets of integers (Assume suitable representation), Device an algorithm to print the cross

product of N sets, N known atruntime . complexity? Assuming m to be the size of each set. And

assuming that all the m elements are present. We will generate bit pattern for base m system anddepeding on each bit, select the values from sets. If this assumption is unreasonable, then arecursive algorithm to do this has to be devised. This will be similar to compute determinant of N x

N matrix.

•  Implement a data structure for dictionary. So that the function which returns all the words ending

with a given string can be implemented efficiently.

•  Generate First n primes -- Find all primes between 1 and n.

•  You have given n boxes with hight, width and depth. But box can be rotated in any direction so the

any dimension can be height or width or depth. Find the maximum number of boxes that can bewrapped inside each others.

struct box{ int d1,d2,d3;}

•  There are n red and n blue balls. Each ball is given a unique number between 1-n. So that number

and color is unique combination. And i’th red balls index in the array is always less than

corresponding i’th blue ball. struct ball {int num, char *color;};

The distance between i’th blue ball and i’th red ball is called some xyz distance. Calculate sum of allthese distances for the array.for eg. r1 r3 b1 r2 b3 b2

Hence sum of those distances is : 2 + 3 + 2 = 7

•  Random # array of size n with no repeatation has to generated. Give a unbiased strategy.

•  Given a circular road and a set of petrol pumps located at distances d1 d2 ... dn away from eachother and supplying p1 p2 p3 ... pn amounts of fuel. Given that your vehicle has a mileage of 1km/

Determine the feasibility of going around the path starting with zero fuel. Find a point from whichyou can start and complete the cycle given that you have zero initial fuel.

•  You are given a string CAT and a dictionary. You can substitute one character in the string at a time

to get another string. This string should be a part of the dictionary. Using such steps, start from thesource string and reach the destination string(DOG) in minimum number of steps. What is the bestway of storing the dictionary? Write the code for the same.

•  Given a repository of 10 billion pages and each page has an average of 10 links, how will find its

neighbors and neighbors of neighbors?

•  Given a 2D space. There are some rectangles in this space with their sides aligned in the x and ydirections. These rectangles are like obstructions. Now find a path from a point s to a point t in thisspace. Find the shortest path

•  How to check if your system is Little Endian or big endian?

•  Given an integer, find all compositions of the numbers considering order important.Composition of 5: 1+1+...+1, 1+1+1+2, 2+1+1+1 Modify it to ‘Dont consider order important 1+1+2 is same as

1+2+1.

•  Given a matrix of zeros and ones, find the largest submatrix consisting only of ones. Then

determine the running time and bring it down. Just algo, no coding.•  Given a sequence of numbers, find the biggest increasing subsequence (not necessarily contigous).

Do asymptotic analysis and improve the algo. Just algo, no coding.

•  Google is looking at phone interfaces, where you type a word by entering some numbers on thekeypad. Given a number and a dictionary of words, generate a list of matches. First describe the

idea and then code it. Then determine the running time and improve it. Now assume you’re allowed

to preprocess the dict and you have infinite time for that. Reduce the lookup time. The interviewersaid he’d be “very happy if I can code it”. Determine the time-space tradeoff – how much morespace do you use? what’s the improvement in the running time?

Answer: Write a function that takes a string of digits that have been assigned letters and a stringof digits that haven’t; take the first digit from the second string, assign a character to it, and

recurse. Stop recursion when the first argument is not in the dict.

Page 9: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 9/11

Second algo: build a lookup table that maps a number to a set of strings.

•  Find Lucky Number: From the sequence: 1 2 3 4 5 6 7 8 9 ...

If you remove every second element you will get 1 3 5 7 9 11 13 ...

Then from this sequence if you remove every third element you will get 1 3 7 9 13

...

The process continues...

The number is considered to be lucky if the number stays in the sequence

indefinitely.Write a function with signature: bool isLucky(int n) which returns true or false

whether the number is lucky or not.

•  Algorithm: Explain algorithm to shuffle cards

Page 10: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 10/11

Puzzles

•  For numbers between 1 and 100, how many numbers have odd numbers of factors. Note that

factors covers all prime and composite factors and including the number itself and 1. -- The answer

will be perfect squares.

•  You are facing a wall that stretches infinitely in both directions. There is a door in the wall, but youknow neither how far away nor in which direction. You can see the door only when you are right

next to it. Design an algorithm that enables you to reach the door by walking at most O(n) steps

where n is the (unknown to you) number of steps between your initial position and the door

•  There is a camel and a person with 3000 bananas, He needs to take the bananas to a market1000km away. The constraints are for every 1km the camel eats 1 banana or else doesnt move. Ata time, it can carry max of 1000 bananas only. How many bananas can he take to other end.

•  You are given a number. It has some number of ones in its binary form. Get the next higher numbewhich has the same number of ones in its binary form.

•  A king has n bottles of wine of which one is poisoned. He intends to find out by having a bunch of 

prisoners taste wine from different bottles – even a little poisoned wine will kill. There will be onlyone tasting session – you can’t say, “feed wine from bottle x to prisoner y and if he doesn’t die,

do...” What are the least number of prisoners required, and who samples wine from which bottle?

•  A biased coin has a probabilty of heads 2/3. How do make a fair toss using such a coin.

Page 11: Chear Seat

8/8/2019 Chear Seat

http://slidepdf.com/reader/full/chear-seat 11/11

Programming

•  Write a program to print all subsets of a given set.

•  Linklist reversal.

•  String reversal (UTL 8)

•  Permutaion of n numbers (distinct and non distinct)

•  Write a program for atoi and itoa.

•