Addition of 2 big numbers (represented by 2 int arrays, assuming each integer can only be 0-9)
========
find the median of million rows in each of the 1000 servers.
==============
What was the most challenging aspect of your previous job?
==============
Write a class that iterates through a list of lists with methods next and hasNext. Next returns the next item in the list, and hasNext returns True or False depending on whether or not we are at the end of the list.
Example:
i = Iterator([[1, 2], [3, 4]])
i.next() returns 1
i.next() returns 2
i.hasNext() returns True
i.next() returns 3
i.next() returns 4
i.hasNext returns False
=================
Given an unlimited stream of input, output the median value at any moment.
============
What was the most challenging issue/bug you came across and how did you resolve it?
==============
Millions of cache entries, each with a unique key, stored in several servers. how to sort all entries whose key falls within a specified range using Map Reduce? What if one server has a very small range of keys (say 1 to 100) and another server has a very large range of keys (say 100 to 1000000)? Sorry I don't remember the answer.
=================
BST running time (creation/updating/traversal)
=====================
Given a string and a list of character mappings of the form (a=>j,k), (d=>r), (t=>r,q,e,y), print out all the possible variants by applying the mapping to the original string.
example:
string="foo", mappings = "o=>1,2", "k=>d,l,w"
output:
foo
fo1
fo2
f1o
f11
f12
f2o
f21
f22
===============
Describe a current project. What was challenging about it? What did you learn from it?
==================
A quad tree is used to represent a black/white image. If you are provided with two such image representations, write a function to create a third tree that represents the merged image. (Black overrides white, mixed; mixed overrides white)
=====================
Implement a random number generator such that the random number generated is always in a particular range. Perform through time complexity analysis of it. How would you improve the solution.
=======================
If a person dials a sequence of numbers on the telephone, what possible words/strings can be formed from the letters associated with those numbers?
=====================
Please tell us about the most satisfying project you worked on in the last year?
=================
Please tell us about a personal challenge you had with someone who managed you?
======================
Find a repeated number in a list of numbers
Naive way: brute force O(n^2) time
Batter way: punch it into a hashtable/hashmap/dictionary, O(n) time
====================
How do you check if a URL is bad really fast in Google server. The point is for the user not to notice the lag in the checking
Use Bloom Filter algorithm. I don't really know how to do this
i don't think a bloom filter works here.. it works as an approximate cache, but when you're talking about arbitrary URLs, you'll end up missing the cache on a huge % of time... hence not valuable
================================
I was asked to determine whether two nodes were connected in a graph.
use union-find data structure (also called disjoint sets)
=================================
design a structure have these two functions: insert, getMedian, discuss the time complexity
use a self balancing binary search tree (BST) that has the same size (or off by one) left and right subtrees from the root
getMedian: O(1)
since the tree is balanced the median will always be the root node
insert: O(logN)
BST gives us logN insertion, balancing the tree is O(logN) as well and works in the following way: (this is only the most difficult case) if upon insertion the left subtree has two more nodes then the right subtree we need to rebalance the BST, that is take the largest value on the left subtree (rightmost node) and make that the new root, that works fine as this value is greater than everything on the left subtree and less than everything on the right subtree, then take the old root value and insert it in the right subtree, then the tree is balanced again and the median value is the root, ta-da! :)
I am not sure that the median is in root. You can draw a tree that is balanced ( the depth of the left child - the depth of the right child <= 1). Then it is very hard to see which is the element.
You can solve this problem by using 2 heaps:
- one max-heap for the 1/2 lowest elements;
- one min-heap for the 1/2 highest elements;
On insertion, you can insert in heap and balance the heap (if the difference of the sizes is greater than 1, then remove the maximum (minimum) from one and insert to another). This is done in O(log n).
When you get the median if the sizes of these 2 heaps are the same, then take the average of the max (min) heaps, otherwise, return the element from top of the heap with the highest number of elements.
===========================
Try to figure out the top unique search queries from a database with 100 billion entries
Use a hash table then sort the counting results
Not sure if this is a trick question.
Are you trying to find the most queried search term? If so, then how is it "unique"?
Assuming it's not unique, this is a typical application of the map/reduce paradigm. Assign each query a value of 1 (map) and then count the number of occurrences (reduce). Google sort of popularized the shift towards map/reduce anyway.
==================
Sample uniformly on a circle centered at zero with radius 1.
randomly generate an integer X.
we know that cos(X)^2 + sin(X)^2 = 1, so just use xx = cos(X) and yy = sin(X)
I think that was the whole point of the question (and I don't like it very much)
=======================
Write code to check whether every element of an array has been visited (you are given a starting position and each position stores a pointer to a subsequent position)
================
You have a genealogy: 1) Describe a data structure to represent it. 2) Given any two people within the genealogy, describe an algorithm to determine if they share a common ancestor. You just need to return true/false, not all ancestors.
1) Each person is represented by an object, with two pointers: "mom" and "dad" that point to their respective parent.
2) Choose one of the two people arbitrarily. Perform depth-first traversal and create a set of ancestors reachable from that person. Perform depth-first traversal on the 2nd person and for each node visited check if they are in the set; if yes, return true. Use a hash-set for best performance.
If you've optimizing for worst case, hash set is O(n) for search. You'd do better in worst case with a sorted structure. You'd do even better if you store a "visited" flag at each node. Alternately you can number each node and keep an array of visited flags.
since depth first seach might find a longer link through dad before checking mom, you're better off with breadth first search. Anything reachable in one hop would be seen before anything reachable at best in 2 hops
Yes. Good points. The second traversal should be breadth first. The first traversal it doesn't matter, as you need to visit all ancestors anyways.
The use of a visited flag is a good optimization. Based upon the way the question was worded, it wasn't clear if you could design the data structure to optimize the algorithm or not.
=====================
Print mth to last elements of the linkedlist
=============================
Create a binary tree based on a sorted array
If you already have a sorted array, then you could say that it is already a minimum heap and that is a binary tree.
Use binary search to construct a balanced tree
===================================
assume you are writing number in ascending order to an array of constant size. once you reach the end of the array, you start writing from the beginning, thus writing over the oldest entries. write an algorithm for finding a specific number in this array.
Start with begining of array.
If n 0:
print k
x,y,ptr1,ptr2 = v(x,y,ptr1,ptr2)
break
Well, we can make several observation:
* a number multiplied by 8 (2^3) is always larger than that multiplied by 5.
* if we seed the list with 2 consecutive multiple of 2 (e.g. 2 and 4), we do not need to multiply the number by 2 (2*2 = 4 is already in the list) and only need to multiply by 4 (see that 2*4 = 8, then 4*2 = 8, oops already in the list)
* if we have a number that is divisible by 5, we simply need to multiply it by 5 since the results of multiplying the number by 2 or 4 would have been generated previously (we note that 5n * 4 is equivalent to 4n * 5, obviously 4n < 5n; similar argument for multiplication by 2).
Hence, here is a very simple algorithms to generate the first n numbers in the sequence:
1. we start with a seed of [1, 2]
2. we iterate through the list until length of list = n, for each number k we see,
(a) if k is divisible by 5, append to the list 5k, otherwise
(b) append 4k and 5k
def createPowerList(n):
lst = [1, 2];
i = 0
while len(lst) < n:
currentValue = lst[i]
if currentValue % 5 == 0:
lst.append(currentValue * 5)
else:
lst.append(currentValue * 4)
lst.append(currentValue * 5)
i = i + 1
return lst
Forget that. It makes a small mistake. Instead this simpler version would work much better. :)
def createPowerList2(n):
lst = [1]
power_of_2 = 2
multiply_by_5 = 0
while len(lst) < n:
if power_of_2 < (lst[multiply_by_5] * 5):
lst.append(power_of_2)
power_of_2 *= 2
else:
lst.append(lst[multiply_by_5] * 5)
multiply_by_5 += 1
return lst
============================
Find the longest word in a dictionary, such that the word can be built one character at a time, and all substrings are words in the dictionary. A new character can be added anywhere.
=============================
Deep search binary tree, what is the worst case memory requirement using Queue.
===========================
Given a large web query log file, how to find the most frequent K queries
============================
Easier questions 1) Two variations of a program exist, A and B. When run on machine 1, A runs twice as fast as B. When run on machine 2, A runs 10x as fast as B. How would you investigate this? -same datasets -same versions of OS and libraries -same hardware 2) Had to code a method that calculated the factorial, first simply, then a second one recursively.
One reason is The process has some random function, and it affects the speed.
Perhaps second machine had more memory, so no swapping was necessary. Perhaps it had more CPUs, and one program was able to take care of that (using multi-threading) but the other one could not. Perhaps second machine had SSE instructions, and the programs running were doing something like decoding movies, perhaps the second machine had a more powerful GPU and one program could take advantage of that.
Answer 1: Processor cache was smaller on slower machine
=========================================
trickier question, code a method given the following method signature that will print out any numbers that intersect both arrays of numbers //Example arrays // 4, 18, 25, 40, 411 // 20, 25, 40, 320, 1009, 1100 void intersect(int[] arr1, int len1, int[] arr2, int len2) {
void intersect(int[] arr1, int len1, int[] arr2, int len2) {
int startIndex = 0;
//have an outer loop of one of the arrays
for( int i = 0; i < len1; i ++){
//have an inner loop of the other array
for( int j = startIndex; j < len2; j++){
if(array1[i] == array2[j]){
System.out.println(array1[i] + "\t");
startIndex = j + 1;
break;
}
else if(array1[i] < array2[j]){
//skip because less than the number in the second array
break;
}
else{
startIndex = j++;
}
}
}
}
}}}
Even if they're not sorted, the first commenter's answer is suboptimal. Assume array sizes are n and m with n > m. Then sorting both arrays is O(n log n). Once sorted, you just need to make one pass over each array --- O(n + m) --- to find common elements. Just have two pointers at the head of each list, and use these to move in sorted order through the union of lists. Whenever both pointers point to the same value, you have an intersection.
If you want a very simple answer, use hashtable to store the contents of the first list (O(n)). Then, for each member of the second list, check whether the value is in the hashtable (each check is O(1)). We have O(n + m) algorithm that is extremely simple to code.
if sorted then you can avoid the nsquare with binary search
============================================
Give 2 coding solutions on returning an array by removing duplicates. One solution with O(n^2) and the other Linear.
Create a new array. Run through the original array, on each element insert to new array in sorted order. O(n^2)
hash select is O(n). What if the hash function is "return 0"? it degenerates into a linked list.
Not sure how you can do this in O(n). If the values are integers of a set size, you can use a lookup table or sort in O(size*n) . Otherwise sort O(nlogn)
You can use a hash. Either assume that you have a good hash function or write one (I doubt the interviewer would ask you to do a very complex hashing, but he'd appreciate you telling him about the assumption you made).
Instead of the solution by venk T, I'd suggest another easier one. For every values you have, push it to the hashtable, usually a standard hashtable will return true or false depending on whether the value is already in the hashtable. If the value is not already in hashtable, output it in your answer, otherwise don't output. This will cut the last step of getting all the values off the hashtable.
======================================
Describe the implementation (along with data structures) involved in making a program that: 1. inserts a number 2. returns the median of all unique numbers
=====================================
a very long single linked list, how to find the n-th entry from the end.
this is a frequently asked question. The answer is to use two pointers to maintain the locations, but i didn't realize why this is better than another method:
Scan the whole list once and calculate the length, N. Then move a pointer from the head by N-n steps.
Answer is the IO efficiency. If n is small, an n-entry list can be saved in cache and in the first method, the 2nd pointer can directly read cache.
set two pointers first and second
1. second pointer step forward for n step, first point stay at the head of the list
2. first and second pointer step forward at the same time until second point hit tail
3. first point is your answer
Interview Candidate is right.. it's the same thing.
in the 2-pointer method, you are basically iterating over the entire list with that 2nd pointer, and the 1st pointer is iterating N-n times.
====================================
Difference between function overloading and overriding.
explained one uses polymorphism and other inheritence.He said right thats what he wanted to know.
=============================
how would you find maximum element in an array of numbers.
2 loops and comparing each element with all other as its not sorted array.
Honestly, something like this is probably the best (assuming an unsorted array):
int getBest(int[] nums){
int max;
for(int i = 0; i < nums.length; i++){
if(i == 0){
max = nums[0]; // ensures it's always initialized
}
int curr = nums[i];
if(curr > max)
max = curr;
}
return max;
}
You have to look at every element once, because if you skip an element you can't be sure it isn't the biggest. The lowest bound we can do is O(n). However, two loops makes this an O(n^2) problem, doing much more work without helping us solve the problem.
sort the list. quicksort gives average of O(nlogn) complexity.
return the last element in the list O(1) complexity.
===============================
How would you find maximum element in a list of items whcih implements comparator.
Unless we want to know something else, this is the same as the array question. Iterate through the list, keeping track of a "max" item, and compare each element to the max so far. The comparator is a red herring, probably meant to get you to think about sorting.
Sorting before we search is not the answer here. For a comparison based sort, the best you can do is O(n log n), which isn't as good as linear search over the unsorted array. Sorting wins if we need to make arbitrary queries after the first.
I guess then that there is no one, correct answer, since we are defining the question. I'd define the "best" element as the element which was scored as "better" than the most others, and compare each element with each other one. For that, the best you can do is O(n^2). You could, though, redefine this - for instance, the "best" element is the element which beat the most other elements that it lost to. It's a more vague problem than originally described.
I think the analogy I'd use would be sports teams over the course of a regular season, where team A might beat every other team except team B, who beats team A but loses several other games. I would definitely ask what the heck this guy was talking about, though - because using words like "maximum", "best" and "comparison" definitely imply some sort of logical ranking.
=============================
Base class has one method takes argument as Object and inherited class overrides it to pass String as parameter.If called with argument of Object whcih method will be called
functions calls go from instance class first and then if no match found then towards base class based on arguments ...so anwer is base class method will be called becuase base class only has method matching argument of Object.
He was happy.
===========================
Give us an example where you solved and handled some complex issue in current project
I explained one scenerio for a design change.I felt he was looking for something else but based on my current job thats what i do.
====================
Find if there are two members of an array that sum to 10 (10 and 0 count, but 10 alone does not).
My first guess is something like the following, where 10 would be passed as the sum parameter:
int[] findSum(int[] nums, int sum){
int[] pair = null;
for(int i = 0; i < nums.length; i++){
int a = nums[i];
int target = sum - a;
for(int j = 0; j < nums.length; j++){
if(nums[ j ] == target){
pair = new int[2];
pair[0] = a;
pair[1] = target;
return pair;
}
}
}
return pair; // returns null if no suitable pair found
}
}
I would use a hash to count how often the numbers between 0 and sum/10 show up. then go through the has to see if we have two that match. it is O(n^2) also, and doesn't work if sum is large.
int[] findSum(int[] nums, int sum) {
int[] hash = new int[sum+1];
//count how many numbers
for (int i=0; i 0) && (hash[sum-i]>0)) {
return new int[] {i, sum-i};
}
}
return null;
}}
Basically sort the elements in n log n . Then for every element k search for (Sum - k) in the array using a binary search. Hence total complexity is n log n.
You can use a hashmap from value to # of occurrences of the number in the hashmap. Enter all numbers to a the hashmap (O(n)), go through the array and calculate 10 - n for each member and determine whether that number has occurrences > 0 in the hashmap. If so, you have a match, don't forget to decrease the occurrence by 1 (O(n)). Total O(n).
Note that if duplicate is allowed (such that 5+5=10 is possible), you may need to check whether n = Sum - n, if so you must make sure the # of occurrences is > 1 and then reduce the occurrences by 2 instead.
================================
What cool things did you do in your previous job. Basically the interviewer wants to know if there can be a good fit between me and the team.
================================
You're given a binary tree and pointers to two nodes in the tree. Describe the fastest algorithm you can come up with to determine the closest common ancestor.
This one is covered a lot on the web and in technical books, but every one I've seen assumes it's a binary search tree. Here he didn't want me to assume it was a binary search tree.
I think I would go with a modified dfs which terminates early. I would need a global variable to indicate the closest ancestor;
//return 0 - none found, 1 - a found, 2 - b found, 3 - both found
public int modifiedDFS(Node node, Node a, Node b, int ) {
int res=0;
if (node) {
if ((node.left == a) || (node.right == a)) {
res += 1;
}
if ((node.left == b) || (node.right == b)) {
res += 2;
}
if (res == 3) {
lowest = node;
} else {
int l = modifiedDFS(node.right, a, b);
int r = modifiedDFS(node.left, a, b);
if ((l==3) || (r==3)) {
//lower node is the one
res = 3;
} else {
if ((3 == (l+r)) ||
(3 == (l+res)) ||
(3 == (r+res)) {
//i am the lowest
lowest = node;
res = 3;
} else {
if ((l==1)||(r==1))
res = 1;
if ((2==l)||(2==r))
res = 2;
}
}
}
}
return res;
}
)}}}}
That may or may not work (I didn't trace through the code), but there's a much simpler and faster way to do it. Worst-case running time is O(lg n). With yours, worst-case running time is O(n).
Remember: you're given a pointer to the nodes in question. To traverse from a leaf node to the root is worst-case O(lg n) operations. Think of something you could do to take advantage of that.
If there is parent pointer, the answer is straightforward. The simplest of which is just to traverse up from 1 node and record all the nodes, then traverse up from the other node and find the first node that match the recorded nodes. This is O(lg n) in a balanced tree, O(n) in worst-case.
If there is no parent pointer, I'd use tree traversal (pre-, in-, or post- doesn't matter much). The closest common ancestor would be the only node that find one node on its left children (or itself) and the other node on its right children (or itself). This is O(n).
=============================
You're writing an application that receives a stream of individual items of data. The stream may be very long or very short, but you have no way of knowing how long it is (i.e. there's no trick to figuring out the size of the stream of data). How would you go about choosing m items such that any subset of m items was equally likely? (Not an even distribution of values, but just that any m items are equally likely to be chosen). So for example, m=1000, and the number of items in the stream, n, may be 1000, or 10000, or 100000000, or much much larger; there is no way to know how many.
The algorithm is rather straightforward:
1. Pick the first m members in the stream (if there is less than m, just return the entire list).
2. For each of the subsequent member of the list, pick the member with m/n probability, where m is the number of elements already seen. If the member is picked, replace 1 member at random from the already selected m members with the new member.
We can prove that this is random via induction. If there is m members (or less), each member has probability 1, which satisfy the requirement that probability is m/N. For the induction step, we assume that for the first k-1 members, we pick them with probability m/k-1, so in step k, we have 2 cases to consider:
(a) the k-th member has m/k probability of being picked, so the induction step holds for k-th member.
(b) for all the previous member, the probability of being picked is now P(k-th member not picked)*P(original) + P(k-th member picked)*P(original)*P(member is not dropped) = (k-m)/k * m/(k-1) + m/k * m/(k-1) * (m-1)/m = m/(k-1) * [(k-m)/k + (m-1)/k] = m/k, which is the required probability.
One idea is for each member, we run random to get a number associate with it. We also keep the minimum m members at any time. For worst case, the algorithm take O(n*log(m)) runtime. But considering the kept m members has very small numbers associated with them after a long run. So the random generated for subsequent members has large probability to be larger, so the comparison can be very quickly.
=================================
Given a stream of integers of unknown (possibly large) length, how would you pick one at random? Now prove its random.
Question was not worded very well, however we eventually reached mutual understanding.
Answer: Store one integer at most. For each pop, decide whether or not to store it in the one slot with probability 1/N (N is current count of integers encountered).
proof is easy:
probability of an object appearing (being chosen) to be in some previous slot K starts with 1/K as per the algorithm. To "survive" to the Nth slot, the probability is
(let M be distance of K to N: M = N - K or N = K + M)
1/K * K/(K+1) * (K+1)/(K+2) * ... * (K+M-1)/(K+M) , the last denominator simplifies to N
All the numerators and denominators cancel except 1/N.
You can prove by induction, probably simpler. If the list only contains 1 member, probability is 1/1 = 1, which is correct. For the induction step, consider what happen when k-th member is encountered:
case(a): for the k-th member, probability of being picked is 1/k, which is what we want.
case(b): for each of the previous (k-1) members, probability of being picked become P(k-th not picked) * P(original, i.e. 1/(k-1)) = (k-1)/k * 1/(k-1) = 1/k, which is what we want.
[]
It is more fun if we were to picked m members at random, then the prove becomes less trivial (though almost equally as straightforward).
======================
Define binary search tree. Develop a procedure to verify a binary search tree.
@Bala
Recursively:
Check node.left < node.value and node.right > node.value. Also, that all subvalues of node.left < node.value and that the values of the subtree of node.right > node.value. Make sure you do checking for edge cases (ie. leaf nodes, etc).
recursive solution is a good option i guess.. its definitely easy to code. However i think we can have it done more efficiently if we just perform a BFS on the given tree. and every time just check tht the left child is smaller and right chiled is greater than or equal to the current node. If we successfully search the entire tree then it is a proper BST otherwise its not.
public static boolean checkTree(BSTNode node, Integer leftLimit, Integer rightLimit)
{
if(node == null)
return true;
if(leftLimit != null && leftLimit > node.info)
{
return false;
}
if(rightLimit != null && rightLimit < node.info)
{
return false;
}
return checkTree(node.left,leftLimit,node.info) && checkTree(node.right,node.info,rightLimit);
}
==================================
Write a function to find intersection of 2 sorted arrays.
void intersection(int* arr1, int* arr2, int len1, int len2, int** res, int& len)
{
*res = NULL;
int i1 = 0;
int i2 = 0;
len = 0;
while(1)
{
if(arr1[i1] < arr2[i2])
{
while((arr1[i1] < arr2[i2]) && (i1 < len1)) i1++;
if(i1 == len1) return;
}
if(arr1[i1] == arr2[i2]) break;
if((arr1[i1] > arr2[i2]) && (i2 < len2))
{
while(arr2[i2] < arr1[i1]) i2++;
if(i2 == len2) return;
}
if(arr1[i1] == arr2[i2]) break;
}
// i1, i2 - pos for arr1, arr2 where (arr1[i1] == arr2[i2])
int i3, i4;
i3 = i1;
i4 = i2;
while((arr1[i3] == arr2[i4]) && (i3 < len1) && (i4 < len2))
{
i3++; i4++;
len++;
}
if(len > 0)
{
*res = new int[len];
for(int i=0; (i < len) && (i1+i < len1); i++)
(*res)[i] = arr1[i1+i];
}
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
void intersection(int *a, int la, int *b, int lb, int **res, int *lres) {
int min_n = la < lb ? la:lb;
(*res) = new int[ min_n ];
int ca = 0;
int cb = 0;
*lres = 0;
while (ca < la && cb < lb) {
while (a[ca] < b[cb] && ca < la)
ca++;
if (a[ca] == b[cb]) {
(*res)[*lres] = a[ca];
(*lres)++;
}
cb++;
}
}}
ublic static void main(String[] args) {
// TODO Auto-generated method stub
int [] A = {1,2,3,4};
int [] B = {4,5};
System.out.println(checkIntersection(A,B));
}
private static String checkIntersection(int[] A, int[] B) {
// TODO Auto-generated method stub
int curA =0, curB=0; // indices for A and B
String result = "No intersection";
while(curA < A.length && curB < B.length && result.compareTo("No intersection") == 0)
{
if(A[curA] < B[curB]){
curA++;
}
else if(A[curA] > B[curB]){
curB++;
}
else{
result = String.valueOf(A[curA]);
}
}
return result;
}
=============================================
Find the lowest common ancestor for BST
One solution is traversing the BST from top to bottom and for every node, you check its children. Then you recursively go down the chain until you reach the leaf.
In BST you use the ordering property of BST:
http://rmandvikar.blogspot.com/2008/08/lowest-common-ancestor-lca-in-binary.html
The lowest common ancestor will be between the two values, so perform a dfs until you reach a node that is between the two values.
We note that the lowest common ancestor must have a value between the 2 values you are given. Any other ancestors higher than that will have a number that is either greater or smaller than _both_ values. Hence the problem is simplified a lot. We can now simply traverse from the root, as if we are searching for the smallest of the 2 numbers. For each traversal, check whether the number is between the 2 values. If it is, return that node.
===========================================
What is the relationship between equals(Object o) and hashCode() in Java? How would you implement each method?
A class which overrides one must override the other such that objects which .equals() each other generate identical hash codes.
Typically, what this would mean for implementation is that every field or attribute (including type depending on the constraints - maybe you want two objects of a given parent type to be equal to each other, so you check the parent type instead of the exact type) which is compared in the .equals() method must be used as input in the hashCode() algorithm. Something which doesn't affect object equality should never be hashed.
You need to be very careful to preserve transitivity if you allow a subclass to be equal to a super class. The super class needs to be designed for this and you have to rely on all other subclasses also being implemented correctly
==============================================
What is your favorite data structure? What opertions does it have? [Then some detailed questions about the algorithms based on this data structure]
I will go for hash and heap.
============================
Design and describe a system/application that will most efficiently produce a report of the top 1 million Google search requests. You are given: You are given 12 servers to work with. They are all dual-processor machines with 4Gb of RAM, 4x400GB hard drives and networked together.(Basically, nothing more than high-end PC's) The log data has already been cleaned for you. It consists of 100 Billion log lines, broken down into 12 320 GB files of 40-byte search terms per line. You can use only custom written applications or available free open-source software.
This is a great question. I would probably use some sort of map-reduce algorithm. Divide the job up between all of the servers (2 jobs per server, since they're dual-core machines), and calculate how large each job can be from the size of the dataset, and the memory size of each server.
Have each server count the occurences of each search request, then send up the counts. Map-reduce will take care of the rest.
Map reduce is the solution. But one should try to have tree structure(bottom up) of map tasks, so that you can filter out at every step.
There are 12 machines, and 12 files of 320 GB each. Presumably there is one file on each machine.
Since hard-drives are slow, loading a chunk of data should take much more time than processing it. So let's do lots of processing.
On each machine:
1. Load a big chunk of 40-byte entries at a time, say 0.5GB each. Compress each entry, say by using in-memory zip.
2. Put the entries in the chunk in buckets, using a hash function whose range is a big number multiple of 12 (say 3 times a power of 2). The reason for this comes later. Use exactly the same hash function on all machines at all times.
3. Once that chunk is processed, append it to 12 files on disk, by taking the hash function value mod 12.
4. At the end we have 12 files on each machine, each having a (compressed) 40-byte query and its frequency. The same query-frequency pair can show up multiple times in each file, since we append to each file multiple times.
5. Each of those files is at most 3GB (assuming that our hash function has good randomness) and each file could be much less due to compression.
6. Process each file again to combine any repetitions.
7. Now, from each machine, send first file to first machine (by compressing it perhaps), send second file to second machine, etc. The beauty here is that due to the same hashing employed at all times a query will hash to exactly one of the 12 files, the same file on each machine.
8. So, after each machine gets 12 files each, all it needs to do is combine them once again. We will find the frequency of each query.
9. The last step is to output the one million most frequent queries. I did not think of this yet, but will require some more communication among the machines.
=========================================
How would you find the most searched for phrase in Google, assuming that you could use 10000 computer in parallel?
Distribute phrases randomly to each of the 10000 computers, sort list of phrases on each computer, find the phrase that came up the most number of times on each computer. Then compare the top searches across the computers.
If you have 10000 computers, then the data for each map job will become N/10000 and emit only the top element. In the reduce step, you will sort 10000 and emit the top frequency word.
===============================================
How do you delete a given node from a single linked list?
template
class LList
{
public:
T val;
LList* next;
public:
static void Delete(LList** head, T& node)
{
if(NULL == (*head))
return;
LList* next;
// the case when the element to delete is a head of the list
if((*head)->val == node)
{
next = (*head)->next;
delete (*head);
(*head) = next;
}
else
{
LList* cur = *head;
while(cur->next)
{
if(node == cur->next->val)
{
next = cur->next->next;
delete cur->next;
cur->next = next;
break;
}
cur = cur->next;
}
}
}
};}
==========================
Implement an LRU cache.
==========================
You have a bag of random numbers which can be negative, positive or zero, and it might contain duplicates. Describe an algorithm for finding all pairs whose sum equals some value m.
Devide and conquer algorithm
Assume that m > 0
1. Devide all numbers for 5 buckets: 1st {n<0}; 2nd {n==0}; 3d {n>0 && n m}
2. To check if 2 numbers sum is equal to m we need to work with buckets this way:
a) if 2nd and 4th are not empty: sum of all numbers from 2nd and 4th are equal to m
b) if 1st and 5th are not empty check what sum of these negative and positive numbers are equal to m
c) Alpply devide and conquer algorithm to the 3d bucket.
==================================
Describe how you would reverse a single linked list.
template
class LList
{
public:
T val;
LList* next;
public:
static void Reverse(LList** head)
{
if(NULL == (*head))
return;
LList* headNew = NULL;
LList* cur = *head;
LList* next;
while(cur)
{
// to insert the pointer to the current node at the head of a new list
next = cur->next;
cur->next = headNew;
headNew = cur;
cur = next;
}
*head = headNew;
}
};
}
and same thing but recursive:
reverse(head)
{
if(head.next==null)
return head
next = head.next
newlist = reverse(next)
next.next = head
}}
======================
I am playing a card game called 24. Cards ace to king are numbered 1 to 13. During a given round, I am provided four cards to play with from the shuffled pack. If the numbers from the four cards result in 24 then I win the round if I shout '24' first. How would you code a function for this?
Four numbers and three operators at a time.
Consider permutations of such expressions in postfix notation.
Evaluate these permutations till you get 24.
It's a naturally recursive operation. Take the four cards, A, B, C, D.
In the different steps you have (target = 24):
(target) : using cards A, B, C, D
(target - A): using cards B, C, D
(target - A - B): using cards C, D
(target - A - B - C): using card D
Repeat for each of the other cards in the step's grouping if the target isn't met, ie.
(target) : using cards B, C, D
(target - B): using cards C, D
(target - B - C): using card D
And so on.
Pass true up the stack when any of the target values reach zero.
Once you have that down, it's trivial to write the function.
If we know the rules won't change (always four cards, always summing to 24) and speed REALLY matters, then the correct answer is to ignore complexity and elegance and let the CPU burn through this. Just add the first two cards and check the sum. If sum == 24, shout (return). If sum < 24, add third card and check. If sum < 24, add fourth card and check.
Sorting or structuring will take too much time even though it could be a big win in the general case - someone else will shout while we're moving our cards around.
It's a naturally recursive operation. Take the four cards, A, B, C, D.
In the different steps you have (target = 24):
(target) : using cards A, B, C, D
(target - A): using cards B, C, D
(target - A - B): using cards C, D
(target - A - B - C): using card D
Repeat for each of the other cards in the step's grouping if the target isn't met, ie.
(target) : using cards B, C, D
(target - B): using cards C, D
(target - B - C): using card D
And so on.
Pass true up the stack when any of the target values reach zero.
Once you have that down, it's trivial to write the function.
You only consider the + operator, which is not true in 24 points game. There are +,-,* and / 4 operators.
=======================================
Given the list of points of the skyline of a city in order (from East to West) Find the maximal rectangle contained in this skyline. I was asked to write the code. I managed to find the algorithm but was not sufficient.
Here's an O(n^3) dynamic programming solution. It's pretty ugly, but it seems to work. More elegant/efficient solutions would be greatly appreciated.
--------------------------------------------
import java.util.ArrayList;
public class Skyline {
private int maxX;
private int maxY;
public String[] findLargestRectangle(String[] points){
// First translate the points into a boolean matrix.
// The cell [i][j] in the matrix should be true if
// it appears under the skyline and false otherwise.
boolean[][] cells = this.pointsToMatrix(points);
System.out.println("Matrix is: ");
this.printBooleanMatrix(cells,maxX,maxY);
// Now we calculate rectangle size. Define
// s[i][j] to be the size of the rectangle
// with (i,j) at its upper left corner.
int[][] s = new int[maxX+1][maxY+1];
int maxSizeX = 0;
int maxSizeY = 0;
int maxSize = 0;
for (int i = 0; i < maxX; i++){
for (int j = 1; j < maxY+1; j++){
if (! cells[i][j]) {
s[i][j] = 0;
continue;
}
int maxHSize = 1;
int maxVSize = 1;
int i1 = i+1;
int j1 = j-1;
// Add one to the maximum horizontal size for
// each cell that is true towards the right.
while (cells[i1][j]){
i1++;
maxHSize++;
}
// Add one to the maximum vertical size for each
// cell that is true towards the bottom.
while (cells[i][j1]){
j1--;
maxVSize++;
}
int max = maxHSize * maxVSize;
s[i][j] = max;
if (max > maxSize){
maxSize = max;
maxSizeX = i;
maxSizeY = j;
}
}
}
System.out.println("Size matrix is: ");
this.printIntegerMatrix(s,maxX,maxY);
System.out.println("Maximum rectangle has size " + maxSize + ".");
System.out.println("Its upper left corner is (" + maxSizeX + "," + maxSizeY + ").");
return null;
}
// Points to be given as "1 0", "2 5", etc.
private boolean[][] pointsToMatrix(String[] points){
ArrayList list = new ArrayList();
// The maximum x-value will be that of the last point.
maxX = Integer.parseInt(points[points.length-1].split(" ")[0]);
maxY = 0;
for (int i = 0; i < points.length; i++){
String[] s = points[i].split(" ");
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
if (y > maxY) maxY = y;
list.add(new Point(x,y)); // Assume there are no duplicates
}
System.out.println("Points are: " + list);
System.out.println(" maxX = " + maxX + ", maxY = " + maxY);
boolean[][] m = new boolean[maxX+1][maxY+1];
int prevX = 0;
int prevY = -1;
for (int k = 0; k < list.size(); k++){
Point p = list.get(k);
//System.out.println("Next point: " + p);
int x = p.x;
int y = p.y;
int j = y;
// If y is zero, ignore the point.
if (y == 0){
// Do nothing.
}
// If x is zero, this is the first cell. Its value and the value
// of the cells below it is true.
else if (x == 0){
m[x][y] = true;
while (j > 0){
m[x][j] = true;
j--;
}
}
else {
// Look left. If the cell to the left is false, then this cell
// is true (start of rectangle top). The value of the cells below
// is also true.
//
// If the cell to the left is true and the previous point had the same value
// of x, then this cell represents the start of another rectangle. Set its value
// to true and the values of the cells below to true.
if ((! m[x-1][y]) || (prevX == x)){
m[x][y] = true;
while (j > 0){
m[x][j] = true;
j--;
}
// If the previous value of y is the same as this value of y and the
// difference between x values is greater than 1, fill in the cells
// in between.
if (prevY == y && (x - prevX > 1)){
int i = x-1;
while (i > prevX){
j = y;
while (j > 0){
m[i][j] = true;
j--;
}
i--;
}
}
}
// If the cell to the left is true and the previous point had a different
// value of x, then this cell is false (end of rectangle top). Set it and
// the cells below it to false. This cell may be inside another rectangle,
// in which case its value will be reset to true.
else {
m[x][y] = false;
while (j > 0){
m[x][j] = false;
j--;
}
}
}
prevX = x;
prevY = y;
//System.out.println("After " + p + ", matrix is: ");
//this.printBooleanMatrix(m,maxX,maxY);
}
return m;
}
}
private void printIntegerMatrix(int[][] b, int maxX, int maxY){
for (int j = maxY; j >=0; j--){
for (int i = 0; i <= maxX; i++){
System.out.print(String.format("%8d",b[i][j]));
}
System.out.println();
}
}
private void printBooleanMatrix(boolean[][] b, int maxX, int maxY){
for (int j = maxY; j >=0; j--){
for (int i = 0; i <= maxX; i++){
System.out.print(String.format("%8b",b[i][j]));
}
System.out.println();
}
}
class Point implements Comparable{
int x;
int y;
Point(int x, int y){
this.x = x;
this.y = y;
}
public int compareTo(Object o){
Point p = (Point) o;
return (this.x != p.x ? this.x - p.x : this.y - p.y);
}
public boolean equals(Object o){
if (! (o instanceof Point)) return false;
Point p = (Point) o;
return (this.x == p.x && this.y == p.y);
}
public int hashCode(){
return x*37 + y*19 + x*11 + y*7;
}
public String toString(){
return "(" + x + "," + y + ")";
}
}
/**
* @param args
*/
public static void main(String[] args) {
String[] points = {"0 2","1 2","1 1","2 1","2 3","3 3","3 0"};
Skyline s = new Skyline();
s.findLargestRectangle(points);
System.out.println();
String[] points1 = {"0 1","1 1","1 4","2 4","2 3","3 3","3 6","4 6","5 3","7 3","7 7","8 7"};
s = new Skyline();
s.findLargestRectangle(points1);
}
}
Output:
Points are: [(0,2), (1,2), (1,1), (2,1), (2,3), (3,3), (3,0)]
maxX = 3, maxY = 3
Matrix is:
false false true false
true false true false
true true true false
false false false false
Size matrix is:
0 0 3 0
2 0 2 0
3 2 1 0
0 0 0 0
Maximum rectangle has size 3.
Its upper left corner is (0,1).
Points are: [(0,1), (1,1), (1,4), (2,4), (2,3), (3,3), (3,6), (4,6), (5,3), (7,3), (7,7), (8,7)]
maxX = 8, maxY = 7
Matrix is:
false false false false false false false true false
false false false true false false false true false
false false false true false false false true false
false true false true false false false true false
false true true true false true true true false
false true true true false true true true false
true true true true false true true true false
false false false false false false false false false
Size matrix is:
0 0 0 0 0 0 0 7 0
0 0 0 6 0 0 0 6 0
0 0 0 5 0 0 0 5 0
0 4 0 4 0 0 0 4 0
0 9 6 3 0 9 6 3 0
0 6 4 2 0 6 4 2 0
4 3 2 1 0 3 2 1 0
0 0 0 0 0 0 0 0 0
Maximum rectangle has size 9.
Its upper left corner is (1,3).
Helpful Answer?
Yes | No
Inappropriate?
Dec 7, 2009
by ellemeno:
Found bug:
public *int* findLargestRectangle(String[] points){
...
*return maxSize*;
}
(obviously)
For others' reference:
http://www.topcoder.com/stat?c=problem_statement&pm=7473&rd=10661
http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm337
https://www.spoj.pl/problems/HISTOGRA/
http://www.informatik.uni-ulm.de/acm/Locals/2003/html/judge.html
ere's a much nicer O(n^2) solution. As Anonymous said, there's an O(n) solution, too.
/*
* In this input array a, the ith building
* has height a[i], which means its lower left
* corner is at (i,0) and its upper right corner
* is at (i+1,a[i]). All buildings have width 1.
* The total width of the skyline is n.
*/
public long getMax(long[] a){
int n = a.length;
int[] leftWidths = new int[n];
int[] rightWidths = new int[n];
// For each building, check how many units width to the left of the
// top block of this building we can move before we are no longer
// in a building.
for (int i = 0; i < n; i++){
int x = i-1; // Look left
int count = 0;
// Until we have passed the leftmost building and while the
// height of the next left building is at least as high as our
// building
while ((x >= 0) && a[x] >= a[i]) {
x--;
count++;
}
leftWidths[i] = count;
}
// For each building, check how many units width to the right of the
// top block of this building we can move before we are no longer
// in a building.
for (int i = 0; i < n; i++){
int x = i+1; // Look right
int count = 0;
// Until we have passed the rightmost building and while the
// height of the next right building is at least as high as our
// building
while ((x < n) && a[x] >= a[i]) {
x++;
count++;
}
rightWidths[i] = count;
}
// Now find the maximum rectangle. The value of the ith building's
// rectangle is its horizontal width times its height, or
// (1 + leftWidths[i] + rightWidths[i]) * a[i].
long maxArea = 1;
for (int i = 0; i < n; i++){
int totalWidth = 1 + leftWidths[i] + rightWidths[i];
long nextArea = totalWidth * a[i];
if (nextArea > maxArea) {
maxArea = nextArea;
}
}
return maxArea;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 8, 2009
by ellemeno:
O(n) solution:
/*
* Basic idea: use a stack to store the buildings. Look at
* the buildings in left-to-right order (west to east). If a
* building is taller than the building on the top of the stack
* (the tallest building to its left), push it onto
* the stack. If a building is equal in height to the building on the
* top, skip it. If a building is shorter than the building on the top,
* it is not part of the maximum rectangle that is topped by the tallest
* building to its left. Pop that tallest building, calculate its area and
* compare it to the current main area, then repeat the comparison
* procedure with the new tallest building.
*
* Along the way, track the number of buildings to the left and right of a
* given building that would participate in that building's maximum
* rectangle. The number to the left is equal to the number of buildings
* that are popped off the stack before this building is pushed - that is
* the number of buildings to the left of this building that are taller.
* We do not need to worry about the buildings that are equal in height
* since they are discarded (they are accounted for in the topBuilding's
* rightWidth count).
*
* The number of buildings to the right of this building that participate
* in this building's maximum rectangle is equal to the number of buildings
* that are discarded because they are equal to this building's height
* plus the number of buildings that are pushed onto the stack because they
* are taller than this building while this building is on the top of the
* stack.
*
* In this input array a, the ith building has height a[i], which means
* its lower left corner is at (i,0) and its upper right corner is at
* (i+1,a[i]). All buildings have width 1. The total width of the skyline
* is n.
*/
public long getMax_useStack(long[] a){
Stack stack = new Stack();
int n = a.length;
long maxArea = 1;
// Process the buildings in left-to-right order.
for (int i= 0; i < n; i++){
Building nextBuilding = new Building(a[i]);
// Keep track of the number of buildings that we pop before we
// push nextBuilding. That number will be equal to the number
// of buildings to the immediate left of nextBuilding that are
// taller in size.
int popCount = 0;
// If the stack is empty, push the next building onto the stack.
// There are no buildings to its left, so we do not need to
// update nextBuilding.leftWidth.
if (stack.empty()) {
stack.push(nextBuilding);
continue;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 8, 2009
by ellemeno:
(cont'd)
// Otherwise, compare the new building's height to the building on
// the top of the stack until the new building is either
// discarded (if it is equal in size) or pushed (if it is taller).
while (! stack.empty()){
Building topBuilding = stack.peek();
long heightDiff= nextBuilding.height - topBuilding.height;
// If the new building is equal in height, skip it. Increment
// the rightWidths count of topBuilding as its largest
// rectangle goes through the new building.
if (heightDiff == 0) {
topBuilding.rightWidth++;
break;
}
// If the new building is greater in height, push it onto the
// stack. The number of buildings to the immediate left of it
// that are taller is equal to the number of buildings that
// were popped before this point, its popCount. Set its
// leftWidth equal to its popCount. Increment the rightWidths
// count of the top building as its largest rectangle goes
// through the new building.
if (heightDiff > 0) {
nextBuilding.leftWidth = popCount;
topBuilding.rightWidth++;
stack.push(nextBuilding);
break;
}
// If the new building is less in height, update the maximum area
// with regards to the element at the top of the stack.
long topArea = topBuilding.getArea();
if (topArea > maxArea){
maxArea = topArea;
}
// Then discard the top element and repeat the comparison
// procedure with the current next building.
stack.pop();
popCount++;
}
}
// If all buildings have been processed and the stack is not yet empty,
// finish the remaining subproblems by updating the maximum area
// with regards to the building at the top of the stack.
while (! stack.empty()){
Building topBuilding = stack.pop();
long topArea = topBuilding.getArea();
if (topArea > maxArea){
maxArea = topArea;
}
}
return maxArea;
}
class Building {
long height;
int leftWidth;
int rightWidth;
Building(long y){
this.height = y;
leftWidth = 0;
rightWidth = 0;
}
long getArea(){
return height * (1 + leftWidth + rightWidth);
}
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 9, 2009
by logimech:
ellemeno,
Nice solution/explanation.
However, maxArea should be initialized to 0.
Helpful Answer?
Yes | No
Inappropriate?
Dec 9, 2009
by ellemeno:
@logimech
Right. :) Thanks.
Helpful Answer?
Yes | No
Inappropriate?
Dec 10, 2009
by tabatabaye:
ellemeno:
The program has bug. We need to store the building's x cordinate.
And when the nextbuilding is shorter than the top one, we need to update each popped building's rightwidth as topbuilding.x - nextbuilding.x
Helpful Answer?
Yes | No
Inappropriate?
Dec 13, 2009
by Pratyus:
Isnt this the convex hull problem?
Helpful Answer?
Yes | No
Inappropriate?
Jan 19, 2011
by Victor:
The O(n) algorithm does not work. I have another solution for it, however.
Suppose we have the array of heights a of length n. We are looking for the smallest building index (let's say x and divide the problem in 2: the left part ( between 0 and i - 1) and the right part (between i + 1 and n - 1). Then we compute the area that can be build using the building indexed with i: a[i] * (n - 1 - 0 + 1) = n * a[i]. We compare this area with the ones obtained from the left and from the right part and return the result.
Therefore, the complexity will be:
N * time to find the index of the smallest building in a range - which is RMQ problem that can be solved in O(logn) and O(n) preporcessing time (and O(N) space). Therefore, the complexity is O( N log N).
It works for 3 6 5 6 2 4: the solution is 3 * 5 = 15. The problem is known as the biggest rectangle below a histogram.
0)
===========================
find the ntersection of two integer arrays in increasing order.
Simple O(n log n) solution:
Sort the arrays individually, then compare.
O(n) solution:
Hash the elements in the first array to a hash table. Walk through the second array. If an element in the second array is in the hash table, add the element to a priority queue where priority = ~ value. Read the elements out of the priority queue. We could also use a bit array instead of a priority queue for unique, nonnegative integers.
================================
Write a program the generates the power set of a set of numbers
How about something like this? Running time is O(n!).
(Java)
/**
* The power set of S is the set of all subsets of S, including the empty
* set and S itself. It is parallel to the idea of all combinations of
* characters in a string.
*/
public Set> getPowerSet(Set s){
Set> pset = new HashSet>();
Object[] a = s.toArray();
// Add the empty set
Set subset = new HashSet();
pset.add(new HashSet(subset));
int n = s.size();
this.getPset(a,subset,pset,n,0);
return pset;
}
private void getPset(Object[] a, Set subset, Set> pset, int originalSize, int currentSize){
for (int i = currentSize; i < originalSize; i++){
subset.add(a[i]);
System.out.println("Attempting to add " + subset + ". i = " + i);
pset.add(new HashSet(subset));
if (i < originalSize - 1){
getPset(a,subset,pset,originalSize,i+1);
}
subset = new HashSet();
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 17, 2009
by OP:
That's a clever way to do it! Though good look thinking that up on the spot.
What i did was, assuming the set has n elements:
for (i; from 0; to (2^n)-1)
{
generate binary represenation of i padded to n bits. (e.g if n=8, and i =4, representation would be 00100000). Call this representation "bitmap"
for (j; from 0; to bitmap.length)
{
if bitmap[j]==1: add set[j] to a tempset
}
add tempset to a global array of sets
}
return that global array of sets
Note that this has exponential complexity which i believe (but am not sure) is better than factorial complexity
Helpful Answer?
Yes | No
Inappropriate?
Nov 18, 2009
by ellemeno:
OP, I think yours is better, and easier to understand too. :)
O(n*2^n) is better than O(n!) as n grows.
Thanks for posting the question.
Helpful Answer?
Yes | No
Inappropriate?
Nov 18, 2009
by ellemeno:
Here's the Java version of your algorithm if you don't want to explicitly pad:
Set powerset(Set set) {
Set power = new HashSet();
Object[] a = set.toArray();
int n = a.length;
int maxCount = (int)Math.pow(2,n);
for (int i = 0; i < maxCount; i++){
Set subset = new HashSet();
char[] c = Integer.toBinaryString(i).toCharArray();
int m = c.length;
for (int j = m-1; j >= 0; j--){
if (c[j] == '1') {
subset.add(a[(n-1)-(m-1-j)]);
}
}
power.add(subset);
}
return power;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 18, 2009
by neakor:
Using recursion and run in O(n2^n).
public List> powerset(final List set) {
// If set is empty, just return an empty powerset.
if(set.isEmpty()) return new ArrayList>();
// Pop the first element as a candidate for composition.
final Integer i = set.remove(0);
// Get powerset of the set without the candidate.
final List> subset = this.powerset(set);
// If the returned powerset is empty, add an empty set to it.
if(subset.isEmpty()) {
subset.add(new ArrayList());
}
// For all the existing sets in the powerset without the candidate,
// add the all combination sets of existing sets plus the candidate
// to the powerset.
final int length = subset.size();
for(int j = 0; j < length; j++) {
final List s = subset.get(j);
final List sWithi = new ArrayList(s);
sWithi.add(i);
subset.add(sWithi);
}
return subset;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 19, 2009
by ellemeno:
I finally got my head around a clearer version... credits to John Mongan et al:
public Set getPowerset(Set set) {
Set powerset = new HashSet();
powerset.add(new HashSet()); // Add the empty set
getPset(set.toArray(), new HashSet(), powerset, set.size(), 0);
return powerset;
}
private void getPset(Object[] input, Set subset, Set powerset, int n, int start) {
for (int i = start; i < n; i++) {
Object o = input[i];
subset.add(o);
powerset.add(new HashSet(subset));
if ( i < n-1) {
getPset(input, subset, powerset, n, i+1);
}
subset.remove(o);
}
}
Time for n = 16 for binary version: 10089 ms. Items: 65536.
Time for n = 16 for recursive version: 9379 ms. Items: 65536
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Dec 17, 2009
by vic:
ellemeno dude if you don't ace your google interview, I'm going to be very disappointed :)
Good luck!
Helpful Answer?
Yes | No
Inappropriate?
Jun 19, 2010
by George:
A little theory: A power set is defined as all subsets of a set S. A specific k-subset of set S will contain n!/(k!(n-k)! elements ( also known as nCk or n Choose k. The lower bound on the operations you have to perform to generate nCk elements is nCk. Since we need all n subset to generate the powerset, total number of operations is the sum of all n choose k for k = 0 to n == 2^n -> lower bound on the algorithm
A little code in Python
def powerset(iterable):
from itertools import combinations
s = list(iterable)
return [ combinations(s, r) for r in range(len(s)+1) ]
if you can't import the combinations function, suggest you'll implement one yourself. Give a reasonable explanation of how you would do it.))}}}}}}}
=============================
Develop an algorithm for finding the shortest distance between two words in a document. After the phone interview is over, take a few hours to develop a working example in C++ and send it to the manager.
Can you do a greedy approach? find the first occurrence of either of the 2 words. Then go through the document until you find the first occurrence of the other word. you need to do this twice. each word will take O(n), which gives you still O(n).
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 11, 2009
by ellemeno:
Assume that we will be passed two Strings that represent the words weâd like to find. Assume âdistanceâ means the number of characters between occurrences â that is, line breaks will be ignored. Assume the document is represented by a long string. We need to find the two occurrences of these words that are closest together.
Simple solution:
- Walk through the string and find each occurrence of word A. Store the middle index of this occurrence
- Walk through again and find each occurrence of word B. Store the middle index of this occurrence.
- Compare the arrays of indicies. Find the smallest difference between each middle position of A and each middle position of B.
- Running time = O(n + ab) where a and b are the number of occurrences of the input strings A and B.
Walk through the document, character by character, looking to match word. If we find such a match, put the index of the middle character into the array. Continue on our walk. Repeat for the second word. Now we have two arrays of integers. Our new task is to find the smallest difference between the elements in each array. Use the mergesort merge method, keeping track of the smallest difference. Return this distance.
Optimization:
Instead of walking one character at a time, when we find a mismatch, skip ahead by an intelligent number of characters â that is, to the next index at which we might find a good match. We can use the Boyer-Moore algorithm for this approach.
Further optimization:
Look for both words in one pass by using Boyer-Moore tables that account for both words. As we walk, keep track of the current shortest distance. Running time is O(n).
Does anyone have a simpler or clearer answer?
Helpful Answer?
Yes | No
Inappropriate?
Nov 12, 2009
by Anonymous:
@ ellemeno
Perfect!
Helpful Answer?
Yes | No
Inappropriate?
Nov 14, 2009
by @ Anonymous:
Thank you! I have my first technical phone interview with Google on Monday. Wish me luck!
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Dec 13, 2009
by Anonymous:
I would clarify with the interviewer, but it doesn't seem to me that finding the words in the document is the principal focus of the question, so would concentrate on the basic algorithm assuming an efficient word finder (which could be implemented independently).
So here's my take on the algorithm:
1. Find the first instance of word A or B (assume A going forward). Continue searching (e.g. iterating) and each time you find another A, discard last recorded position of A until you reach and record the first B. (If B is the first word reverse A and B in the last sentence). The distance is the first try.
2. Continue searching until you reach the next instance of A or B. Measure the distance to the last recorded instance of the other word. If it's less than the current smallest distance, discard the last recorded instance of the word and record the distance.
3. Repeat 2. until the distance between the words found is greater than the current smallest distance.
4. Keeping track of the distance, start 1 again from current index until you find the next smallest distance or until you run out of words. Replace the recorded smallest distance each time you find one smaller.
Helpful Answer?
Yes | No
Inappropriate?
1 of 5 people found this helpful
Jan 13, 2010
by Grant:
The shortest distance between two words is a space. My algorithm would simply search for the first occurrence of a space.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Jan 18, 2010
by nEx:
Grant, I whole-heartedly agree. It doesn't say that they are two specific words, just the shortest distance between two words... Which would naturally be the one space character between each word. In this case, the algorithm could simply return 1, and not even bother with searching the document at all. After all, the question doesn't really ask where the shortest distance is located in the document.
Helpful Answer?
Yes | No
Inappropriate?
Jan 18, 2010
by Jeff in Boston:
Since this is labeled a C++ programming question asked at a top-notch software company solving difficult problems, handing in a program that always returns 1 probably isn't a good idea. If I were a hiring manager at Google I'd want to see the algorithms, data structures, & design skills you have at your fingertips. If I got this question during an interview at Google with no chance to ask additional questions, I'd assume they wanted the answer to a hard problem. And if I were interviewing for a C++ programming position but never asked such a question, I'd worry about the competence of current staff.
Helpful Answer?
Yes | No
Inappropriate?
2 of 3 people found this helpful
Jan 18, 2010
by Jeff in Boston:
P.S. - If I could ask a question, it would be whether the document was already indexed ('cuz I'm interviewing at Google after all). Then try to show a bit of linguistic sensitivity, such as whether intervening sentence and paragraph boundaries should count as "extra" distance. After the interviewer left the room, I'd Google the Web for an answer - why reinvent the wheel? ;-)
Helpful Answer?
Yes | No
Inappropriate?
Jan 6, 2012
by John in Waterloo:
index1 = -1
index2 = -1
minDistance = -1
Scan the string for words.
For each word:
1. If it matches 1st word, set index1 to index of word.
2. If it matches 2nd word, set index2 to index of word.
3. If it matches neither word, continue
4. If index1 == -1 or index2 == -1 continue
5. distance = abs( index1 - index2 )
6. minDistance = (minDistance == -1) ? distance : min( distance, minDistance )
================================================
* Describe a balanced binary tree. * When would you want to use a balanced tree rather than a hashmap?
Each tree node only contains a maximum of 2 children nodes maintained in a particular order. For instance, left child has a value less than the right child. The parent node typically has a value in between the 2 children. (greater than left child, but less than right child).
When ordering of elements in the data structure matters. for instance, keep the root node as the node with the largest or smallest value for fast retrieval. Also when the hierarchical parent children relationship is important for a complete traversal. for instance when a parent is marked as invisible, all of its children are also considered invisible, e.g. scene graph bounding tree.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 7, 2009
by Chris:
Thanks for the answers Neakor. It all looks good, but I think we need to include emphasis on the "balanced" part of balanced binary tree, which means that the insert & delete operations are specialized to keep the tree's height relatively low. For example, an AVL tree does this by trying to keep all leaves close to the same level of the tree. This "balanced" constraint keeps the tree from degenerating into a linear linked list.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 7, 2009
by neakor:
thanks for the clarification chris! very helpful!
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 10, 2009
by ellemeno:
(assume "balanced binary tree" means "balanced binary search tree", else the question doesn't really make sense)
A balanced binary search tree is a tree-based data structure where each node has at most two children and each level is complete except possibly the deepest. The left descendants of a given node have keys less than the nodeâs key and the right descendants have keys greater than the nodeâs key. Finding an item in a balanced binary search tree runs in O(log n). Insertion and deletion run in O(log n). Finding an item in a hashmap runs in constant time, but one would want to use a balanced binary tree if the hashmap function is imperfect and many key collisions are expected to occur. With a balanced binary tree, there will never be more than one value per node. One may also want to use a balanced binary search tree if the hash function is particularly slow.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Apr 24, 2010
by Anonymous:
ellemeno nailed it but a little more info.
The reason you want balanced tree is to have all the operations be O(logn) where an unbalanced tree would have O(n) for all operations.
A hash has constant insert and O(n) search. It does have average constant time search but if you need to minimize O(), a balanced tree gets you a better search time (though worse on average)
Helpful Answer?
Yes | No
Inappropriate?
Apr 25, 2010
by Shards:
Balanced trees have predictable and constant space overhead, hashtable, in general, does not. It is worse if the hashtable is only sparsely populated. Balanced trees are also generally better when you need to traverse the contents a lot rather than simply searching. Given a balanced ordered tree, you can easily get a sorted list of all members (O(n)), or find k-th smallest/biggest member easily (O(lg n)). This can't easily be done with hashmap (O(n lg n)).
============================
Describe preorder, inorder, postorder.
preorder: the root node is visited before the sub-trees are visited in a traversal.
inorder: the root node is visited in between the left sub-tree and the right sub-tree in a traversal.
postorder: the root node is visited after both sub-trees are visited in a traversal.
===========================
* Write a function, preferably in C or C++, to reverse a string.
I'm no c/c++ person. so here's my solution in java.
public void reverse(final char[] array) {
final int half = array.length/2;
final int last = array.length-1;
for(int i = 0; i < half; i++) {
final int j = last-i;
final char ci = array[i];
final char cj = array[j];
array[i] = cj;
array[j] = ci;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 10, 2009
by ellemeno:
More concisely (still Java):
public String reverse(String s){
char[] a = s.toCharArray();
int n = a.length, j = n-1;
for (int i=0; i < n/2; i++){
char c = a[i]
a[i] = a[j-i];
a[j-i] = c;
}
return new String(a);
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by vic:
C++ Solution. I got this question on another interview albeit with the constraint that I couldn't use any temp variables. So the swapping is done using math:
a = a+b;
b = a-b;
a = a-b;
Will swap a and b!
To convert this into a C solution, pass char* s with the length and use pointers.
void reverse (string &s) {
int start = 0;
int end = s.length() - 1;
while (start < end) {
s[start] = s[start] + s[end];
s[end] = s[start] - s[end];
s[start] = s[start] - s[end];
start++;
end--;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by Chris:
Thanks all for the nice solutions. There's another good C solution at StackOverflow, and it's allegedly UTF safe: http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c/198264#198264
Helpful Answer?
Yes | No
Inappropriate?
Feb 17, 2010
by Benquan Yu:
@ vic
a = a+b; // this may cause overflow.
you can use the ending '\0' as a temp for swapping, and restore it to '\0' after the whole loop is done.
Helpful Answer?
Yes | No
Inappropriate?
}
=====================
* Describe the design of a most-recently-used list, such as the "Recent Files" menu in Microsoft Word. It has two public methods, getlist() and access(str), which retrieve the list and mark an item as accessed, respectively. The list has a maximum number of items it can hold, say 5, and it should not have duplicates. Describe the data structure used and the running time of both public methods.
Answers & Comments (10)
0 of 1 people found this helpful
Nov 8, 2009
by Anonymous:
It will be a queue.
getlist() will return head of queue - O(1)
access(str) will check if str will exist and if not, insert at the head - O(1)
space - O(1)
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2009
by neakor:
To the above answer:
I don't think that will work. first of all, a queue is usually defined as FIFO, so you can only add to the tail of the queue. Secondly, using a queue to check if an item exists will take O(n) time, not O(1) as you suggested. So insertion will take O(n). also using a queue does not guarantee the fixed length. think of the MS example, your first accessed item will eventually get pushed out of the list when you keep accessing new files.
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2009
by Anonymous:
To above, actually we need to use a stack instead.
Checking against the stack won't be O(n) since the size of the stack is constant (5). It will be O(1).
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2009
by Chris:
For what it's worth, the final solution I arrived at with the Google engineer--and he confirmed he was satisfied with it--was to use a dictionary with the strings as keys for O(1) lookup, where the values in the dictionary act as doubly-linked lists for O(1) insertion & removal.
He wanted to be sure I covered all 3 logical cases every time I improved my solution towards the final one:
* Returning the sequence in appropriate MRU order
* Maintaining the order at insertion
* Maintaining the maximum list size at insertion
Anonymous, your point about constant size, while technically correct, might feel like a bit of a cop-out in an interview. It's a good observation, but I think I would point it out and then ask if the analysis should assume arbitrary n for the maximum size. Since this is Google, processing infinite streams of data daily, we might assume they want an MRU list that could be used for arbitrary n. In that case I believe we do need a little more machinery than a plain stack or queue.
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2009
by Chris:
To add to my above response, taking n to be the size of the list (though technically bounded by a constant at instantiation), we would have to say that space use is O(n) rather than O(1). While Anonymous's observation that the max size 5 is given in the problem definition is both correct and astute, I think that interviewers would appreciate a candidate to then go further and assume arbitrary n for the max size. Then the candidate has an opportunity to display understanding of the purpose of asymptotic notation, which is not to prove O(1) by whatever means possible but instead to give an informed analysis of resource usage for a proposed design. Again, either O(1) or O(n) in this problem can be correct, provided you explain what your variable n means and give its domain. In the context of an interview, I think I would run through both analyses and most importantly, talk talk talk to the interviewer about my thoughts as I proceed.
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2009
by Anonymous:
Thanks Chris for your explanation - I agree.
Did they get back to you with an offer?
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2009
by Chris:
They got back to me but they turned me down for now. I didn't ask for more information, but I imagine it's because I look like a big risk. I have sort of sabotaged myself with too much schooling & TA/RA work and too little paid experience.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 9, 2009
by neakor:
My 2 cents:
I don't think using either a stack or a map(dictionary if you will) would be a very good solution as maintaining the order would be important in this case. stack must be LIFO, and a map is simply not good for ordering.
A special case must be considered is when an item already exists in the list but not the top, then when this item gets accessed, it should pop to the top while pushing other items down. though none of the elements already in the list should be removed in this case.
in order to maintain order and satisfy the above special case, an array for fixed size or an array-based queue/list would be a better fit. note i specifically said array-based queue as they are easier to sort and manipulate ordering than a linked list. sorting a linked list is simply nightmare.
finally an alternative, and also good solution would be to use a binary search tree structure with the tree sorted based on the access order. this would give pretty good general case performance for both fixed size and arbitrary length.
Helpful Answer?
Yes | No
Inappropriate?
Nov 10, 2009
by ellemeno:
I would use a hash table with the strings as keys and a string pair as the values, as Chris described. I would also have two sentinel elements that would hold the most recently used string and the least recently used string.
The basic access(myStr) algorithm:
// Check if str is MRU, O(1)
if (myStr == mru) return;
// Remove LRU, O(1)
tmp = lruStr.successor
tmp.predecessor = null
remove lru from table
lru = tmp
// Check if myStr in table, O(1)
if (myStr in table)
// "Remove" myStr, O(1)
myStr.predecessor.successor = myStr.successor
myStr.successor.predecessor = myStr.predecessor
endif
// Add myStr as head, O(1)
myStr = mruStr.successor
myStr.predecessor = mruStr
mruStr = myStr
Comments, corrections, and advice greatly appreciated.
Helpful Answer?
Yes | No
Inappropriate?
Feb 17, 2010
by Benquan Yu:
@ neakor
array is not a good solution either, because it is not easy to remove an item in the middle and insert in the front.
a simple single linked list should do the work. get list is O(1), since you only need to return the head. access(str) is O(n). you travel the list and count how may items you traveled, if you find it (str), just remove it from the list. And if you did not find it right before you hit the end, and if total number of items exceeds the limit, remove the last one. after you travel the list, put the new item in the front.
Helpful Answer?
Yes | No
Inappropriate?
=============================
* You have a data structure of integers, which can be negative, zero, or positive, and you need to support an API with two public methods, insert(int) and getmedian(). Describe a data structure you would use to support this API and describe the running time of the two methods. * Imagine you're writing a function that takes an array of integers and an integer and it needs to return true if any pair in the array sum to the 2nd argument. The array can have negative numbers, zero, or positive numbers. Describe how you would design this function and what its running time would be. I ran through the trivial n^2 solution, then modified it to an nlogn and finally to a linear solution.
>>You have a data structure of integers, which can be negative, zero, or positive, and you need to support an API with two public methods, insert(int) and getmedian(). Describe a data structure you would use to support this API and describe the running time of the two methods.
-----------------------------
You have several choice here, with differing running times for insert and getmedian. You could use an unsorted list, implemented as an array. With an unsorted list, insert would run in constant time and getmedian would run in O(n). You could use a sorted list, implemented as an array. Finding the location to insert would run in O(log n), actual insertion is O(n) in the worst case since all elements might need to be shifted over, and getmedian could run in constant time since you could keep a sentinel variable to track the center. Lastly, you could use a self-balancing binary search tree, such as a red-black tree. With self-balancing binary search trees, insertion would run in O(log n) time and getmedian would run in constant time since the root is always the median.
-------
(Is that correct? Did I leave out any major structures?)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 10, 2009
by ellemeno:
>>Imagine you're writing a function that takes an array of integers and an integer and it needs to return true if any pair in the array sum to the 2nd argument. The array can have negative numbers, zero, or positive numbers. Describe how you would design this function and what its running time would be
---------------------------------
For O(n^2), I'd use a nested for loop that summed a[i] with a[j] whenever i != j.
For O(n log n), I would first sort the list with mergesort (O(n log n)), then compare the sum of a[0] with a[n-1]. If it is less than the target, compare a[0] plus a[n-2]. If it is greater than the target, compare a[1] plus a[n-1]. In the worst case, you'd perform n/2 comparisons.
For O(n), create an empty bit array of size abs(2*target)+1. Walk through the list. Check bit[(target - a[i])]. If set, return. If not set, set bit[a(i)]. The idea is that as you walk through the list, you check if the required "partner" of each element is set, where a[i] + partner of a[i] = target. If the partner's bit is set, we know that there is a pair that sums to the target.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 26, 2009
by Anonymous:
The answer to the median question is to actually use two heaps, a min heap and a max heap. Google for "median heap"
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by Chris:
Nice solutions. I now remember there was a follow-up to the median question:
* Suppose you know the numbers will all be between 0 and 200, though there can still be duplicates. Can you change your solution using this information?
Helpful Answer?
Yes | No
Inappropriate?
Feb 17, 2010
by Anonymous:
@ellemeno
your O(n) solution for the second question won't work if there is a hung negative num say -100*target and a huge positive num 101*target, they sum to target, but your bitmap won't able to hold them.
For O(n), create an empty bit array of size abs(2*target)+1. Walk through the list. Check bit[(target - a[i])]. If set, return. If not set, set bit[a(i)]. The idea is that as you walk through the list, you check if the required "partner" of each element is set, where a[i] + partner of a[i] = target. If the partner's bit is set, we know that there is a pair that sums to the target.
Helpful Answer?
Yes | No
Inappropriate?
Apr 25, 2010
by Shards:
@ellemeno
For the first question, you can't simply pick off the root of a balanced tree. (I'll let you figure why.)
For the second question, a simple O(n) solution would be to utilize hashmap from the value to # of occurrences. Then go through the list again, for each number k, check whether sum - k is in hashtable. This is just a rough framework, you need to be careful of duplicate answers and things like sum/2 + sum/2 = sum (does sum/2 occurs once or twice).
Helpful Answer?
Yes | No
Inappropriate?
Dec 3, 2010
by __:
@Anonymous Feb17,2010
In that case, instead of having bitArray of size 2*target+1, the bitArray may be sized largest-smallest+1 [largest and smallest can be calculated in O(n)] and the indices vary from smallest to largest.
Helpful Answer?
Yes | No
Inappropriate?
==========================
There were 2 questions: 1 design and 1 implementation. The design was something like the following: you have a billion google searches a day, design a data structure which lets you pull out the top 100 unique ones at the end of the day.
I started off with an implementation on the file system, when he got me to compute the size of memory required to maintain a billion numbers (where I screwed up majorly). Finally we figured out we need 14 32-bit computers. After this I started using a tree of tries, which maintains the top 100 throughout : like in insertion sort(because maintaining all billion and at the end computing the top 100 takes a lot of time, a few years). He did not like my design and told me I was complicating the whole thing big time.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Nov 7, 2009
by neakor:
Why can't you just maintain a priority queue or a binary search tree where you put the smallest node on top. then every time a new query comes in, you just check if the queue is full. if it is full, replace the smallest which would be the root. if it's not full, just directly insert into the queue and do a sort.
in terms of memory, you only need 100 elements in the queue and the queue itself. in terms of performance, you get the typical nlogn insertion of binary search trees.
Helpful Answer?
Yes | No
Inappropriate?
Nov 12, 2009
by Anonymous:
neakor,
if at some point the search will be smth like:
search 1
search 2
search 1
search 2
and so on
your idea will not work
Helpful Answer?
Yes | No
Inappropriate?
Nov 14, 2009
by ellemeno:
I think the best way to approach this problem is to use two data structures: one to hold the searches with their individual counts and one to hold the current top 100 unique ones.
We can use a hash table to hold the search strings. Weâd want to use a table of one billion slots and choose a hash function that assures a uniform distribution of our strings over the slots. In terms of memory consumption, we must store one billion strings and one integer (32-bit, since 10^9 = ~2^30) for each of those strings. Assume that the average length of the string is 100 characters or less. This is probably a good estimate; the actual average length is probably more like 10 or 15 than 100 since most of the time people search using only one or two words. Assume each character requires two bytes of memory. Therefore, we need:
(2 bytes/char * 100 char/str * 10^9 str) + (4 bytes/int * 10^9 int)
= 200 GB + 4GB = 204 GB memory
Lookup and insertion into the hash table run in constant time with respect to n, the number of search strings.
Another data structure we can use to store the strings and their counts is a radix tree or a Patricia trie. A radix tree is a tree in which the edges are labeled with characters and internal nodes are shared by strings that have their prefixes in common. The leaf nodes hold a special termination character and, in this case, our count. This data structure will take up less space than the hash table since the strings are not stored explicitly and instead share nodes. In the worst case, where every search string is unique, the radix tree becomes quite large and unwieldy, but of course we do not expect such a case to happen since the input is not at all random.
The data structure that we can use to store our top 100 unique searches is a priority queue. A priority queue is a queue in which the elements are ordered by some priority value that is provided at insert time. In this case, weâd use the search count for each string as its priority and the last element in the queue would be the string with the highest search count. We could also maintain this highest search count value separately to add processing.
So, for every incoming string, check if itâs in the hash table. If it is, check if its old count is less than or equal to the highest search count in the priority queue. If that is true, the string may be in the priority queue, so we remove it from the priority queue if it is there. Next, increment its count. If its new count is still less than than highest search count in the priority queue, add it to the queue. If the item is not in the hash table, add it to both the hash table and the priority queue with a count of 1. Remove the 1001th item from the priority queue and reset the highest search count value.
---------------------------
Obviously this approach requires a *ton* of memory. Does anyone have a better solution?
Helpful Answer?
Yes | No
Inappropriate?
Dec 13, 2009
by Anonymous:
You don't have to store each search query individually - think string hash - you can create a dictionary of hash to word and store each search query as a single byte per word (allowing you 65536 words - enough for the english language at least). Two bytes per word would give you 4billion possible words.
Each search query can be represented by a combination of word hashs, so you create another hash table containing (combined hash -> count). A billion non-repeating search queries, assuming an average of five words per query, would be stored in 10GB.
At the end of the day, you can iterate through the data and use a min heap to store the top results. If the next value is greater than the current min, insert it in the min heap and remove the current min (root node). Finally, sort the heap.
Helpful Answer?
Yes | No
Inappropriate?
Dec 13, 2009
by Anonymous:
Duh - double the byte sizes in my response above - I'd hope I'd not say 2^16 is one byte in an interview. Still 20GB max is scalable.
==================================
The implementation question: Find a max and min in an array simaltaneously. I used a 2n comparisons approach and a 1.5n on-average approach.
There is a very common simple approach which does worst case 1.5n (google for this), could not come up with this. The interview ended such that I did not do both the questions anywhere near satisfactorily. So expecting a negative result :(
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Oct 29, 2009
by neakor:
You can use a simple divide and conquer technique in which you divide up the array recursively and only compare when you reach the leaf node, in which case you only have two numbers in your divided array. Then recursively go up to compare with the results from other sub-arrays. This should give you a worst case 1.5n comparison performance.
Helpful Answer?
Yes | No
Inappropriate?
Nov 7, 2009
by cockroachzl:
Hey neakor,
please do not keep misleading others, divide and conquer will lead u O(nlogn).
Helpful Answer?
Yes | No
Inappropriate?
Nov 7, 2009
by neakor:
hi cockroachzl:
a complete sorting using divide and conquer will lead to worst case O(nlogn).
however, in this case, the merging steps can be simplified to just two comparisons, thus allowing the worst case performance to be 1.5n. i have the algorithm implemented in java. you can try it out. for the merging step, just check the first and last elements of the 2 sub arrays and do swaps.
Helpful Answer?
Yes | No
Inappropriate?
Nov 14, 2009
by ellemeno:
I'm confused... why not just:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++{
if (a[i] > max) {
max = a[i];
}
else if (a[i] < min)
min = a[i];
}
}
Is this the 2n approach? O(2n) = O(n)....
What am I missing?
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 14, 2009
by ellemeno:
Sorry... found it. Thank you CLR!
int tempMin, tempMax;
int max = a[0];
int min = a[0];
for (int i = 1; i < n-1; i = i+2){
if (a[i] <= a[i+1]){
tempMin = a[i];
tempMax = a[i+1];
}
else {
tempMin = a[i+1];
tempMax = a[i];
}
if (tempMax > max) {
max = tempMax;
}
if (tempMin < min) {
min = tempMin;
}
}
if (n % 2 == 0) { // Do this if there are an even number of elements
if (a[n-1] < min) min = a[n-1];
else if (a[n-1] > max) max = a[n-1];})))))
====================
Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. Do this in sub-linear time. I.e. do not just go through each element searching for that element
Binary Search will do this in O(log n)
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by vic:
To respond to Sid's comment:
Binary search is the way to go, but you do need a slight modification, coz a simple binary search may not necessarily return the index of the first occurence, e.g. given input array
7777777777, what would a simple search return?
The trick would be to seek to the left if the index at the middle of the current partition is the element you are looking for.
The performance would depend on how many duplicates there are on average + log n
If this average is n as in the above example you are looking at O(n/2), but then if you knew that already you could simply return the first element :)
Anyone have a better idea?
Helpful Answer?
Yes | No
Inappropriate?
Apr 24, 2010
by Anonymous:
binary search for target.-1. At the last step remember where you were checking even if you don't find it. If the element is target this is the first one. Otherwise it is in the next index of the array.
Helpful Answer?
Yes | No
Inappropriate?
Apr 24, 2010
by Anonymous:
*I left out an important part. You need to modify the binary search for the case that there's more than one instance of target-1. If you are at a node that matches your search and the right and the item at the next index also matches, move to the right child and continue searching.
=========================================
Given two linked lists, return the intersection of the two lists: i.e. return a list containing only the elements that occur in both of the input lists.
Answers & Comments (3)
1 of 1 people found this helpful
Oct 13, 2009
by Radu Litiu:
Traverse the first list. Insert all the elements in the list into a hash table. Complexity: O(n)
Traverse the second list. For each element in the list, look it up in the hash table. If it is in the hash table, then insert it into the destination list. Complexity: n * O(1) = O(n)
Total complexity: O(n)
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 7, 2009
by neakor:
Hi Radu Litiu,
Your solution is correct though the complexity analysis is incorrect.
Insertion and lookup from the hashtable can take a worst case performance of O(n) or O(logn) if you use a priority queue as the backend storage. This means that while traversing the lists for n times, each time you can encounter a O(n) complexity thus resulting in a worst case performance of O(n^2), or at least O(nlogn).
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by vic:
Here is where I am confused: A hashtable is supposed to have a O(1) lookup, is it not?
The actual implementation of a hash table is platform specific. For e.g. C++ hashtables are Balanced binary search trees?
Helpful Answer?
Yes | No
=================================
Answers & Comments (3)
1 of 1 people found this helpful
Oct 13, 2009
by Radu Litiu:
Traverse the first list. Insert all the elements in the list into a hash table. Complexity: O(n)
Traverse the second list. For each element in the list, look it up in the hash table. If it is in the hash table, then insert it into the destination list. Complexity: n * O(1) = O(n)
Total complexity: O(n)
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 7, 2009
by neakor:
Hi Radu Litiu,
Your solution is correct though the complexity analysis is incorrect.
Insertion and lookup from the hashtable can take a worst case performance of O(n) or O(logn) if you use a priority queue as the backend storage. This means that while traversing the lists for n times, each time you can encounter a O(n) complexity thus resulting in a worst case performance of O(n^2), or at least O(nlogn).
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by vic:
Here is where I am confused: A hashtable is supposed to have a O(1) lookup, is it not?
The actual implementation of a hash table is platform specific. For e.g. C++ hashtables are Balanced binary search trees?
Helpful Answer?
Yes | No
======================================
What's the difference between a hashtable and a hashmap?
n the general sense, there's no difference in a hashtable and a hashmap. There are, however, differences between the two Java classes named "Hashtable" and "HashMap" You'd need a real programmer to explain the key differences between the two. But, at first glance, it looks to me like one module, Hashtable is meant for use in a multi-thread context, while HashMap is not. For what it is worth, like I said, I ain't a Java programmer, but I did sleep at a Holiday Inn last night (not really).
Helpful Answer?
Yes | No
Inappropriate?
Nov 7, 2009
by neakor:
I'd assume this question is asked in Java context.
There are 3 differences:
1. Hashtable is completely synchronized. There is no concurrent access allowed but it is thread-safe in the sense that only a single thread can access the table. HashMap is not thread-safe in any ways.
2. Hashtable does not allow null keys or null values(you will get a NPE). HashMap allows both null keys and values.
3. Hashtable's enumerator is not fail safe, meaning if the map is changed during iteration, there is no way of knowing so. HashMap's iterator is fail safe, if the map is modified during iteration, you will get a ConcurrentModificationException.
======================
Given an array of integers which is circularly sorted, how do you find a given integer.
bool FindInCirArray (int& array_cir[SZ], int data)
{
int& arr[SZ] = array_cir[SZ];
enum ArDir {UNK, UP, DN};
bool pivot_found = false;
ArrDir arr_dir = UNK;
int pivot_point = -1; // negative means undetermined
// first check if the integer is in the first three
....
// determine the direction and the pivot point
if (arr[1] <= arr[2] <= arr[3]) {
arr_dir = UP;
} else if (arr[1] >= arr[2] >= arr[3]) {
arr_dir = DN'
} else {
// pivot in the first 3 elements... determine by comparison
.....
pivot_point = X; // value found
}
for (int k = 0; k < N; k++) {
if (arr[k] == data) {
return (true);
if (dir == UP) {
if (arr[k] > data) {
return (false);
if (arr[k+1]) < arr[k]) {
pivot = k+1;
dir = CHANGE_DIR;
break;
}
}
// repeat for the other direction
if (pivout > 0) {
// loop to find the data and return
....
}
// check the end of array and return false
....
return false; // end of the road... did not find data
}}}}
==================================
Most phones now have full keyboards. Before there there three letters mapped to a number button. Describe how you would go about implementing spelling and word suggestions as people type.
Each key will represent 3 possibilities (letters). If N keys are pressed, it will create 3^N possibilities. The Dictionary of known words is organized as a Radix Tree on the Alphabet. Then just lookup the tree for the 3^N possibilities. Display the possible completions (spelling check) as well as longest matches.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Dec 26, 2010
by real_solver:
Take every word in the dictionary, and convert it to a sequence of digits.
Form a trie where the keys are the digit sequences, and values are the words.
With every key press, the possible completions will be a smaller sub-tree of the previous trie.
Possible improvements, if data and computation power are available:
-Display words in decreasing order of frequency in English language.
-Display words in decreasing order of probability based on some Markov model.
-Find possible typos by looking at keys with a short Hamming distance away from the typed sequence.
=================================================================
Implement on a board a shortest path algorithm when traveling from point A to point B on a board. Once you produce a solution, they throw modifications to an initial problem like what if you know that points x, y, z cannot be used in a path.
design, google, brain teaser
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 29, 2009
by google man:
This can be solved using SPF (Shortest Path First) or Dijkstra's Algorithm. If some points are excluded then it is solved using CSPF (Constraint Shortest Path First) algorithm. Make the cost of the points excluded infinity then apply SPF.
===============================================================
Write a program to find depth of binary search tree without using recursion
nswers & Comments (2)
Aug 28, 2009
by answer man:
// Traverse the tree and count the depth at every leaf. The maximum count is
// the depth of the tree
// SInce recursion is not allowed use a Stack. Any recursive problem can be solved
// iteratively by using a stack
// Rough skeleton code, without testing
class TraverseTree {
public:
Traverse_Tree { curr_depth = max_depth = 0; }
void push(Node& n);
int get_depth() { return max_depth }
void inc_depth()'; { curr_depth++; }
void set_max_depth { if (curr_depth > max_depth) max_depth = curr_depth; }
private:
int curr_depth;
int max_depth;
}
int bst_depth (const Node& root)
{
Traverse_Tree t;
const Node& n = root;
while (n) {
t.inc_depth();
t.push(n);
if (n->left) {
n = n->left
continue
} else if (n->right) {
// same as for left tree
.....
} else [
// leaf node
t.set_max_depth();
n = t.pop()->right ;
t_dec_depth();
}
}
return t.get_depth();
Helpful Answer?
Yes | No
Inappropriate?
Jul 31, 2011
by Anonymous:
do a preorder traversal, and find the depth from the resulting array. time complexity = O(n^2)
'}
============================
The question was the following. I'm rephrasing the question to make it clear for everyone to understand: - You are going on a one-way flight trip that includes billions of layovers. - You have 1 ticket for each part of your trip (i.e: if your trip is from city A to city C with a layover in city B, then you will have 1 flight ticket from city A to city B, and 1 flight ticket from city B to city C. - Each layover is unique. You are not stopping twice in the same city. - You forgot the original departure city. - You forgot the final destination city. - All the tickets you have are randomly sorted. Question are: - Design an algorithm to reconstruct your trip with minimum complexity. - How would you improve your algorithm. Example: - randomly sorted: New York->London San Francisco-> Hong Kong Paris->New York London->San Francisco - sorted: Paris->New York New York->London London->San Francisco San Francisco-> Hong Kong
)
Answer:
1. Select a ticket from the pool of tickets that is different from all the previously selected starting tickets.
2. Keep a count on how many tickets you have used.
3. Keep walking on the ticket path until you exhaust all possible paths without going back. Increment count every time a ticket is used.
4. If the final count equals the total number of tickets you have, you've got the path sorted.
5. Otherwise, repeat from step 1.
Can be improved via parallelization where you can shoot off multiple threads each having its own starting ticket in parallel. Whenever a thread completes the sorting based on step 4, stop all other threads.
Helpful Answer?
Yes | No
Inappropriate?
Nov 7, 2009
by cockroachzl:
Represented it as a direct graph, the number of nodes are N+1, the number of edges are N,
topological sorted, Time = O(N)
Helpful Answer?
Yes | No
Inappropriate?
Nov 21, 2009
by lucita:
Represented as a directed graph.
Start from node without any entering edge O(n) and follow the path O(n).
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by vic:
Hmm, I implemented this graph using a Hashtable :
Note that this solution will only work for unique layovers...
The starting cities are the keys, and the ending cities are the values
Helpful Answer?
Yes | No
Inappropriate?
Nov 27, 2009
by vic:
I forgot to finish my answer:
loop through all the entries {
add the start->end pairs in there (checking to see if the start doesn't already exist) and an empty entry for the end city (again, only if it doesn't already exist). In the case that you add a start->end entry, the start becomes your global start.
}
Then just follow the white rabbit from the global start at the end to get your list :)
If I've screwed up somewhere please let me know, thanks!
Helpful Answer?
Yes | No
Inappropriate?
Feb 4, 2010
by Adrian:
I think its simpler than that. Just count all of the cities on the tickets. The original departure and final location city will appear once (assuming unique layovers, an odd number of times with non-uniqueness) this is O(n).
Then, follow the path, which I think is O(n^2) because you have to check the remaining remaining tickets each time.
Helpful Answer?
Yes | No
Inappropriate?
Feb 17, 2010
by Benquan Yu:
none of these will work for billions of layovers. you can not load billions of layovers into memory.
Helpful Answer?
Yes | No
Inappropriate?
Dec 4, 2011
by mike:
Benquan Yu, yes but to reconstruct the whole path we'll always need O(N) memory, either RAM memory or disk space.
Helpful Answer?
Yes | No
Inappropriate?
====================================================
what's the your favorite sorting algorithm and explain why?
This is an invitation for you to discuss your understanding of one or more sorting algorithms, both the pros and cons. One might pick quick sort, and say it's the fastest algorithm out there, and that it lends itself well to a multiple thread/processor scenario, since once the pivoting phase is completed, the numbers on each side of the pivot can be further sorted independently, which means that portion can be handled by its own thread/processor.
===================================================
integer partiontioing given N (a integer) how many ways you can write as N summation of other numbers 5 = 1+ 2 +2 = 2+ 2 + 1 = 1 + 3 +1 = 1 + 4 etc.. write C code to print every combination
Answers & Comments (5)
3 of 6 people found this helpful
Apr 1, 2009
by Interview Candidate:
for given N it is 2 to the power N - 1
Helpful Answer?
Yes | No
Inappropriate?
1 of 4 people found this helpful
May 5, 2009
by Another Interview Candidate:
The answer is (2^N) - 1. NOT 2^(N-1) as the above answer seems to indicate.
Helpful Answer?
Yes | No
Inappropriate?
2 of 3 people found this helpful
May 22, 2009
by Anonymous:
Not that simple.
See
http://en.wikipedia.org/wiki/Integer_partition
Helpful Answer?
Yes | No
Inappropriate?
2 of 3 people found this helpful
Aug 9, 2009
by Anonymous Coward:
If the problem is really about partitions, then the previous poster is correct that the solution is complicated. However, if 1+2+2 and 2+2+1 are to be counted as distinct "compositions", (rather than the same partition), then the answer is 2**(n-1) as stated by the first Interview Candidate. Proof: Consider n sticks placed side by side. Between every two sticks you may place a comma or a plus. Each choice gives a distinct composition.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Aug 26, 2009
by yaskil:
Here is my solution
int intpartition( int nn, int number, int iter, int r[512] )
{
int i;
int res;
//static int result[255];
int sum;
sum = 0;
for( i=0;i 0; i /= 26)
low += i;
// if value is lower than lower bound, decrease quotient by one
if( denominator != 1 && col < (quotient * denominator + low) ) {
quotient --;
}
printf("%c", quotient - 1 + 'A');
col = col - denominator * quotient;
denominator /= 26;
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jun 29, 2010
by JParija:
Let the size of the string asked is 3 e.g GHD . The formula to this :
[ 26+26^2+...+ 26^(size-1) + (LetterIndex-1)*{26^(size-1)+....+(LetterIndex-1)*26}+Index ]
Helpful Answer?
Yes | No
Inappropriate?
Jun 29, 2010
by JParija:
In the code the above formula will use recursion to find the column number.
Helpful Answer?
Yes | No
Inappropriate?
Dec 10, 2010
by Naresh:
The answer can be as simple as finding the first combination of number * i such that it is less then xcelcolvalue;
ie
repeat this till xcelColValue >= 26
( 0 < i <= 26) * num < xcelColValue;
xcelColValue -= i*num
public static String xcelString(int xcelNum) {
StringBuffer sb = new StringBuffer();
while(xcelNum >= 26){
int i = 1, num = 1;
while((num * (i + 1)) < xcelNum)
if(i > 26){ i = 1; num++;} else i++;
xcelNum -= num*i;
sb.append((char) i);
}
if (xcelNum > 0) sb.append((char) xcelNum);
return sb.toString();
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 10, 2010
by Naresh:
Also the above code is rough idea and not tested but gives enough idea on simplifying the solution. The code does not use lot of / and % calcuations but could elegantly find the solution. Note the Gaurd if(i > 26){ i = 1; num++;} else i++;
which is important in finding the combination of num and i which multiples at least to xcelNum.
Helpful Answer?
Yes | No
Inappropriate?
Dec 10, 2010
by Naresh:
I think the above is incorrect and it should be :
public static String xcelString(int xcelNum) {
StringBuffer sb = new StringBuffer();
while(xcelNum >= 26){
int i = 1;
for(;(26 * (i + 1)) < xcelNum; i++);
xcelNum -= 26 * i;
sb.append((char) i);
}
if(xcelNum > 0)
sb.append((char) xcelNum);
return sb.toString();
}}}}
=================================
Design a data structure for LRU cache
Would a Priority Queue work here? If we have a hash function to help us the lookup, then we might have to just end up truncating tail of the Queue and add element to the head or vice versa.
==========================================
which 2 datastructures will you use to design a dictionary .
i answered ...hashtable and tree
Helpful Answer?
Yes | No
Inappropriate?
Jul 1, 2010
by Anonymous:
I would say a trie/radix tree for efficient word searching, and LinkedList for the definitions of the word. This even allow to link words together (for example : "Please see: word:").
If you say HashTable, never assume its implementation is correct. If you want to use a hash table, then explain what kind you will be using, for example: "Perfect Hashtable (a hash table where each bucket holds another hash table)".
=========================================
How would you store 1 million phone numbers?
Answers & Comments (3)
3 of 3 people found this helpful
Sep 7, 2009
by Anonymous:
Depends entirely on what I was going to do with them.
Helpful Answer?
Yes | No
Inappropriate?
1 of 3 people found this helpful
Jan 13, 2010
by Anonymous:
If the purpose was to search for a phone number, I would store them in a sorted order. Perhaps in a tree. The reason being, we can quickly use O(nlogn) for searching, which will tremendously be quick.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Mar 20, 2010
by Anonymous:
The key here is that 1 million phone numbers will be within some range, likely 10 million or so. 10 million bits = 10^7 bits ~ 0.12 GB. Just have a bit array where the first bit being set implies that the first phone number is set (e.g., 10 000 000) and the last bit indicates the last phone number (10 999 999). If you find a number in the list, just set the appropriate bit. You now have a bit vector of size 1million bits, sorted, and to check for a particular number, you just check whether the corresponding bit is set.
======================
Design a web search engine that searches web locations for anagrams of a given string.
Some books suggests tries as data structure for search engines to store inverted indexes.
The trie store the words and at the end of the word there is a list of documents which contain that word.
If I would do a search engine for anagrams, when I index the document I would not store the words as they are, but in lexicographic order (the word "bamboo" will be "abbmoo").
When performing a search I will not look for the query but for its lexicographic order version.
====================
Design a 2D dungeon crawling game. It must allow for various items in the maze - walls, objects, and computer-controlled characters. (The focus was on the class structures, and how to optimize the experience for the user as s/he travels through the dungeon.)
============================
Quad tree bitmap: describe data structure and an algorithm
===========================
Giving n numbers, and one number s, find out whether there are two numbers form the n numbers sums up to the number s. Finding one solution is extremely easy, but what's required is to find out ALL solutions to the problem and analyse the run times.
Answers & Comments (4)
Apr 25, 2010
by Shards:
First, fill a hashmap from the number to number of occurrences of the number (O(n)). For each number n, find whether s - n and n is in the hashmap with occurrence > 0. If so, you have a match, reduce # of occurrences for s-n and n by 1. (Note that if s-n = n, the number of occurrence must obviously be >1.) The entire algo is O(n).
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Apr 25, 2010
by That's the obvious solution:
You won't pass if you don't find another one. Hint: no extra data structure like the hashmap.
Helpful Answer?
Yes | No
Inappropriate?
Jul 7, 2010
by Joe Mama:
This assumes a sorted list in input. Runtime is O(n).
public static List getPairs(int[] num, int x) {
int n = num.length, s=0, e=n-1;
List ret = new LinkedList();
for (int i=0; i= e) return ret;
if (v[1] >= x-v[0] && e-- <= s) return ret;
}
return ret;
}
Helpful Answer?
Yes | No
Inappropriate?
Feb 22, 2011
by NehaGupta:
Why List ...? Why not Array? We can apply bin_search on sorted array and get complexity of o(lg n).
Even if unsorted, which is expected sort that in o(nlgn) time then apply the above algo. This effectively give you o(nlgn).
===============
Write a function to modify a singly linked list, appending copies of the first N-1 elements to the end in reverse order. For example, ['A', 'B', 'C', 'D'] becomes ['A', 'B', 'C', 'D', 'C', 'B', 'A'].
Answers & Comments (8)
1 of 2 people found this helpful
Nov 4, 2011
by Using stacks:
Well I would use a stack to hold the N-1 elements. Then pop one by one and attach it to the end of the list !
Helpful Answer?
Yes | No
Inappropriate?
Nov 12, 2011
by Rob:
I would not use stacks because you don't have to.
this would be more memory efficient. remember to think google scale for google interview questions.
char[] appendReverse(char[] in)
{
int n = in.length;
char[] out = new char[n2-1];
for(int i = 0; i < n; i++)
{
out[i] = in[i];
out[n-i] = in[i];
}
return out;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 14, 2011
by Anonymous:
Given that the original question states that we're using a singly-linked list rather than arrays, I think the stack-based solution (proposed by 'Using stacks' above) is the right one.
Helpful Answer?
Yes | No
Inappropriate?
4 of 5 people found this helpful
Nov 19, 2011
by MB:
Actually, you don't have to use stack or any other data structure. What you can do is have to pointers one is pointing the last element (in this case 'D') and the other one is the head of the list. Add the first element at the end of the list. It becomes A', 'B', 'C', 'D' 'A' then move the head pointer next element and add it to after 'D' :A', 'B', 'C', 'D' 'B' 'A'. Finally add 'C'
'D' :A', 'B', 'C', 'D' 'C' 'B' 'A'
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Nov 21, 2011
by mike:
You can do everything on the fly by creating an auxiliary reversed list. Then just append this list to the last element of the original list
struct List {
List * next;
char val;
};
void modify( List * node ) {
if (node == NULL)
return;
List * rev = NULL ;
while (node->next != NULL) {
List * newNode = new List;
newNode->next = rev;
newNode->val = node->val;
rev = newNode;
node = node->next;
}
node->next = rev;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 25, 2011
by Alec:
Followed MB's suggested algorithm. O(1) space required (for two pointers), O(n) runtime (two loops of n):
void modify (Node * node) {
Node * last = node;
while (last->next != NULL) {
last = last->next;
}
Node * curr = node;
while (curr != last) {
Node * duplicate = new Node;
duplicate->key = curr->key;
duplicate->next = last->next;
last->next = duplicate;
curr = curr->next;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 13, 2011
by Bo Hu:
I bet they just want to see your implementation using recursion.
void foo(node *p)
{
if(p->next == 0)
return p;
node * end = foo(p->next);
end->next = p->copy();
return end->next;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 22, 2011
by Anon:
One loop can provide O(n) time and O(2n-1) space.
def modify(root):
s = root
last = node(root.v)
while root.n.n:
root = root.n
n = node(root.v)
n.n = last
last = n
root.n.n = last
return s
Helpful Answer?
Yes | No
Inappropriate?
}}}}}}}
==============================
Given an array of structs: write a function that finds equal values in all the structs in the array
==============================
You have a n number of cities. Lets say city 1 has some information that needs to be sent to all other n-1 cities using minimal cost. Cost between each pair of cities is given. any number of cities can transmit the information once they receive the information but the overall total cost should be minimum
Dijkstra's algorithm
Helpful Answer?
Yes | No
Inappropriate?
4 of 5 people found this helpful
Nov 16, 2011
by Kurtis:
Dijkstra's tells you the shortest path from city 1 to any other city, but instead it is looking for a minimum spanning tree (MST). Prim's and Kruskal's algorithms would work.
===================
Out of 10 coins, one weighs less then the others. You have a scale. How can you determine which one weighs less in 3 weighs? Now how would you do it if you didn't know if the odd coin weighs less or more?
First Trial: 5 coins at each side of the scale. Exclude all the 5 coins in the heavy side.
Now you have only 5 coins.
Second Trial: Hold one coin in your hand and put 2 coins at each side of the scale. If the two sides weighs the same, then the lighter one is the one you are holding in your hand (FINISHED).
If one side is heavier than the other, exclude the two coins in that side. Now you have only 2 coins and a scale to find out which is the lighter by using the scale for a third time :)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jan 12, 2012
by Eskimo:
Weight 3 vs 3, set 4 aside.
if there's balance you're left with 4 -> weigh 2 vs 2 -> if there's balance weigh 1 vs 1.
If there's no balance weigh 1 vs 1 from the lighter side. if there's balance choose the 1 left, else choose lighter.
Best case 2 weighs, worst case 3 weighs.
As for doing it without knowing if it's lighter or heavier:
break 10 to 3,3',3',1
function weigh(grp1, grp2) {
if grp1 is heavier return -1
if grp1 == grp2 return 0
else return 1
}
res1 = weigh(3,3')
res2 = weigh(3,3')
if (res1 == 0 && res2 == 0) choose the '1'
if (res1 == -1 && res2 == -1) newGrp = 3, odd coin is heavier
if (res1 == 1 && res2 == 1) newGrp = 3, odd coin is lighter
if (res1 == 0 && res2 == -1) newGrp = 3', odd coin is lighter
if (res1 == 0 && res2 == 1) newGrp = 3', odd coin is heavier
if (res1 == 1 && res2 == 0) newGrp = 3', odd coin is heavier
if (res1 == 1 && res2 == -1) Not possible (3 lighter than 3' and heavier than 3')
if (res1 == -1 && res2 == 0) newGrp = 3', odd coin is lighter
if (res1 == -1 && res2 == 1) Not possible (3 heavier than 3' and lighter than 3')
newGrp is 3 coins and you know if the odd coin is heavier or lighter.')))'''
=================
Array of 100 integers from 1 to 100, shuffled. One integer is taken out, find that integer.
Answers & Comments (5)
1 of 1 people found this helpful
Dec 28, 2011
by Anonymous:
The answer is relatively simple and requires linear space and linear time, which in this case is number of numbers to be assessed. Additionally, this solution works for both one and more than one missing numbers. (Note: there is no error checking...)
public static void findremoved(int[] input) {
HashSet s = new HashSet();
for(int i = 1; i <= 100; i++) s.add(i);
for(int i = 0; i < input.length; i++)
s.remove(input[i]);
for(int e : s)
System.out.println(e);
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 29, 2011
by Anonymous:
Constant space and linear time:
def missing_num(numbers):
s = len(numbers) + 1
for i, num in enumerate(numbers):
s += i+1
s -= num
return s
numbers = range(1, 101)
numbers.remove(89)
random.shuffle(numbers)
print missing_num(numbers)
Helpful Answer?
Yes | No
Inappropriate?
Jan 3, 2012
by chandra shekhar:
sum = 0;
n = 100;
for( i =1; i <= n; i++)
sum += array[i];
print( (n+(n+1)/2 ) - sum )
Helpful Answer?
Yes | No
Inappropriate?
Jan 4, 2012
by Anonymous:
you meant print( (n*(n+1)/2 ) - sum )
Helpful Answer?
Yes | No
Inappropriate?
Jan 8, 2012
by alan:
5050 - sum. 5050 is the sum from 1 to 100
Helpful Answer?
Yes | No
Inappropriate?
======================
Google Interview Question
Post an Interview
Web: www.google.com | HQ: Mountain View, CA
Overview
|
Salaries
|
Reviews
|
Interviews
|
Photostats
|
Jobs
1,021 Interview Reviews |
Back to all Google Insteadterview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
Dec 21, 2011
========================
How to find the max number of a shift buffer queue. For instance, there is an array like 5, 6,8,11,1,2, how to find the max number, which is 11 in this example.
Answers & Comments (6)
0 of 2 people found this helpful
Dec 7, 2011
by Interview Candidate:
Binary search.
Helpful Answer?
Yes | No
Inappropriate?
Dec 16, 2011
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
0 of 1 people found this helpful
Dec 19, 2011
by Gabriel:
Of course you can use binary search! :) Think about it! You just have to know where you are!
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
int[] list = new int[]{5, 6, 8, 11, 1, 2};
int max = list[0];
for(int i = 1; i < list.length; i++)
{
if (i > max)
{
max = i;
}
}
return max;
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
I see a couple of people suggested use binary search to find the max above, In order to do perform binary search, the list needs to be sorted. If the list is already sorted, you don't need a binary search to find the max number since it's located at the end of the list.
Helpful Answer?
Yes | No
Inappropriate?
Jan 15, 2012
by Liron:
int[] arr = new int[]{5,6,8,11,1,2};
int max = arr[0];
for (int i =0; i list1 = new ArrayList();
for (int i=0; i list2 = new ArrayList();
for (int i=0; i max)
{
max = i;
}
}
return max;
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
I see a couple of people suggested use binary search to find the max above, In order to do perform binary search, the list needs to be sorted. If the list is already sorted, you don't need a binary search to find the max number since it's located at the end of the list.
Helpful Answer?
Yes | No
Inappropriate?
Jan 15, 2012
by Liron:
int[] arr = new int[]{5,6,8,11,1,2};
int max = arr[0];
for (int i =0; imake my trip
Answer Question
2nd Round:
A design question (don't remember) and another question on adversarial mini-max search
3rd Round:
Write a method to find the next ancestor of a node in a Binary Search Tree.
Write a recursive function to convert Binary Code of a number into its equivalent Gray's code and the other way round.
4th round:
Given two sorted arrays, find the kth minimum element of both.
Given a set of intervals, find the interval which has the maximum number of intersections.
5th round:
This one was focused on previous projects and experience and how good I was at what I had been doing.
Answer Question
==================
why do you want to choose Google?
Answer Question
where is your edge?
=============
Cominations of strings.
==============
1) Code and analyse the function findMaximums(). 2) Use a sorted data structure (a binary tree). 3) std::vector findMaximums(int* Data, int N, int K) where 4) Data is an array of int's. 5) N is the size of the array Data. 6) K is the number of element from Data you want to compare and maximize. 7) The vector you return is the list of these "local maximums".
by neslon:
std::vector findMaximums(int* Data, int N, int K)
{
std::vector list;
qsort(Data, n, sizeof(int), compare);
for (int i = N ; i--; i>0)
{
if (Data[i]>K)
list.push_back(Data[i]);
else
break;
}
return list;
}}
===================
the binary representation of 4100
I wonder what the interviewer expected to hear in response. I personally was puzzled for some minutes thinking that i should use some general manual division technique to convert. In real life i just have a calculator. Then i realized that 4100 is 4096 + 4. Given than 4096 is 2^12 and 4 is 2^2 coming up with 100000000100 was easy.
======================
Given a sorted array, find how many times a specified element appears.
nswers & Comments (4)
0 of 3 people found this helpful
Mar 25, 2011
by Dan:
One time, because is a sorted array.
Helpful Answer?
Yes | No
Inappropriate?
Apr 6, 2011
by v:
I suppose "a specified element" means "a given value". "Specified element" normaly means "element with the given index", and there is only one such element. So, "find how many times a given value appears in a sorted array" would be the question to answer.
First, binary search yields _some_ element at _some_ index "j" with the given value in O(log(N)) time. Then step to the left and to the right from "j" till find values different from the given one. The number of steps is (K+1) where K is the number of elements with specified value.
The total computation time can vary between O(log(N)) and O(N) - the latter is when K is comparable to N
Helpful Answer?
Yes | No
Inappropriate?
Apr 19, 2011
by Naresh:
One way it to do binary search and look left and right to find number of items.
Other way is to do two binary search. One establishes arr[i] < X && arr[i+1] >=X and other etablishes arr[i] <= X && arr[i+1] > X. The number of items is difference of these two indexes.
public static int numEquals(int[] arr, int num) {
if(arr.length <= 1){
return arr[0] == num ? 1 : 0;
}
if(arr[0] == arr[arr.length]){
return arr.length;
}
int left = 0, len = arr.length;
int i = 0, j = len;
//Establish condition arr[i] < X && arr[i+1] >= X
for(; i + 1 != j;){
int k = (i + j) / 2;
if (arr[k] < num) i = k; else j = k;
}
//Establish condition arr[i] <= X && arr[i+1] > X
if (arr[len-1] == num) return len - i;
for(left = j, j = len; i + 1 != j;){
int k = (i + j) / 2;
if (arr[k] <= num) i = k; else j = k;
}
return j - left;
}
Helpful Answer?
Yes | No
Inappropriate?
Apr 19, 2011
by Naresh:
Minor correction above
if(arr.length == 1){
return arr[0] == num ? 1 : 0;
}
=================
Implement Binary Search
=================
Some web sites have text in multiple languages. How could you determine the dominant language of a web page when indexing it? (open-ended question)
Answers & Comments (2)
0 of 1 people found this helpful
May 23, 2010
by Interview Candidate:
One trick is that without knowing the page's encoding, it's hard to guess character width.
Helpful Answer?
Yes | No
Inappropriate?
Oct 7, 2010
by vsp:
without encoding:
1. Done once: compile hashes of all the words in all dictionaries of supported languages. Good hash function should keep collisions at minimum.
2. Once per page: compute hashes of all unique words and check them against hashes against each dictionary. The dictionary with the maximum number of matches gives the dominant language.
Complexity (step 2 only): N*M, where N - the number of supported languages, M - the number of words in a page. Using hashes is required for constant-time look-up of words in the dictionaries.
=========================
Copy a graph.
Breadth first of depth first search.
======================
write an algorithm to divide two numbers using only loops and addition.
Answers & Comments (6)
1 of 1 people found this helpful
May 12, 2010
by Interview Candidate:
delegate the problem to one of the mindless google calculator boys.
Helpful Answer?
Yes | No
Inappropriate?
May 17, 2010
by marcos:
// I don't get this question....
// Is there any Aha algorithm for solving it, instead of the naive approach?
int divide(int dividend, int divisor)
int ans=0, partial=0;
while(partial+divisor= number) {
System.out.println((j));
break;
}
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jun 10, 2010
by Anonymous:
If they were looking for engineers with dumb ideas like totally destroy their branding by copying Bing's background image function, this would definitely be a good recruiting questions.... like I said before; idiots!
Helpful Answer?
Yes | No
Inappropriate?
Jul 7, 2010
by Andi Mullaraj:
int a = 9;
int b = 2;
int sum = 0;
int result = 0;
while (sum + b < a) {
int term = b;
int mult = 1;
while (sum + term < a) {
result = result + mult;
sum = sum + term;
term = term + term;
mult = mult + mult;
}
}
Print result;
It's not hard to realize the calculation time is O(Log(a)) and more precisely C * Log(a/b) <= Time <= C * 2 * Log(a/(2*b))}
============
Write a code to check whether partially filled sudoku is proper or not
What do you receive as an entry? A NxN matrix with the squares filled and empty?
Helpful Answer?
Yes | No
Inappropriate?
Mar 24, 2010
by Anonymous:
ya The interviewer meant that 9x9 matrix .. which are subdivided into boxes like in sudoku .. and some elements are filled in.
Writing a N3 solution was the most obvious .. but interviewer wanted a solution which was efficient.
Helpful Answer?
Yes | No
Inappropriate?
Jan 21, 2011
by v:
// Create a bunch of sets keeping numbers 1 through 9 for
// a) 9 columns, b) 9 rows, and c) 9 3x3 boxes:
Set[] columns = new Set[9];
Set[] rows = new Set[9];
Set[][] boxes = new Set[3][3];
// Sudoku board:
int[][] board = new int[9][9];
initialize(board); // assume uninitialized cells set to 0
// The algorithm:
for (int row = 0; row < 9; ++row) {
int row_box = row%3;
for (int col = 0; col < 9; ++col) {
int col_box = col%s;
int value = board[row][col];
if (value == 0) continue; // empty
if (rows[row].contains(value)) return false; // conflict within a row
else rows[row].add(value);
if (columns[col].contains(value)); return false; // conflict within a column
else columns[col].add(value);
if (boxes[row_box][col_box].contains(value)) return false; // conflict within a box
else boxes[row_box][col_box].add(value);
}
return true; // proper
Instead of using Set, one can use BitSet, replacing all calls to contains(int) with isSet(int), and add(int) with set(int).
The performance is O(N^2) where N is the matrix dimension (9) not the number of elements (81). You cannot do better than that because all N^2 elements must be checked.
Additional memory is O(N), provided we keep the box sise SQRT(N). For instance, for Sudoku with N = 100, the box size would be 10. This way, the number of sets for all boxes would still be SQRT(N)^2 == N.
Helpful Answer?
Yes | No
Inappropriate?
Jan 21, 2011
by v:
two typos in my algorithm: use integer division "/" instead of remainder"%" to find a box for a given cell:
int row_box = row/3;
...
int col_box = col/3;
For performance freaks, it can be further optimized using lookups:
int[] lookup = { 0, 0, 0, 1, 1, 1, 2, 2, 2 };
...
int row_box = lookup[row];
...
int col_box = lookup[col];"}
========================
Whats is max possible edges in a graph with no cycles.
n-1
Helpful Answer?
Yes | No
Inappropriate?
1 of 5 people found this helpful
Apr 18, 2010
by ha:
n * (n - 1) / 2
For example,
2 nodes: 1 edge, (0,1)
3 nodes: 3 edges, (0,1), (0,2), (1, 2)
4 nodes: 6 edges, (0,1), (0,2), (0, 3), (1, 2), (1, 3), (2, 3)
Helpful Answer?
Yes | No
Inappropriate?
Feb 3, 2011
by s:
it's n-1. In response to ha, your 3 nodes and 4 nodes examples both have cycles.
======================
How would you write a sort routine to ensure that identical elements in the input are maximally spread in the output?
This is my opinion:
First of all, understand what "maximally spread out" means - if we have an array of 4 identical elements, there are 4! = 24 permutations we can arrange the elements by.
If we measure for each element the distance of its new position minus its old one (i.e. the number of "hops" the element made), and sum these measurements we get an idea of how well the permutation "mixed up" the array.
However, there is more than one such maximal permutation, and so we need to choose the "maximally spread out" one. I think this is the one where the minimal amount of "hops" for any element is maximal, in the 4 elements array case - each element does 2 hops, i.e. [a b c d] turns into [c d a b].
In order to achieve this we can use a *stable* MergeSort, and when performing the last merge (e.g. between [a b] and [c d]), we simply choose to perform this specific merge with preference for items from the right array and not the left one.
(all through the recursions levels of the operation we stayed stable, meaning we preferred to initially place elements from the left array, this time we do the opposite).
We can accomplish this by giving an extra boolean parameter for the recursion, the top level gets it as 'true' and invokes all other levels with it being 'false'.
... This is just my opinion :)
Helpful Answer?
Yes | No
Inappropriate?
Jan 21, 2011
by v:
I am confused for more than one reason.
First, "sort" usually means "arranged in ascending or descending order". In sorted output the identical elements are right next to each other, not "maximally spread out"! Or do I miss something?
If your "sort" means "any arrangement that follows certain rules", then you should mention what these rules, besides identical elements in the input being maximally spread out. Is there some ordering of non-identical elements?
Helpful Answer?
Yes | No
Inappropriate?
May 21, 2011
by dantepy:
probably dynamic programming question, o(n^2)
for each item in input_array
for i=0 to i=output_array.length
if (item == output_array[i]) {
swap_in_output_array(i, i-count)
count++
}
output_array.append(item)
===============
How would you reverse the image on an n by n matrix where each pixel is represented by a bit?
Answers & Comments (5)
Aug 28, 2009
by coder:
void ReverseImage (bool &image, int const &size)
{
for (int i=0; i < size; i++) {
for (int j=0; j < size; j++) {
image[i][j] = !image[i][j];
}
}
}
Helpful Answer?
Yes | No
Inappropriate?
Aug 28, 2009
by coder:
void ReverseImage (bool &image, int const &size)
{
for (int i=0; i < size; i++) {
for (int j=0; j < size; j++) {
image[i][j] = !image[i][j];
}
}
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 1, 2009
by thinker:
Surely the challenge is to flip the image not just to change white pixels black and black pixels white.
Assumptions: n is even; flip along the vertical axis
ReverseImage (image, length, width)
{
center = width/2
for (i=0 to length) {
for ( j=1 to center) {
if image[i][center-j] != image[i][center-1+j]{
image[i][center-j] = !image[i][center-j]
image[i][center-1+j] = !image[i][center-1+j]
}
}
}
}
Technically length and width are both n but I thought the code is easier to read if we give them separate, meaningful names.
Instead of the if statement, you could always swap all the values
temp = image[i][center-j]
image[i][center-j] = image[i][center-1+j]
image[i][center-1+j] = temp
But that is always three operations whereas the if statement is only 3 operations in the worst case.
Helpful Answer?
Yes | No
Inappropriate?
Aug 5, 2011
by tommypickles:
why not use bitwise NOT operation?
For unsigned integers, the bitwise complement of a number is the "mirror reflection" of the number across the half-way point of the range of the unsigned integer type. For example, for 8-bit unsigned integers, ~x == 255 - x, which can be visualized on a graph, as a downward line, which effectively "flips" an increasing range from 0 to 255, to a decreasing range from 255 to 0. A simple use of this is that to invert the colors of a grayscale or RGB image where each color component for every pixel is stored as an unsigned integer, one simply needs to bitwise complement all these integers.
Helpful Answer?
Yes | No
Inappropriate?
Aug 5, 2011
by tommypickles:
Update: I've just realised the question was to reverse the image (not the colors) !!
}}}}}}}
=======================
Design a networked 'snake' multiplayer game. What are the problems and issues to be solved? When the network 'splits' I want the game to continue for all players.
Consider messaging between clients, or client server approach etc. Vague question
=========================
Given a string of characters, find the character with the highest frequency.
Consider hashmap of counters approach, or array of counters depending on the range of valid characters.
========================
Fibonacci numbers... haha.
It can be done in O(logN) time is you are really clever. O(n) is the standard iterative answer, if you cache the last two calculations. If you gave the recursive answer, O(2^N), then that is why you failed.
========================
Given a graph, find if it represents a tree.
I think this can be done by traversing the graph in Breadth First manner, and if you happen to visit a node more than once, it is a graph, otherwise it is a tree
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 21, 2011
by mike:
a tree is a graph with N-1 edges (N = number of vertices). then i think you just need to pick 1 vertex and check if you can reach all the others from this one
Helpful Answer?
Yes | No
Inappropriate?
Dec 29, 2011
by pat:
it depends on your definition of a tree. Technically all you need to qualify as a tree is to have that tree's nodes be connected and have no cycles. That means you don't necessarily need all the nodes of the graph to be part of the tree (that's called a spanning tree)
==============
nterviewed Aug 2011 in Mountain View, CA (took 2 months)
I had always wanted to work at Google, but I never thought I would get in. I'm 45 years old and I have a 2.2 GPA.
My friend at Google submitted my resume and I waited quite a while before I got a rejection letter. In retrospect, with them receiving 3000 resumes a day, it must be very easy to get lost in the shuffle unless your resume really stands out, and mine certainly did not. I waited a while and then contacted Google again and asked them to reconsider my resume, and they did. From that point on, it was an amazing process.
Right away I got an email asking when would be a good time for a recruiter to talk with me (HR screen). I said, "If not now, when?" and 60 seconds later I got a call from the recruiter. We talked for 45 minutes and mostly it seemed like just fun chitchat. She asked about my experience and what I liked to work on and what languages I preferred. Then she said she would find an engineer suitable for me and would call me back soon. She called the next day and we scheduled a phone interview (tech screen) for the following week. She also send me an email about what to expect and things to brush up on.
The next week I got the call from an engineer. We worked together in a Google Doc, and on the phone. He asked me about my resume, particularly my machine language experience. Then we did a bit manipulation problem, and I missed an obvious optimization. Then he asked me the main problem which was very clever. I came upon the solution very quickly, using recursion, but I screwed up on the complexity analysis. Afterwards, we chatted about Google life. It was a fun experience, but I figured I had blown it.
I got a call from the recruiter an hour later telling me that the feedback was positive and that we would move on to the on-site interview. I spent a month in front of my white board practicing problems, especially from Gayle Laakmann's book, Cracking the Coding Interview. I read through Introduction to Algorithms , but there was just too much information in there to cram into my brain.
At one point I was worried about my low 2.2 GPA and asked if I would be given a chance to explain the situation. I sent them an email and 30 seconds later one of the recruiters called me and said, basically, no one cares about your GPA. I get the impression that it's just a metric they use if there's nothing else on your resume to judge you by.
I am not going to describe the interviews here. Sorry. Not only did I sign an NDA, but I also don't want to spoil it for anyone. I will just say this much: Those people who said, "They asked me a simple CS101 question and I answered it and they still didn't hire me, those arrogant pricks!", well, dude you completely missed the point of the exercise. It's really not about getting the "right" answer.
The interviewers were all very cool. Some were reserved, and some were friendly and outgoing. I had a very fun time, but I missed a lot of simple things, didn't complete all of the problems, made simple syntax errors, and completely fumbled the interview that focused on Java. I left depressed, but feeling like I had been given a very fair chance.
I got a call from a recruiter two days later saying that the interview feedback was "pretty positive" and that he decided to forward it to the Hiring Committee. The following Monday the Hiring Committee gave me a "unanimous thumbs up". Another recruiter emailed me to say she would be contacting my references and my application would go through the Compensation Committee and the Executive Committee. I was given a questionnaire to fill out, asking about past employment details and such. It also asked about any past achievements I may want the Executive Committee to know about. They said I would probably hear something in the next few weeks.
Getting close to the end of the two week period, at 10:30pm, I got the email to "extend me an offer". When I replied to the email, she saw I was still awake so she called me on my cell phone at 11pm to give me the details as soon as possible. And the details were VERY generous, so I did not negotiate.
Overall, it was an awesome experience. Everyone was super nice and polite. The whole thing took two months, but a month of that was me asking for time to prepare. I've heard of cases where they can push it through in two weeks if you re really in a hurry. They kept asking me if I had any time constraint that they needed to work with. Also, yes, I asked, and Larry Page did review and sign off on my final approval. From his own words, he's gotten so good at it that it takes him less than a minute for each one.
I will only give this advice about the actual interview process: If you thought you aced it, you probably missed something. It's not about getting the "right" answer. It is about soooo much more. But, like I said, I don't want to spoil the fun.
================
How to find anagrams in a sentence ?
nswers & Comments (3)
0 of 1 people found this helpful
Sep 15, 2011
by Interview Candidate:
Use Hashmaps with words as key to find anagrams
Helpful Answer?
Yes | No
Inappropriate?
Sep 29, 2011
by Anonymous:
1. prep your lexicon, sort each word of your dictionary, the resort the whole dictionary.
2. all duplicate entries are anagrams, make a list of duplicates.
3. sort each word in your sentence, and check if it exists in your new lexicon. A hashmap is a good way to go, but a binary search will work fine in a pinch.
4. consider building a couple indexes to make the process more robust.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Sep 30, 2011
by Kaustubh:
Hey
Take all alphabet and map with a prime number.
Like A = 2, B=3, C=5, D=7, E=11 etc.
Now read each word in the sentence and each word char by char and make a product of those with mapping prime num.
And store them in a map with key as product.
Each anagram will have same product of prime numbers.
=====================
Maximum contiguous sub sequence sum problem.
Detailed analysis and solution are available on the blog:
http://codercareer.blogspot.com/2011/09/no-03-maximum-sum-of-all-sub-arrays.html
=======================
What is the data structure behind hashmap
array of pointers.
if using open chaining it will be array of pointer to linked lists.
if using close chaining it will be just arrays.
=================================
I've been contacted by their recruiters every 6 months or year for the past 6 or 7 years. Finally I was in the right place in my career to actually interview there, so I agreed.
The first step was a phone interview. The recruiter suggested a whole lot of studying material. I kinda skimmed "Programming Interviews Exposed", but I don't think it really made much of a difference at any point in the interview process. I feel like you either know your CS fundamentals or you don't and reading a book about them at the last minute isn't going to help much. Maybe I'm wrong.
This is my best tip for interviewing!: don't just discount your first answer because you think it's "too obvious"! It very well might be the right answer, and now you'll be lost searching for an even better answer that doesn't exist! If you think it's not right, just say "there might be a better way to do this, but I'm just brainstorming", and then explain what you're thinking. If there's a better way to do it, they'll let you know. I made this mistake twice in my interviews.
First there was a 45 minute phone interview. It was just two questions, one coding, and one more conceptual. It was pretty straightforward. The coding one was just something basic like implementing a binary search with a few tweaks.
Despite all the scary things people say, I felt like the in-person interview wasn't especially difficult, but I probably just lucked out with the group of interviewers I pulled. My friend told me he knows a ton of really smart people who didn't pass the in-person, so I shouldn't take it personally if I didn't either. That helped me relax and realize I just had to go in there and do my best and see what happened. I wasn't really nervous then and the interview mostly just felt like I was discussing interesting problems with co-workers. I think being relaxed really helped me get the job, so if you can... chill out. :)
Then things got really boring. At this point, it had been six weeks since I first started talking to the recruiter. Within three days, I was told that I'd passed the hiring committee. And after the I didn't get the offer for FOUR AND A HALF MORE WEEKS. That's 2.5 months total. The recruiter was very nice and apologetic about the whole process, but I feel like they need to do something to speed it up. It was a frustrating experience, knowing I'd passed the hiring committee and was probably hired, but then things just kept getting held up for weird reasons passing through all the other processes.
When the offer finally came, however, it was a good offer and I accepted immediately.
===============================
Create a graph class and graph traversal algorithms.
There are a lot of online solutions posted about this.
==============================
write a program to translate alphanumeric phone number to numbers only
nswers & Comments (3)
0 of 1 people found this helpful
Oct 17, 2011
by Interview Candidate:
Actual translation is easy. Store information is a hashmap (key,value) for example (abc, 2), (def,3) ...(wxyz, 9). You can get the information back very easily in O(1) time. Even when you have 20 characters in the alphanumeric string: 1(800)gofedex. It would still be very efficient O(20) etc...But extracting the information you need is somewhat complicated because you can't control what a user enters...lots of cases to consider...not in a 30 minute phone interview.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 21, 2011
by Greg:
Why wouldn't you map ..... ..? it reduces complexity of retrieval.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 26, 2011
by Async:
You're saying you can't come up with a 10 line solution in 30 minutes but want a job at google? Once you came up with the crazy hashmap idea you had already failed the interview .... the solution to every problem is not a hashmap, especially when a simple lookup table will do.
===============================
what happens when you type: google.com in the browser
dns name lookup and caching...
==============================
Write a code to find out if two string words are anagrams
Answers & Comments (3)
Oct 17, 2011
by Interview Candidate:
First way is to use HashMaps (quick but not memory use effective)
Second is to use arrays (memory effective but slower).
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 4, 2011
by Srini:
Sort the characters in the words. Compare them.
Complexity : O(n log n) depending on the sort algorithm.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 12, 2011
by rob:
boolean areAnagrams?( String s1, String s2)
{
int s1Length = s1.length(), s2Length = s2.length();
if(s1Length != s2Length ) return false;
int[] frequencies = new int[128]; //assuming ascii. make a hash table for unicode
for( int i = 0; i < frequencies.length; i++)
{
frequencies[ i ] = 0;
}
for(int i = 0; i < s1Length; i++)
{
frequencies[ (int)s1.charAt(i) ]++;
}//now we have an int array corresponding to letter frequencies
for(int i = 0; i < s2Length; i++)
{
frequencies[ (int)s2.charAt(i) ]--;
}//now, if they are anagrams, all will be zero
for(int = 0; i < s1Length; i++)
{
if( frequencies[ (int)s1.charAt(i) ] )
{//evaluates to true for anything but zero
return false;
}
}
return true;
}
Helpful Answer?
Yes | No
Inappropriate?
}
===========================
Given two numbers m and n, write a method to return the first number r that is divisible by both (e.g., the least common multiple).
A clever way to do this is by using the formulae :
LCM * HCF = m * n
LCM = (m*n)/HCF
there is a simple way to find( with n > m);
HCF(m,n) = HCF (m%n , m )
Helpful Answer?
Yes | No
Inappropriate?
Oct 29, 2011
by Anon:
Create a loop that multiplies m by the loop counter
mod the mulitple of m by n and if the first modulus that is 0 is the least common multiple.
============================
You have a n number of cities. Lets say city 1 has some information that needs to be sent to all other n-1 cities using minimal cost. Cost between each pair of cities is given. any number of cities can transmit the information once they receive the information but the overall total cost should be minimum
Answers & Comments (2)
1 of 5 people found this helpful
Nov 6, 2011
by candidate:
Dijkstra's algorithm
Helpful Answer?
Yes | No
Inappropriate?
4 of 5 people found this helpful
Nov 16, 2011
by Kurtis:
Dijkstra's tells you the shortest path from city 1 to any other city, but instead it is looking for a minimum spanning tree (MST). Prim's and Kruskal's algorithms would work.
=============================
Write a function to modify a singly linked list, appending copies of the first N-1 elements to the end in reverse order. For example, ['A', 'B', 'C', 'D'] becomes ['A', 'B', 'C', 'D', 'C', 'B', 'A'].
Answers & Comments (8)
1 of 2 people found this helpful
Nov 4, 2011
by Using stacks:
Well I would use a stack to hold the N-1 elements. Then pop one by one and attach it to the end of the list !
Helpful Answer?
Yes | No
Inappropriate?
Nov 12, 2011
by Rob:
I would not use stacks because you don't have to.
this would be more memory efficient. remember to think google scale for google interview questions.
char[] appendReverse(char[] in)
{
int n = in.length;
char[] out = new char[n2-1];
for(int i = 0; i < n; i++)
{
out[i] = in[i];
out[n-i] = in[i];
}
return out;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 14, 2011
by Anonymous:
Given that the original question states that we're using a singly-linked list rather than arrays, I think the stack-based solution (proposed by 'Using stacks' above) is the right one.
Helpful Answer?
Yes | No
Inappropriate?
4 of 5 people found this helpful
Nov 19, 2011
by MB:
Actually, you don't have to use stack or any other data structure. What you can do is have to pointers one is pointing the last element (in this case 'D') and the other one is the head of the list. Add the first element at the end of the list. It becomes A', 'B', 'C', 'D' 'A' then move the head pointer next element and add it to after 'D' :A', 'B', 'C', 'D' 'B' 'A'. Finally add 'C'
'D' :A', 'B', 'C', 'D' 'C' 'B' 'A'
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Nov 21, 2011
by mike:
You can do everything on the fly by creating an auxiliary reversed list. Then just append this list to the last element of the original list
struct List {
List * next;
char val;
};
void modify( List * node ) {
if (node == NULL)
return;
List * rev = NULL ;
while (node->next != NULL) {
List * newNode = new List;
newNode->next = rev;
newNode->val = node->val;
rev = newNode;
node = node->next;
}
node->next = rev;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 25, 2011
by Alec:
Followed MB's suggested algorithm. O(1) space required (for two pointers), O(n) runtime (two loops of n):
void modify (Node * node) {
Node * last = node;
while (last->next != NULL) {
last = last->next;
}
Node * curr = node;
while (curr != last) {
Node * duplicate = new Node;
duplicate->key = curr->key;
duplicate->next = last->next;
last->next = duplicate;
curr = curr->next;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 13, 2011
by Bo Hu:
I bet they just want to see your implementation using recursion.
void foo(node *p)
{
if(p->next == 0)
return p;
node * end = foo(p->next);
end->next = p->copy();
return end->next;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 22, 2011
by Anon:
One loop can provide O(n) time and O(2n-1) space.
def modify(root):
s = root
last = node(root.v)
while root.n.n:
root = root.n
n = node(root.v)
n.n = last
last = n
root.n.n = last
return s}}}}}}}
=========================
Given a matrix of 0s and 1s, write code to get all the different ways of getting from a given cell to another, such that you can't walk through any of the cells with 0s in them.
Answers & Comments (3)
Nov 30, 2011
by Steve:
I think you need to use a optimal search algorithm like BFS or A*. An edge is going from a cell to another with one step, such that the next cell is a zero. Aside from that the algorithms are standard.
Helpful Answer?
Yes | No
Inappropriate?
Dec 1, 2011
by NoOne:
struct Point
{
int i;
int j;
Point(int ii, int jj) {i = ii; j = jj;}
};
int mazeSolutions(int **a, int n, int m, Point s, Point d)
{
int **solutions = new int *[n];
for (int i = 0; i < n; ++i)
{
solutions[i] = new int [m];
memset(solutions[i], -1, sizeof(int) * m);
}
solutions[di][dj] = 1;
stack st;
st.push_back(s);
while (!st.empty())
{
Point r = st.top();
if (solutions[r.i][r.j] != -1)
{
st.pop();
}
else
{
int solved = 1;
int c = 0;
if (r.i + 1 < n && a[r.i+1][r.j])
{
if (solutions[r.i+1][r.j] == -1)
{
st.push(Point(r.i+1, r.j));
solved = 0;
}
else
{
c += solutions[r.i+1][r.j];
}
}
if (solved && r.j + 1 < m && a[r.i][r.j + 1])
{
if (solutions[r.i][r.j+1] == -1)
{
st.push(Point(r.i, r.j + 1));
solved = 0;
}
else
{
c += solutions[r.i][r.j+1];
}
}
if (solved)
{
solutions[r.i][r.j] != c;
}
}
}
// need to de-allocate memory.
return solutions[s.i][s.j];
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
Since the question is finding all the paths, use DFS instead of BFS and don't end the search upon finding the first path.
}}}
=====================
Given a set of strings, a number 'n', and a function that takes a string and gives back a score, find the n largest scored strings in the set.
nswers & Comments (5)
0 of 1 people found this helpful
Nov 30, 2011
by Steve:
Use a Max heap (a min heap where the x<=y operation is score(x) >= score(y)). It can be built in O(n) time. Extracting the maximum element (which is the root) take O(log(n)) , and you do it k times.
Anyway the idea is around sorting. There are tons of less efficient way but I am sure there is one or 2 more efficient way.
Helpful Answer?
Yes | No
Inappropriate?
Dec 1, 2011
by Anonymous:
{{{
int score(char *str)
{
int x = 0;
while (*str)
{
x += (int)*str++;
}
return x;
}
int partition(int *scores, char **s, int n)
{
int pivot = scores[0];
char *ps = s[0];
int small = n - 1;
int large = 1;
while (small > large)
{
if (scores[small] < pivot)
{
--small;
}
else if (scores[large] >= pivot)
{
++large;
}
else
{
int temp = scores[small];
scores[small] = scores[large];
scores[large] = temp;
char *st = s[small];
s[small] = s[large];
s[large] = st;
}
}
if (scores[small] < pivot)
{
--small;
}
scores[0] = scores[small];
s[0] = s[small];
scores[small] = pivot;
s[small] = ps;
return small;
}
char ** TopKScorer(char **s, int n, int k)
{
if (n <= k)
{
return s;
}
int *scores = new int [n];
for (int i = 0; i < n; ++i)
{
scores[i] = score(s[i]);
}
int goal = k;
char **cs = s;
int *c_scores = scores;
int length = n;
int current = -1;
while (1)
{
current = partition(c_scores, cs, length);
if (current == goal)
{
break;
}
if (current < goal)
{
goal -= (current + 1);
cs += (current + 1);
c_scores += (current + 1);
length -= (current + 1);
}
else if (current > goal)
{
length = current;
}
}
delete []scores;
return s;
}
}}}
Helpful Answer?
Yes | No
Inappropriate?
Dec 7, 2011
by Allen:
/*return the position of the ith smallest element(index start with 0). scores[index][0=str_key 1=value]*/
public static int quick_select(int[][] scores, int p, int r, int i) {
if(i > r || i < p) return -1;
if (p == r) {
return scores[p][0];
}
int q = partition(scores, p, r);
if (q == i) {
return scores[q][0];
}
if (q > i) /*ith is in the left pile*/ {
return quick_select(scores, p, q - 1, i);
}
return quick_select(scores, q + 1, r, i);
}
/*return the position of the selected pivot*/
private static int partition(int[][] scores, int p, int r) {
int x = scores[r][1];
int q = p;
for (int i = p; i < r; i++) {
if (scores[i][1] < x) {
int[] tmp = {scores[i][0], scores[i][1]};
scores[i][0] = scores[q][0];
scores[i][1] = scores[q][1];
scores[q][0] = tmp[0];
scores[q][1] = tmp[1];
q++;
}
}
int[] tmp = {scores[r][0], scores[r][1]};
scores[r][0] = scores[q][0];
scores[r][1] = scores[q][1];
scores[q][0] = tmp[0];
scores[q][1] = tmp[1];
return q;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 9, 2011
by Anonymous:
Depending on the size of the string set, you have multiple possibilities here.
1. If the number of strings is reasonable and you can store the score for each one of these. Then the method you guys described, by using the idea from QSORT is perfect! :)
Complexity:
Time: O(M)
Space: O(M)
M is the number of strings! Good when M is reasonable as size.
2. If the set size is really big, and also you assume the strings come to you 1 by one, then the most efficient solution that I can see is to implement a Double Ended Priority Queue of maximum size N (Nth element). This can be done by using a Min-Max Heap.
The total complexity will be in this case:
Time: O(M * log (N))
Space: O(N)
M is the number of strings and N the Nth Element we want. Good method when N<=0; index--) {
worseSell[index] = Math.min(worseSell[index+1], ticks[index]);
}
int lose = 0;
for (int index = 0; index < ticks.length; index++) {
lose = Math.max(lose, ticks[index] - worseSell[index]);
}
System.out.println(lose);
}
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Dec 1, 2011
by NoOne:
double WorstSell(double *values, int n)
{
double maxBuySeenSoFar = 0.0;
double minprofit = 0.0;
// in-order lose most. we need to buy high and sell low. we can only sell after buying.
for (int i = 0; i < n; ++i)
{
if (values[i] > maxBuySeenSoFar)
{
maxBuySeenSoFar = values[i];
}
else if (maxBuySeenSoFar - values[i] < minprofit)
{
minprofit = maxBuySeenSoFar - values[i];
}
}
return minprofit;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 7, 2011
by Allen:
Recursive way to solve this in n logn
public static int[] findMaxLost(int[] prices) {
return rFindMaxLost(prices, 0, prices.length-1);
}
private static int[] rFindMaxLost(int[] prices, int p, int r) {
if (p == r) {
int[] ml_pos = new int[2];
ml_pos[0] = p;
ml_pos[1] = p;
return ml_pos;
}
int q = (p + r) / 2;
int[] l_ml_pos = rFindMaxLost(prices, p, q);
int[] r_ml_pos = rFindMaxLost(prices, q + 1, r);
/*find the max_min cross the center point q*/
int[] m_ml_pos = new int[2];
m_ml_pos[0] = findMax(prices, p, q);
m_ml_pos[1] = findMin(prices, q + 1, r);
if ((l_ml_pos[0] - l_ml_pos[1]) >= (m_ml_pos[0] - m_ml_pos[1])
&& (l_ml_pos[0] - l_ml_pos[1]) >= (r_ml_pos[0] - r_ml_pos[1])) {
return l_ml_pos;
} else if ((m_ml_pos[0] - m_ml_pos[1]) >= (r_ml_pos[0] - r_ml_pos[1])) {
return m_ml_pos;
} else {
return r_ml_pos;
}
}
private static int findMax(int[] prices, int p, int q) {
int pos = 0;
for (int i = p + 1; i <= q; i++) {
if (prices[pos] < prices[i]) {
pos = i;
}
}
return pos;
}
private static int findMin(int[] prices, int q, int r) {
int pos = 0;
for (int i = q + 1; i <= r; i++) {
if (prices[pos] > prices[i]) {
pos = i;
}
}
return pos;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 8, 2011
by vinicius:
reader writer pointer soution. O(n)
public class MaxLose {
public static void main(String[] args) {
MaxLose m = new MaxLose();
int[] a = new int[]{10, 3, 20, 10, 12, 5, 20, 7, 5, 3};
int max = m.maxLose(a);
System.out.println(max);
}
private int maxLose(int[] a) {
int b = 0, max = 0;
for (int s = 1; s < a.length; s++) {
if (a[b] <= a[s])
b = s;
else
max = a[b] - a[s] > max ? a[b] - a[s] : max;
}
return max;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 17, 2011
by anonymus:
Most answers here are in correct. Here is the algorithm. You first identify all buy canditaes, and all sell candidates. A buy canditate is: a point which is bigger than everything on its left and also bigger than the next point on its right. A sell candiate is a point that is smaller than everything on its right and also smaller than the point on its left.
Then you match buy canditates to sell candidates, for every buy candidate the matching sell canditate is the first sell candidate on its left. (multiple buy candidates can match multiple sell) After they are matched the pair with maximum difference will give you the max loss. O(n) needed to find candidates, les than O(n) neded to match pairs.
Helpful Answer?
Yes | No
Inappropriate?
Dec 17, 2011
by Anonymous:
Most answers here are in correct. Here is the algorithm. You first identify all buy canditaes, and all sell candidates. A buy canditate is: a point which is bigger than everything on its left and also bigger than the next point on its right. A sell candiate is a point that is smaller than everything on its right and also smaller than the point on its left.
Then you match buy canditates to sell candidates, for every buy candidate the matching sell canditate is the first sell candidate on its right. (multiple buy candidates can match multiple sell) After they are matched the pair with maximum difference will give you the max loss. O(n) needed to find candidates, les than O(n) neded to match pairs.}
==============================
Given two sorted integer arrays, write an algorithm to get back the intersection.
Answers & Comments (5)
Nov 26, 2011
by Interview Candidate:
Should clarify what intersection means, after that it's pretty straightforward
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Dec 1, 2011
by NoOne:
vector SortedIntersection(int *a, int an, int *b, int bn)
{
vector result;
// assuming asscending order.
int *aend = a + an;
int *bend = b + bn;
while (a != aend && b != bend)
{
int candidate = *a;
++a;
while (*b < candidate && b != bend)
{
++b;
}
if (b != bend && candidate == *b)
{
result.push_back(candidate);
++b;
}
}
return result;
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Dec 2, 2011
by dmn:
It can be solved in O(nlogn) . For each number in the 1st array, do a binary search in the second one, if found - try comparing the two subsets.
Helpful Answer?
Yes | No
Inappropriate?
Dec 8, 2011
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
1 of 3 people found this helpful
Jan 3, 2012
by chandra shekhar:
for(int i=0,j=0; i < ar1.length && j < ar2.length;){
if( ar1[i] == ar2[j] )
System.out.println( ar1[i]);
if( ar1[i] < ar2[j])
i++;
else if ( ar1[i] > ar2[j])
j++;
else {
i++; j++;
}
}}
============================
Judge if a Sudoku solution is right.
Answers & Comments (2)
Dec 7, 2011
by Interview Candidate:
I use two loop to do the judgement and the time complexity is O(n^2)
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Dec 19, 2011
by Gabriel:
It can be done in O(n) really easy :).
you need 27 variables (int). And based on the coordinates in the sudoku table you update for each value 3 of these by setting the corresponding bit to 1.
At the end in order to check the validity of the solution, it just needs all those 27 variables to be 111111111(2). If not, then you have no solution!
Implementing is straightforward!
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment
==================
How to find the max number of a shift buffer queue. For instance, there is an array like 5, 6,8,11,1,2, how to find the max number, which is 11 in this example.
Binary search.
Helpful Answer?
Yes | No
Inappropriate?
Dec 16, 2011
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
0 of 1 people found this helpful
Dec 19, 2011
by Gabriel:
Of course you can use binary search! :) Think about it! You just have to know where you are!
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
int[] list = new int[]{5, 6, 8, 11, 1, 2};
int max = list[0];
for(int i = 1; i < list.length; i++)
{
if (i > max)
{
max = i;
}
}
return max;
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
I see a couple of people suggested use binary search to find the max above, In order to do perform binary search, the list needs to be sorted. If the list is already sorted, you don't need a binary search to find the max number since it's located at the end of the list.
Helpful Answer?
Yes | No
Inappropriate?
Jan 15, 2012
by Liron:
int[] arr = new int[]{5,6,8,11,1,2};
int max = arr[0];
for (int i =0; i weigh 2 vs 2 -> if there's balance weigh 1 vs 1.
If there's no balance weigh 1 vs 1 from the lighter side. if there's balance choose the 1 left, else choose lighter.
Best case 2 weighs, worst case 3 weighs.
As for doing it without knowing if it's lighter or heavier:
break 10 to 3,3',3',1
function weigh(grp1, grp2) {
if grp1 is heavier return -1
if grp1 == grp2 return 0
else return 1
}
res1 = weigh(3,3')
res2 = weigh(3,3')
if (res1 == 0 && res2 == 0) choose the '1'
if (res1 == -1 && res2 == -1) newGrp = 3, odd coin is heavier
if (res1 == 1 && res2 == 1) newGrp = 3, odd coin is lighter
if (res1 == 0 && res2 == -1) newGrp = 3', odd coin is lighter
if (res1 == 0 && res2 == 1) newGrp = 3', odd coin is heavier
if (res1 == 1 && res2 == 0) newGrp = 3', odd coin is heavier
if (res1 == 1 && res2 == -1) Not possible (3 lighter than 3' and heavier than 3')
if (res1 == -1 && res2 == 0) newGrp = 3', odd coin is lighter
if (res1 == -1 && res2 == 1) Not possible (3 heavier than 3' and lighter than 3')
newGrp is 3 coins and you know if the odd coin is heavier or lighter.')))'
===================
A Google recruiter called me a few months back about having me apply for a Software Engineer position at their New York office. I was already employed in a good job at the time, so I was in two minds about exploring new opportunities. They set up a meeting for me with one of their engineers to clear any doubts or questions I may have about working at Google. This really helped with my decision to interview there, and I indicated to the recruiter that I would like to go ahead and interview with them. An on-site interview was scheduled within three weeks.
The interviews started at 10:00AM at the Google offices in Manhattan (since I live in the area, I didn't need to travel, etc.), and were over by 3:00PM. There were 1-on-1 interviews by five of their engineers, each lasted about 45 minutes. One hour was set aside for lunch at the Google cafeteria (where all of the food is free and awesome), and one of their engineers was assigned as my "host" at the lunch to answer any questions I may have about life at Google. He also gave me a tour of their offices (which is very cool).
All of the interviews were conducted in an "interview room" at the Google offices, which is a small meeting room consisting of a single (small) round table and a couple of chairs, a whiteboard and writing supplies. The interviewers (promptly) came to the room at their scheduled times and conducted their interviews for their 45 minutes, or until the next interviewer had arrived outside. Each of the interviews consisted of one or two math or algorithm problems. I was expected to first describe my general approach to the solution. After the interviewer was satisfied with the general approach, I was asked to write code on the whiteboard. I could use any programming language of my choice. I chose Java in almost all questions, and it seemed that most of the interviewers did their day-to-day work in C++. In any case, about half of the time was spent in the back and forth with the interviewer in coming up with the general approach to the problem -- I would come up with an approach, and the interviewer would point about certain cases that didn't work (or other conditions that needed to be met). The other half of the time was spent in planning and writing out the code on the whiteboard.
Despite my background in research, none of the questions pertained to my background and experience. The questions were all designed to gauge fundamental problem-solving and algorithms expertise. It seemed like the interview questions were devised completely independently of my resume/background.
Finally, during the last 15 minutes (2:45PM-3:00PM), I had a short "debrief" session with the HR guy, who gave me the opportunity to ask him any final questions I may have had, and to give him a little feedback about my experience that day. Overall it was a good interview experience -- very professional, all interviewers were well-prepared, punctual and respectful.
====================
I was contacted by a recruiter from Google Southern California (Irvine and Santa Monica) through LinkedIn and was asked if I had any interest in applying to Google. I replied yes and then had a phone call with the recruiter (about 40 minutes) to talk about my background and experience, and the recruiter talked about the interview process and answered all my questions. The recruiter was amazingly nice and very easy to talk to. The first thing I had to do was choose an office to apply to. I chose Santa Monica and asked for 2 weeks to study before the first phone interview.
Two weeks later I had the phone interview. I was very nervous but my nerves calmed down as soon as I started talking to the interviewer, he was friendly and the interview felt more like we were a team working on a problem together rather than an interview (to some extent). It was very casual and the problems were interesting. The interviewer gave me a few tips and clues when I got stuck, but overall I felt like I did pretty well.
One week later, the recruiter contacted me to announce I passed the phone interview and was invited to an onsite interview at the Santa Monica office. The onsite interview was scheduled for a week after that (so 2 weeks after the phone interview). I arrived at the building, but they have 3 buildings and I showed up at the wrong one! Way to make a good first impression, I felt so stupid. So if you have an interview there, make sure to follow the directions they give you by email instead of googling "Google Santa Monica" for the location.
The onsite interview consisted of five 45 minutes 1:1 interviews back to back with a lunch with an engineer in the middle. Four of the interviewers were male software engineers in their early 30s, one was older (50s). All of them were nice and friendly and made the experience very pleasant. All but one of the interviewers made me feel like I was already part of the team and that we were just working together on a problem.
The lunch was a little more awkward. The guy was older than me (50s) so we didn't have much in common (I am in my late 20s) and he was very hard to talk with. I had some questions and conversation topics ready to make sure the lunch would go smoothly, but I ran through all my questions in about 10 minutes because he only answered with "yes", "no", or a few words. He never asked me anything or made any effort to keep the conversation going. You could tell he was a nice guy, nothing wrong with him, just not a talker. Seems like a weird choice for a interviewee lunch, the whole thing felt like an uphill battle against awkward silence. The lunch was probably the most stressful part of the whole interview day!
At the end of the day, I left the onsite interview feeling confident and happy. The problems had all been interesting and I really did enjoy most of the interviewers. One week later I received an email from the recruiter saying I was not selected for the job. I think I did pretty well, I guess I was not quite quick enough with my answers.
============================
merge sort
===========================
implement dijkstras algorithm
===========================
Write a function to convert a collection of strings into a single string and a function to convert it back.
============================
Given a bitmap of open and closed cells, where you can traverse through open cells but not closed ones and a set of origin points on the bitmap, write a program to find the shortest path to every reachable open cell from any of the origin points.
===================================
how would you validate an xml?
===================================
you have a file which contains no. from 100 to 999999999, but some nos. are missing. how would you find the missing nos.? - loading the whole file or keeping the file open for long time isn't desirable.
Answers & Comments (5)
0 of 2 people found this helpful
Aug 2, 2011
by Anonymous:
First I would ask if the numbers in the file are sorted, if yes a thread pool might be a good idea with indexes seeking at different position in the file depending on the worker thread. Since we do not want to load the all file limiting the number of worker thread with a partition of the file and each returning the missing value I think would work, suggestions ?
If the numbers are not sorted then it is a all different story ! I would use the same technique but first I would use multiple Thread or process to sort the file (maybe merge sort since it would work well in parallel because of its divide and conquer methodology) and then apply the above method. just some thought...
Helpful Answer?
Yes | No
Inappropriate?
Aug 4, 2011
by Alex:
Just use a hash, where keys are numbers. Then iterate through the sorted list of keys and push the missing ones into another list.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 11, 2011
by Anonymous:
The number are from 100 - (1 billion -1). If we use a bitset then we would need 1 billion bits = 125 MB. Assuming it'll fit in given memory we can do a 1 pass on the file and in the end just print out the cleared(0) bits of bitset starting from index 99 (100th bit).
Helpful Answer?
Yes | No
Inappropriate?
Sep 14, 2011
by bigo:
As it is clear requirement that file should not be loaded/open for long time. I think reading file in chunk and as alex also mention, having hash-map is faster solution then just using plan bit-set. Run-time complexity to set individual bit in bit-set based on number read from file is MORE than hash, which gives near O(1) complexity, but yes space complexity with hash is HIGH (could be "125MB + 125*8 MB" or 16*125MB)).
Helpful Answer?
Yes | No
Inappropriate?
Sep 14, 2011
by bigO:
mistake: space complexity seems to be (32*125MB + 8*125MB). Pls correct me if you find problem or have any better solution
=============================
u have a thick client application i.e. swings. two users are working on the app. one of them wants to update name field where as the other one wants to update company name.until the users are trying to update different field , they should be allowed to do that . when both are trying to modify the same field, one of them should be notified and the updated value should appear.
version number pattern
============================
Find the largest 100 numbers out of a list of a trillion unsorted numbers
Use a heap to hold the 100 largest numbers so far. If the new number is larger than the heap top (the smallest number in the heap) pop it out and add the new number.
The worst case complexity is O(N * log(100)). Hence log(100) is a small constant (7) the complexity should be good enough.
===========================
Implement a stack that pops out the most frequently added item.
Answers & Comments (2)
Jul 10, 2011
by Anonymous:
You could have a combination of two heaps: one indexed by value, and the other indexed by frequency of addition. Or a hash table and a heap, respectively. It depends on the applications and the balance between memory and processing time resources.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by Noel C.:
An additional comment: Nodes in the hash table and the heap must be shared (to save memory, and for convenience). Which means nodes should have links not only to their children, but their parents as well, so that rotations on the heap can be performed by lookup in the hashtable.
=========================
Write a function to perform incremental search
Answers & Comments (1)
Jul 10, 2011
by Noel C.:
You can use a trie that keeps track of frequencies in each node. When the user begins typing, you've selected one branch of the trie. The trick comes in selecting the branches, or leaves, with the most common occurrences.
A simple way to do this would be to do a traversal of the tree based on frequency at each level of the tree. You could do this with a linear search, or you could generate a max-heap for children at each level of the tree on-the-fly.
====================
Write a function to caculate the angle between hour and minute hand on a clock.
Just make sure u take account of the angle of hour hand
Helpful Answer?
Yes | No
Inappropriate?
Jul 12, 2011
by Oz:
public class Clock {
/** * @param args */
public static void main(String[] args) { System.out.println(getAngle(2,11));
}
public static double getAngle(int hours, int mins) {
System.out.println(hours * 30.0 + 30.0*mins/60.0);
System.out.println(mins*360/60);
double angle = Math.abs((hours * 30 + 30.0*mins/60.0) - (mins*360.0/60.0));
return angle; }
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2011
by anonymous:
Just few thoughts on interview process:
- why the interviewer attacks that way at beginning?
- when u know the answer, i think it's sort of honesty to say you had read this question before; then the interviewer might ask different ques, or he might ask to see how do u code it
- finally, why do you said "Received and Declined Offer", when you failed 2nd phone screen. No offense, just ask for correction.
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2011
by OP:
Quick answers
1. I have no idea why.
2. I didn't see the question before but I solved it too quickly and he accused me.
3. Oops, this needs to be corrected.
Helpful Answer?
Yes | No
Inappropriate?
Jul 14, 2011
by Hasan Diwan:
Oz,
Your code has some bugs... the corrected code is below:
public class Clock {
public static void main(String[] args) {
System.err.println(getAngle(Integer.parseInt(args[0]),Integer.parseInt(args[1])));
}
public static double getAngle(int hours, int mins) {
double angle = Math.abs((hours * (360.0/12.0)) - ((60 - mins) / 5.0 * (360.0/12.0)));
return angle % 360.0;
}
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Oct 12, 2011
by bensegar:
Sorry Hasan,
But I still don't think your code is correct. For example, if the time was 3:15, the angle should be 0 rather than 180 [ the output your code suggests. Similarly, if the time was 3:45, the angle should be 180 rather than 0 [ the output your code suggests. Why? because the question is the angle between the hour and the minute hand. I will post my solution soon. Its alot more complicated than people think!
Helpful Answer?
Yes | No
Inappropriate?
Dec 15, 2011
by anonymous:
Think of it this way:
First, you need to take the hour and do a modulo 12 on it, because there aren't 24 hours on a clock.
Next, every minute, the minute hand moves by 6 degrees (360/60).
Now, the hour hand does a complete rotation in 12 hours, that would be 30 degrees per hour (360 degrees / 12 hours)
Of course, as the minute hand rotates beyond H:00, the hour hand keeps advancing, so we need to account for that. We know it takes 60 minutes for the hour hand to advance by 30 degrees, so the correction is (fraction of an hour) * 30 degrees.
So the angle between 12 o'clock and the position of the hour hand (Ha) is:
Hour = Hour % 12 -> handle values past noon
Ha = 30*Hour -> position of the hour hand without correction
Ha = Ha + (Minute / 60 * 30 degrees) -> correction for the position of the hour hand
And the angle between noon and the minute hand (Ma) is:
Ma = 360 degrees / 60 minutes * Minute
And so the angle between the two hands is:
Abs(Ha - Ma)
For instance, for 14h20:
Hour = 14 % 12 = 2
Ha = 30 * 2 = 60 (uncorrected)
Ha = Ha + (20 / 60 * 30) = 70°
Ma = 360 / 60 * 20 = 120°
Angle between the two = 50°
Whenever you have a problem like this one, try to draw it on the board, and pick easy values, for instance 6:30, which is obviously not 0°, but half of the angle that represents 5 minutes, and you'll end up figuring it out pretty quickly.]]
====================================
Given an unsorted array of integers, find first two numbers in the array that equal a given sum.
Answers & Comments (5)
1 of 1 people found this helpful
Jul 1, 2011
by Interview Candidate:
Gave a O(n^2) solution by comparing each number to every other number, was asked to improve it.
Build a binary tree out of the array, do a traversal of the tree, and use the fact SUM = A + B, where A is the node you are currently visiting. Do a binary search of B. Was asked to come up with a O(N) solution.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 6, 2011
by kaustubh:
Sort the array. O(nlogn)
take two pointer at head( index 0 ) and tail (index array.length-1)
while (head sum)
tail--
else
print head and tail
}
Helpful Answer?
Yes | No
Inappropriate?
7 of 7 people found this helpful
Jul 6, 2011
by René:
The question is ill-posed. What does 'the first two numbers" mean? Suppose that the numbers at indices 1 and 100 add up to the given sum, as well as the numbers at indices 2 and 5, as well as those at indices 3 and 4. Which one of these three pairs constitute "the first two numbers"?
Finding a valid pair can be done in linear time with hashing: (1) hash al the numbers, together with their index in the array, into a hashmap (2) for every insertion of a number n, do a lookup of (sum - n) to check if that value is in the hashmap too. If so, you have found your pair.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 14, 2011
by Tom:
Here you go, an excuse for me to play a bit with Ruby and an excuse for you to learn it:
def find2sum(array,desired_sum)
the_hash=Hash.new
i=0
array.each do |elt|
complement = desired_sum-elt
lookup = the_hash[complement]
if (lookup == nil)
the_hash[elt]=i
else
#puts "soln found, complement=#{complement} at index=#{lookup}, with #{elt} at #{i}"
return [lookup,i]
end
i=i+1
end
#puts "soln not found!"
return[-1,-1]
end
puts find2sum([39,5,15,3,7,9,16,30,23],30)
Helpful Answer?
Yes | No
Inappropriate?
Aug 3, 2011
by bt:
Ok im on a tablet so i ll keep it short.
make an array up to sum/2.
Scan thru the list.
If u find int represented by array or its counter part, mark the the space.
Eg 2+5 equals 7
if 2 or 5 comes along put that in 2.
Now do that until u bump into 5 or other number before. U know?
its easy just think bout it.
Helpful Answer?
Yes | No
Inappropriate?
=======================
Given an unsorted array of integers, find first two numbers in the array that equal a given sum.
Answers & Comments (5)
1 of 1 people found this helpful
Jul 1, 2011
by Interview Candidate:
Gave a O(n^2) solution by comparing each number to every other number, was asked to improve it.
Build a binary tree out of the array, do a traversal of the tree, and use the fact SUM = A + B, where A is the node you are currently visiting. Do a binary search of B. Was asked to come up with a O(N) solution.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 6, 2011
by kaustubh:
Sort the array. O(nlogn)
take two pointer at head( index 0 ) and tail (index array.length-1)
while (head sum)
tail--
else
print head and tail
}
Helpful Answer?
Yes | No
Inappropriate?
7 of 7 people found this helpful
Jul 6, 2011
by René:
The question is ill-posed. What does 'the first two numbers" mean? Suppose that the numbers at indices 1 and 100 add up to the given sum, as well as the numbers at indices 2 and 5, as well as those at indices 3 and 4. Which one of these three pairs constitute "the first two numbers"?
Finding a valid pair can be done in linear time with hashing: (1) hash al the numbers, together with their index in the array, into a hashmap (2) for every insertion of a number n, do a lookup of (sum - n) to check if that value is in the hashmap too. If so, you have found your pair.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 14, 2011
by Tom:
Here you go, an excuse for me to play a bit with Ruby and an excuse for you to learn it:
def find2sum(array,desired_sum)
the_hash=Hash.new
i=0
array.each do |elt|
complement = desired_sum-elt
lookup = the_hash[complement]
if (lookup == nil)
the_hash[elt]=i
else
#puts "soln found, complement=#{complement} at index=#{lookup}, with #{elt} at #{i}"
return [lookup,i]
end
i=i+1
end
#puts "soln not found!"
return[-1,-1]
end
puts find2sum([39,5,15,3,7,9,16,30,23],30)
Helpful Answer?
Yes | No
Inappropriate?
Aug 3, 2011
by bt:
Ok im on a tablet so i ll keep it short.
make an array up to sum/2.
Scan thru the list.
If u find int represented by array or its counter part, mark the the space.
Eg 2+5 equals 7
if 2 or 5 comes along put that in 2.
Now do that until u bump into 5 or other number before. U know?
its easy just think bout it.
Helpful Answer?
Yes | No
Inappropriate?
'
================
C++ versus Java. Reverse a singly lined list.
reverse(Node n1, Node n2) {
Node newHead;
if (n2.next != null) newHead=reverse(n2, n2.next);
else newHead = n2;
n2.next = n1;
}
Helpful Answer?
Yes | No
Inappropriate?
Oct 8, 2011
by D:
to J, good stuff. remember to return newHead
=====================
How to add a counter to www.google.com to track the billionth user.
Answers & Comments (3)
Jun 25, 2011
by Interview Candidate:
The idea is to have a distributed local counters and a good way to combine the local counters into one global counter. Another key property is to combine the results of local counters asynchronously in order not to slow down the search time.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by Anonymous:
Each server should keep track of the total number of users, and perform "edits" to this number.
At a specified time interval, servers should synchronize their counter by transmitted their aggregated "edits" to the total number of users.
"Edits" are simply how much to add to the sum.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by Noel C.:
Each server should keep track of the total number of users, and perform "edits" to this number.
At a specified time interval, servers should synchronize their counter by transmitted their aggregated "edits" to the total number of users.
"Edits" are simply how much to add to the sum.
==================
You have a 64bit interger counter set to 0. How long it will take to overflow the counter given that you are incrementing it at 4Ghz speed.
Answers & Comments (6)
0 of 2 people found this helpful
Jun 28, 2011
by grad stud:
60 years
Helpful Answer?
Yes | No
Inappropriate?
2 of 3 people found this helpful
Jul 2, 2011
by Praveen:
If we were to keep it simple and not consider every increment to be a load, increment, store then we basically need 2^64 increments to make the long overflow.
4GHz means 4*(2^30) instructions per second.. which is 2^32
effectively it is (2^64)/(2^32) = 2^32 seconds.. or roughly 136years.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 18, 2011
by Parag:
total increments before overflow (tibo) = 2^64
increment speed(is) = 1 second / (4*10^9) increments | 4Ghz = 1x10^9 Hz
total seconds (ts) = 2^64 increments * (1 second /(4*10^9) increments)
ts = 4.611 * 10^9 seconds
total years = ts/(60*60*24*52) = 146.2 years
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 18, 2011
by correction(s) to above:
total years = ts/(60*60*24*7*52) = 146.2 years
and 4ghz = 4*10^9 Hz
Helpful Answer?
Yes | No
Inappropriate?
Jul 22, 2011
by Anonymous:
Please read the question carefully, it says counter is incrementing at the rate of 4GHz.
i.e, 4GB per second. Not incrementing every second.
So after elapsing first second, counter is at 4GB. After elapsing 2nd second, it is 4 + 4 = 8GB.
64 bit integer is, 2^64 = 2^32 * 2^32. Which is roughly 4GB * 4GB = 16GB.
So per second counter incremented to 4GB, so for 16GB it takes 4 seconds.
Helpful Answer?
Yes | No
Inappropriate?
Sep 17, 2011
by donutello:
Anonymous: 4GB * 4GB != 16 GB. You're ignoring the units!
To be accurate, the answer is 4G * 4G = 16 G^2 = 16 * 2^30 * 2^30.
======================
Comparisons of trees and hash tables. What are the tradeoffs of using one versus another.
=============================
Quickly estimate 2^64 without using a pen/papar.
=============================
Answers & Comments (5)
0 of 1 people found this helpful
Jun 27, 2011
by justaguye:
Well, 2^8 is 256 and 2^16 is that squared, which should have 5 digits..
If I square it again, I should have double those digits, and again if I square it again..
So I'm looking for something in the neighborhood of 1x10^20, or approx
10,000,000,000,000,000,000.
Calculator says: 18,446,744,073,709,551,616--> I'm in the ballpark.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Jun 29, 2011
by Kaustubh:
2^10=1024 ~10^3
2^64=(2^10)^6 * 2^4
=> (10^3)^6*16
=> 10^18*16
=> 1.6 * 10 ^ 19
= 16,000,000,000,000,000,000
Calculator says: 18,446,744,073,709,551,616
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 1, 2011
by Saurabh:
2 ^ 10 = 1.024 * (10^3)
2 ^ 60 = (1.024 ^ 6) * (10 ^ 18)
2 ^ 64 = (16 * (1.024 ^ 6) * (10 ^ 18) )
All, we need to solve is 1.024 ^ 6. using binomial expansion, ignoring the smaller terms we get : (1 + 0.024) ^ 6 = 1 + 6 * 0.024 = 1.144 = 1.15 (approx)
Hence the answer is : (16 * 1.15) * (10 ^ 18) = 18.4 * (10 ^ 18)
It is much closer to the actual answer and very fast to calculate.
Helpful Answer?
Yes | No
Inappropriate?
Aug 3, 2011
by bt:
Donno if this is to test witt and prepness..
I would say 18,446,.... so on
He ll ask how i get that..
Say "calculator"
The question was about without using pen/paper
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 25, 2011
by m:
2^32 ~= 4 bil
2^64 = 4bil * 4 bil
= 16 bil bil
each bil 9 0's, so 16 with 18 0's.
======================
This is not a question from the day but gives you an idea of what to expect. Given an array of numbers and another number, work out whether the array of numbers can be manipulated using standard mathematical techniques to equal the other number given. e.g. given 5 and 10, can you make 50? 5 * 10 = 50, so yes.
Answers & Comments (3)
2 of 2 people found this helpful
Oct 7, 2010
by vsp:
The "standard mathematical techniques" is a meaningless term. Perhaps "addition, subtraction, multiplication, division, and parenthesis"? Perhaps, "you can use each array element just once"? Or "create the shortest mathematical expression evaluating to some number K" - that would also make sense, since it would eliminate bohring solutions like "5/5 + 5/5 + ... + 5/5 = 1000". Knowing Google people, I doubt you've given an exact problem statement.
Helpful Answer?
Yes | No
Inappropriate?
Oct 7, 2010
by xerox:
You are correct that it is not a particularly helpful term, but you have managed to figure out what was meant by it and that each number can only be used once. It was a very hastily thrown together question that summarizes what sort of logic puzzles can be given by Google, not an actual question given by them, as stated.
So to clarify - you can only use one number once, and you can only use addition, subtraction, multiplication and division.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 15, 2010
by Vijay:
I can only think of brute force. But that would mean there will be n! permutations of the numbers (or if you can use less than n numbers, sigma {(n-i)!}).
between these sequences, we can have 4 possible operators, so we have 4^n possible sequences of operators.
Total time = O(n! * 4^n). Any n > 16 will overflow even a 64-bit long long variable.
Helpful Answer?
Yes | No
Inappropriate?
===========================
Partition an array in such way zeros to be moved on the left side of the array, other numbers on the right side of the array. Extra storage not allowed, only in-place.
Answers & Comments (6)
Oct 7, 2010
by vsp:
int j = 0;
for (int i = 0; i < vec.length; ++i) {
if (vec[i] == 0 && i > j) {
vec[i] = vec[j];
vec[j++] = 0;
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 7, 2010
by vsp:
correction: the loop body should be:
if (vec[i] == 0) {
if (i > j) {
vec[i] = vec[j];
vec[j] = 0;
}
j++;
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 7, 2010
by int:
I progress a zero pointer from right to left, and a non-zero pointer from left to right, then swap them until they meet in the middle.
int j=N-1;
int i=0;
for(i=0; i=0; j--) if(array[j]==0) break; //j points to right-most zero
while(j>i){
swap(i,j)
for(; i=0; j--) if(array[j]==0) break;
}
Helpful Answer?
Yes | No
Inappropriate?
Oct 18, 2010
by for:
exit=0;
i=0;
j=0;
while((exit==0)&&(i<=vector.length)) {
swapped=0;
j=i;
if(vector[i]!=0)
while((swapped==0)&&(j<=vector.length)) {
if(vector[j]==0) {
vector[j]=vector[i];
vector[i]=0;
swapped=1;
}
if(j==vector.length)
swapped=exit=1;
j++;
}
i++;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 16, 2010
by Anonymous:
Similar to how partitioning is done in quicksort.
Helpful Answer?
Yes | No
Inappropriate?
Dec 12, 2010
by Anonymous:
Tweaking vsp's imp for readability...it is the optimal on this forum in O(n).
int zeroInsertPosition = 0;
for (int i = 0; i < c; i++)
{
if (vec[i] == 0)
{
if (i != zeroInsertPosition)
{
vec[i] = vec[zeroInsertPosition];
vec[zeroInsertPosition] = 0;
}
zeroInsertPosition++;
}
}
Also change the i= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
private static boolean isPalindrome(String a)
{
return a.endsWith(reverseIt(a));
}
public static void solve(String initial)
{
int[] cost = new int[initial.length()];
int[] position = new int[initial.length()];
cost[0] = 1;
position[0] = -1;
for(int i = 1; i < initial.length(); i++)
{
cost[i] = initial.length();
position[i] = i-1;
for(int j = 0; j < i; j++)
{
if(isPalindrome(initial.substring(j, i + 1)))
{
if(j == 0)
{
cost[i] = 1;
position[i] = -1;
}
else if(cost[i] > cost[j-1] + 1)
{
cost[i] = cost[j-1] + 1;
position[i] = j-1;
}
}
}
}
Stack stack = new Stack();
int pos1 = position[initial.length() - 1];
int pos2 = initial.length() - 1;
while(pos1 >= 0)
{
stack.add(initial.substring(pos1+1,pos2+1));
pos2 = pos1;
pos1 = position[pos2];
}
if(pos1 == -1)
{
stack.add(initial.substring(0,pos2+1));
}
while(!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
public static void main(String[] args) {
solve("ABAABABA");
solve("AAAAAAAAAAB");
solve("ABC");
solve("ABAC");
solve("CABA");
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Feb 25, 2011
by Anonymous:
Here is a simple way to build the set of all palindromes in O(n^2) time.
What you do is you take every character (or two adjacent characters) and find all palindromes such that your character is in the middle. It's pretty easy to see that you can do this in O(n) time to find all palindromes with a given character in the middle, because if you have a palindrome then knocking a character off each end leaves you with another palindrome. Therefore it takes O(n^2) to find them all.
Then, as others have mentioned, you can use dynamic programming to find the best covering.
Helpful Answer?
Yes | No
Inappropriate?
)))
================
I got an initial indication of interest e-mail from a recruiter at Google who had my resume on file from a while back. He asked me a couple standard non-technical questions, and then set up a phone interview.
My phone interview consisted of a couple sanity checks (e.g. "What does static mean in C++?") followed by one very tough technical question which lasted the entire interview.
That went well, so they brought me onsite, where I had 5 technical interviews, all 45 minutes each. They always seemed to run up to the limit/a couple minutes over, I think they should consider making the time longer. In the middle of the day I had lunch with an engineer for an hour who fielded whatever questions I had, but they don't provide feedback, so feel free to ask anything.
Each interview pretty much followed the same format -- they presented the question, asked me to go, I would say something like "Well the naive way to do it is ___, but let's look for the better way", but they would ask me to code the naive way anyway (usually). Then they would ask me how inefficient it is, how to improve it, and then ask me to code that. They wanted code (or pseudo code, if there were only a couple minutes left) in almost all situations -- they write it all down or just take a picture. At the end, each one turns it around to see if you have any questions for them.
My recruiter gave me status updates along the way, letting know what my status was, and it took about 3 weeks to hear back.
People: a couple interviewers seemed grumpy, like they didn't want to be there -- I didn't like that. But everybody, including the grumps, were really excited about their job, and really liked all their benefits/perks/freedom/situation in general.
Advice: the interviews are tough! Expect at least a couple months to review if you're rusty; study lots of books like CLRS; do a **lot** of practice problems (TopCoder is a very good resource); practice problems on the white board (I found this especially useful); bring in your own skinny white board markers -- the ones in the interview rooms are fat and hard to write with; be prepared to talk through your solution; bring several questions for all the interviewers (even just "how do you like your job?"); for things like quicksort/mergesort/merge/binary search, you should be able to write that in your sleep while you're drunk. Finally: google for "google interview questions". I was only asked one question that I had seen online, but preparing for the others helped me for the new ones I got.
============================
Given a set of integers find if two elements sum to a given value.
Answers & Comments (3)
0 of 1 people found this helpful
Apr 24, 2010
by Shards:
Since this is a set, solution is straightforward. Push all members to a hashtable. Now, we go through the set again and for each member k find whether sum - k is in the hashtable, if it is, then we have a match. Be careful to make sure that k != sum - k though, that is *not* a match.
Helpful Answer?
Yes | No
Inappropriate?
2 of 3 people found this helpful
Apr 28, 2010
by Anonymous:
You don't need a hashtable. Iterate through the set. For each element, if (sum - k) != k and (sum - k) is an element in the set, then return true. Return false otherwise.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Apr 29, 2010
by Shards:
Certainly, if the set given is already a hash_set. This is something that you can (and should) clarify with the interviewer. Typically they'll mean a sequence of distinct numbers with no further assumption.
===============================
Given a picture of a skip list data structure, implement the algorithm to maintain skip lists (add, search, delete).
================================
what's wrong with the following code : T accumulate ( vector in) { T total = in[0]; for (int i =0; i < in.length() ; i++) { total = total + in[i]; } return T }
Answers & Comments (6)
2 of 2 people found this helpful
Jul 29, 2010
by Interview Candidate:
1. The big bug in[0] is accumulated twice.
2. empty vector ...
The solution or 1 and 2 : total = T();
3. input vector need to be const &
4. Better return the value as a &T in the argument list rather than as the ret value T can also be a string for example ! or some class that is expensive to copy. I.e. void accumulate(const vector & , T &total)
5. For string this function sucks and better a template specialization for string is preferred.
6 (? ) total += in[j] . Much more effective if T is not primitive type . On the other hand should ask if += is defined for the required T .
7. Not a big thing but passing in const_forward_iterators is nicer (This one I thought only afterward )
8. I think the most important thing, after doing 1-7 the function will be exactly as the accumulate from algorithm.h ( as I said I missed few knock outs in this interview)
Helpful Answer?
Yes | No
Inappropriate?
Sep 9, 2010
by Anonymous:
.size not .length
Helpful Answer?
Yes | No
Inappropriate?
Oct 24, 2010
by Jay:
return T?
Helpful Answer?
Yes | No
Inappropriate?
Oct 25, 2010
by Randell:
Right - should be "return total;", though I'd agree with most of the comments made by the Interview Candidate.
Helpful Answer?
Yes | No
Inappropriate?
Dec 16, 2010
by Anonymous:
Can elements of a Vector be accessed array style...? I thought it was a Iterable Collection.
Helpful Answer?
Yes | No
Inappropriate?
Sep 17, 2011
by donutello:
In addition to what is suggested by the candidate:
- If you are going to hand-write iteration, do it with const_iterators instead of an index into the vector
- Prefer ++i instead of i++. The post-increment operator is defined in terms of the pre-increment operator and is less efficient since a copy of the original value needs to be made and returned
Re: #6. If += is not defined, define it! operator+ should be defined in terms of operator+=.
Helpful Answer?
Yes | No
Inappropriate?
=================
Intersection of two numerical arrays
Answers & Comments (6)
0 of 6 people found this helpful
Apr 24, 2010
by Interview Candidate:
Algorithm and pseudo code
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 19, 2010
by Steve M:
* assuming b[] is the longer array
quick sort b[]
for all items from a[]
binary search this item in b[]
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 19, 2010
by Steve M:
for above..
O(n log n) + O(n) * O(log n)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 20, 2010
by Roger:
I have a O(n) algorithm:
1. Iterate over all the elements of first array a[] and build a dictionary mapping the element value to the index - O(n)
2. Now iterate over all the elements of the second array b[] and for each element that is already present in the dictionary, move the element to a different array that maintains the intersection elements - O(n)
3. Hence the overall complexity is O(n) in time and O(n) for the dictionary and the array to maintain the intersection elements.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 27, 2010
by Anonymous:
given arrays of lengths n and m. A simple solution is to sort array n in O(n lg n) and for each item in array m, look for it in sorted n, O(m lg n). So total time = O((m+n)lg n), let array n be the short array. I feel there is a much quicker solution, maybe O(n+m) if we assume integers.
Helpful Answer?
Yes | No
Inappropriate?
Sep 17, 2011
by donutello:
Two possible approaches:
1. Sort both arrays and then walk over each array simultaneously until you find all the common entries. This is O(n*logn) to do the sort and then walking over the items is O(n).
2. Walk over first array and insert each item into a hash table. Then search for each item in the hash table. This is O(n) time and O(n) space.
If you're doing this a lot with the same sets of data, both algorithms allow you to do the expensive step once for each array and then find the common items in linear time.
================
Hardest things to unit test
Answers & Comments (3)
Jul 19, 2010
by Steve M:
Singletons in a runtime environment.
Helpful Answer?
Yes | No
Inappropriate?
Aug 27, 2010
by Anonymous:
my first reaction is "people behavior"
Helpful Answer?
Yes | No
Inappropriate?
Sep 7, 2010
by vic:
multi-threaded code :)
Helpful Answer?
Yes | No
Inappropriate?
======================
Difference between arithmetic and logical shift
Answers & Comments (2)
1 of 1 people found this helpful
Apr 7, 2010
by Interview Candidate:
I think..... arithmetic right shift will shift in the sign bit while preserving the sign bit .. Logical shift always shifts in zeros no matter in which direction you do the shift
Helpful Answer?
Yes | No
Inappropriate?
Jul 22, 2010
by Andi Mullaraj:
That's correct. Moreover, in Java the arithmetic right shift operator is >> whereas the logical right shift is >>>
===========
talk about 1s complement and 2s complement representation
1s complement is the inverse of all bits.
2s complement is used to represent negative values by offsetting 1s complement by 1 so that we avoid the value -0.
==========
Write algorithm to compute a Log to the base 2 of a number (integral results no need for floating point). Solution should not assume a particular size of integer
Answers & Comments (4)
1 of 2 people found this helpful
Apr 14, 2010
by user:
result = 0
while(number != 1)
{
result++
number>>1
}
return result
Helpful Answer?
Yes | No
Inappropriate?
Jun 14, 2010
by Anonymous:
// this c routine SHOULD compile and run ok regardless of sizeof (int)
// It returns -1 for i<=0 as an error flag. otherwise it returns (int) log2(i)
int l(int i){for(int j=0,k=1;k<=i;k<<=1,j++);return(j-1);}
Helpful Answer?
Yes | No
Inappropriate?
Jun 14, 2010
by Anonymous:
There are at least 2 bugs in the first proposed answer:
"number >> 1" should be "number >>=1"
Also, if initial value of number is 0 or less, this routine will infinite loop
Likewise, the second solution only works for inputs less than 1/2 of maxint
But I like it because it is concise :)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 22, 2010
by Andi Mullaraj:
public class Test2 {
public static void main(String[] args) {
System.out.println(new Test2().log(31)); // prints 4
}
int log(int n) throws RuntimeException {
if (n <= 0) {
throw new RuntimeException();
}
int result = -1;
while (n > 0) {
result++;
n >>= 1;
}
return result;
}
}}}}
==============
- maximum sum of any continuous subsequence in an array of signed integers whats the complexity. - program to compute fibonacci sequence..standard recursive and more efficent iterative one.. algorithmic complexity of both.
public class Test3 {
public static void main(String[] args) {
System.out.println(new Test3().max(new int[] { 2, 3, -5, 6 }));
}
int max(int[] array) {
int result = array[0];
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
if (sum > result) {
result = sum;
} else if (sum < 0) {
sum = 0;
}
}
return result;
}
}
Complexity is O(n)}
====================
How many golf balls can fit in a school bus?
Answers & Comments (10)
2 of 5 people found this helpful
Jan 11, 2010
by Naing:
48 passenger + 1 driver
therefore 49 * 2 = 98
Helpful Answer?
Yes | No
Inappropriate?
Jan 11, 2010
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
2 of 2 people found this helpful
Jan 13, 2010
by Anonymous:
Depends how big the school bus is, for simplicity, lets say its the small bus that can fit 20 + 1 people. You have to take account of the empty space as well, therefore a person could be sitting in the middle line and three more in the front so we have around 30 people making a full squished bus.
The average size of a golf ball is around 3 cm in diameter. The height of the bus is usually 200 cm, the width of an average person is usually 50 cm. The depth of the seat is about 70 cm You can calculate the volume of that cubic form to be 50 x 70 x 200 x 3 x 30 = the number of golf balls in average.
Helpful Answer?
Yes | No
Inappropriate?
2 of 4 people found this helpful
May 11, 2010
by Anonymous:
not enough to shove up your a@@
Helpful Answer?
Yes | No
Inappropriate?
Jul 30, 2010
by Jehova:
Nobody need to actually put golf balls in a school buss , nobody care if the number is 61,000,000 or whatever .Nobody in Google cares how good are you in giving estimates to the size of a buss.
The answer is
bussWidth*bussHight*bussLength / (ball/Diameter ^ 3 * sin (60) * sin(60) ^2 ) .
This answer depends on the size of the school buss, different busses yield different answer. The sin(60) are since its gold balls and not cubics.
Helpful Answer?
Yes | No
Inappropriate?
Sep 10, 2010
by Anonymous:
As Jehova put it. This tests your problem-solving stance being seeing that you leave the right things as variables. The question is really about trigonometry and understanding how tightly you can pack spheres. In other words, you need to figure the effective volume of each golf ball.
To do so, first consider a single plane of balls, and a single row from it. If the ball radius is r, the width required for each ball is 2r.
Now consider the depth required by each row. Since the rows will be "staved off" from each other, each row requires somewhat less than 2r for its depth. In fact, each requires r * tan 60, or about 1.73 * r. To see why, notice that each adjacent group of three spheres forms a triangle, and, because of the symmetry of the situation, their centers form an equilateral triangle. Thus each of its angles it 60 degrees. Since tan(theta) = opposite / adjacent, we have that tan(60) = depth / radius, or depth = radius * tan(60).
Finally, consider the height require by each plane of balls. Take the three adjacent balls from the first plane and imagine adding a forth ball above them in the center. The centers of the four balls now form a tetrahedron (just a pyramid with a triangular base). We need to find the height from the center of the base of the tetrahedron to its top vertex. Looking at a diagram, one can see that the distance to the center of the base from one of the base vertices is found by cos(theta) = radius / hypotenuse, or cos(30) = r / distance, meaning distance = r / cos(30), or about 1.15 * r. If you create a line going from the base vertex to the base center, it then becomes clear that this line forms a vertical isosceles right triangle with the height line. In other words, the distance we just found is equal to the height of the tetrahedron.
Bring it all together, we have that the effective volume of each ball is:
effectiveWidth * effectiveDepth * effectiveHeight =
2r * r tan 60 * r / cos 30.
So finally, the number of balls is the bus volume divided by each ball's effective volume.
Helpful Answer?
Yes | No
Inappropriate?
Sep 10, 2010
by Anonymous:
"If you create a line going from the base vertex to the base center, it then becomes clear that this line forms a vertical isosceles right triangle with the height line. In other words, the distance we just found is equal to the height of the tetrahedron."
My girlfriend actually figured it out better when I got home. I was wrong saying it was clear that the internal vertical triangle was isosceles. It's not actually isosceles. The way to figure out the height of the tetrahedrom is actually to note that the hypotenuse is 2r and use the Pathagorean(sp?) Theorem: height^2 = (2r)^2 + (r / cos 30)^2, and solve for height. Sorry!
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jan 19, 2011
by Anonymous:
A school bus of golf balls.
Helpful Answer?
Yes | No
Inappropriate?
Feb 13, 2011
by farkyou:
@Anonymous commenter on 9/10/2011: you are completely ignoring the effective volume inside a bus. You would have to subtract volume taken up by seats as well as any people inside the bus.
Helpful Answer?
Yes | No
Inappropriate?
Aug 25, 2011
by devin:
http://mathworld.wolfram.com/SpherePacking.html
Helpful Answer?
Yes | No
Inappropriate?
=======================================
I was asked a question about the following. If a user types in a n digit number on the telephone, how do you write a function to deduce if the number constitutes a valid word. For example, if the user enters 123, then can a valid word be made out of (a/b/c) + (d/e/f) + (g/h/i)
Answers & Comments (3)
2 of 3 people found this helpful
Jan 7, 2010
by Justin Beal:
The easiest way to do this is to create a "keypad-spelling" mapping to a proper dictionary ahead of time. For every word in the dictionary, store the English spelling as well as the appropriate number presses (e.g. the entry for "beg" would also store "123"). Then, you simply search the dictionary for the numeric sequence the user input, and return whatever is needed (a boolean, the first matching English string, an array of all matching strings, whatever). There's wiggle room for whatever your constraints are in how the dictionary and lookup are implemented, but this is the best approach I can see.
Doing it without this mapping would be significantly harder. Doing it with no dictionary at all is effectively impossible without more context (how do you know what a "valid word" is without a dictionary?).
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jan 15, 2010
by Raj G:
Comment: What if people want words that are not in the dictionary? Such as names, places, or things? If that's the case then the logic of your explanation is null. I'm not a software engineer or anything but it seems your forgetting that they want you to be able to create any word (valid or otherwise) with "keypad spelling"
Helpful Answer?
Yes | No
Inappropriate?
Mar 4, 2010
by Aaron M:
The simplest way of doing this would be to generate the character permutations possible and pass the results through a dictionary.
e.g.
pad = {}
pad[1] = [' ']
pad[2] = ['a','b','c']
pad[3] = ['d','e','f']
pad[4] = ['g','h','i']
pad[5] = ['j','k','l']
pad[6] = ['m','n','o']
pad[7] = ['p','q','r','s']
pad[8] = ['t','u','v']
pad[9] = ['w','x','y','z']
pad[0] = [' ']
def perms(digits):
if len(digits) == 0:
yield []
else:
for padchar in pad[digits[0]]:
for tailitem in perms(digits[1:]):
yield [padchar] + tailitem
for s in perms([2,5,7,9]): print ''.join(s)
Another solution could be to build up a dictionary trie, using the digits instead of the word chars (e.g. cat, bat -> 228).
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this question â Join Now (It's Free) or Sign In
You might also be interested in: Interview Questions, Senior Software Engineer Interview Questions, Google Interview
==================================================
Create a stack of numbers where the maximum number is always known.
Answers & Comments (6)
Jul 13, 2009
by Interview Candidate:
Create a separate stack for the maximums.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 31, 2009
by Dr Zhang:
maintain a sorted stack, the insert would look like
insert(int p,stack s){
stack large;
int top = s.peek();
while(top>s){
large.push(s.pop());
top = s.peek();
}
s.push(p);
while(!large.empty()){
s.push(large.pop());
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 31, 2009
by Dr Zhang:
sorry, typo
while(top>p)
Helpful Answer?
Yes | No
Inappropriate?
Aug 21, 2009
by jobSeeker:
I was asked of this question as well. I not sure how to implment a second stack in a way that the max number is always on top.
Helpful Answer?
Yes | No
Inappropriate?
Aug 21, 2009
by jobSeeker:
I was asked of this question as well. I not sure how to implment a second stack in a way that the max number is always on top.
Helpful Answer?
Yes | No
Inappropriate?
5 of 5 people found this helpful
Aug 21, 2009
by Interview Candidate:
To Job Seeker:
The basic idea is that when a new number is being pushed onto the stack, you need to see if that number is greater than or equal to the current top of the maximums-stack. If it is, you push the number onto maximums-stack as well.
Also, when pop is called, you look to see if the number being popped is equal to the number on the top of the maximums-stack. If it it, pop that stack as well.
===========================
Create a cache with fast look up that only stores the N most recently accessed items.
Answers & Comments (4)
Jul 13, 2009
by Interview Candidate:
Use a hash map and a queue.
Helpful Answer?
Yes | No
Inappropriate?
Jul 18, 2009
by ml:
I think you can do better than hash map and a queue...or just simply it.
Since you're only interested in the N most recently accessed items, an array is suffice. Because N is essentially the index right?
Helpful Answer?
Yes | No
Inappropriate?
Jul 18, 2009
by Anonymous:
To ml:
N was not the index, instead some random key. The combined data structure had the implement the interface:
Object get(String key); and
void put (String key, Object obj);
Besides the array isn't the best choice when you have to take an object out of the array and add it to the front of the queue every time the object is accessed. A double linked list works better. The hash map entries points to an item in the linked list, which then points to the object to be returned. This way you can find the item quickly to move it to the front of the queue.
Helpful Answer?
Yes | No
Inappropriate?
Aug 21, 2010
by Roger:
This answer below has the best solution:
http://stackoverflow.com/questions/1935777/c-design-how-to-cache-most-recent-used
=============================
Given an array of numbers, replace each number with the product of all the numbers in the array except the number itself *without* using division.
Answers & Comments (13)
2 of 3 people found this helpful
Jul 13, 2009
by Interview Candidate:
Create a tree, where the leaf nodes are the initial values in the array.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Jul 23, 2009
by husb:
Given array A[1..n]
create array B[1..n]= {1} // all elements =1 ;
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++ ) {
if (i<>j) B[i] *=A[j];
}
}
A=B;
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 23, 2009
by Interview Candidate:
To husb:
Your answer will work, but it's O(n^2) solution. Can you do better?
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 29, 2009
by Bill:
Am I missing something? It can't be this easy:
given array[0..n]
int total = 0;
for(int i=0; i<=n; i++)
{ total += array[i]; }
for(int i=0; i<=n; i++)
{
array[i] = total-array[i];
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 29, 2009
by Bill:
Ah yes.. I was. The question is PRODUCT, not sum. That will teach me to read the question too fast ;)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 31, 2009
by Dr Zhang:
Create a tree, where the leaf nodes are the initial values in the array. Build the binary tree upwards with parent nodes the value of the PRODUCT of its child nodes. After the tree is built, each leaf node's value is replaced by the product of all the value of the "OTHER" child node on its path to root. The pseudo code is like this
given int array[1...n]
int level_size = n/2;
while(level_size != 1){//build the tree
int new_array[1...level_size];
for ( int i=0; i left = array[i*2]; (and also from child to parent)
new_array[i] -> right = array[i*2+1]
new_array[i] = new_array[i] -> right* new_array[i] -> left; (take the product)
}
array= new_array;
level_size /=2;
}
for(int i=0; iparent;
if( parent->left == node){//find the other node under the parent
brother = parent->right;
}
else{
brother = parent->left;
}
p *= brother;
node = parent;
}
return p;
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 31, 2009
by Dr Zhang:
btw, it's O(n*logn)
Helpful Answer?
Yes | No
Inappropriate?
12 of 13 people found this helpful
Sep 16, 2009
by betterStill:
It seems to me that for any number array[i], you're looking for
PRODUCT(all array[j] where j < i]) * PRODUCT(all array[j] where j > i])
we can simply precompute these "running products" first from left-to-right, then right-to-left, storing the results in arrays. So,
leftProduct[0] = array[0];
for j=1; j < n; j++
leftProduct[j] = leftProduct[j-1]*array[j];
rightProduct[n-1] = array[n];
for j=n-2; j >= 0; j--
rightProduct[j] = rightProduct[j+1]*array[j];
then to get our answer we just overwrite the original array with the desired product
array[0] = rightProduct[1];
array[n-1] = leftProduct[n-2];
for j=1; j < n-1; j++
array[j] = leftProduct[j-1] * rightProduct[j+1]
and clearly this solution is O(n) since we just traversed the data 3 times and did a constant amount of work for each cell.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jan 9, 2011
by Ethelbert:
betterStill, I think you have the answer the interviewer wanted..
But... if the array is google sized, don't we have to worry about overflows?
Helpful Answer?
Yes | No
Inappropriate?
Mar 3, 2011
by dadao:
it looks to me can be done in order n time given the following relation:
product[n] = product[n-1]*array[n-1]/array[n]
for example we have array 2 3 4 5 6
product[0]=3*4*5*6
product[1]=2*4*5*6
array[0] = 2;
array[1]=3
product[1]=product[0]*array[0]/array[1]
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jun 10, 2011
by narya:
Here are my 2 cents to do this in memory without creating temporary arrays. The simple solution , if division was allowed, was multiple all the elements of the array i.e.
tolal = A[0]*A[1]]*....*A[n-1]
now take a loop of array and update element i with A[i] = toal/A[i]
Since division is not allowed we have to simulate it.
If we say X*Y = Z, it means if X is added Y times it is equal to Z e.g.
2*3 = 6, which also means 2+2+2 = 6. This can be used in reverse to find how mach times X is added to get Z. Here is my C solution, which take pointer to array head A[0] and size of array as input
void ArrayMult(int *A, int size)
{
int total= 1;
for(int i=0; i< size; ++i)
total *= A[i];
for(int i=0; i< size; ++i)
{
int temp = total;
int cnt = 0;
while(temp)
{
temp -=A[i];
cnt++;
}
A[i] = cnt;
}
}
Speed in O(n) and space is O(1)
Helpful Answer?
Yes | No
Inappropriate?
Jun 23, 2011
by kiran:
narya trick is good but really useful as it might take more iterations depending on values... eg. 2,3,1000000000000000
so if you have 3 numbers and if you are trying for the first one it will go for 500000000000000 iterations, hence as the overall product value wrt to the value matters a lot... try something else....
Helpful Answer?
Yes | No
Inappropriate?
Sep 17, 2011
by donutello:
narya, your solution is not O(n). You have to also account for how many times you will run through the inner loop - which will be a lot.
You can do it in O(n) time and O(n) space. In one pass, populate B[i] with the product of every number before i. In the second pass, multiply this with the product of every number after i. Can't think of a way to do it without the second array.
void ArrayMult(int *A, int size)
{
runningProduct = 1;
int *B = new int[size];
for(int i = 0; i < size; ++i)
{
B[i] = runningProduct;
runningProduct *=A[i];
}
runningProduct = 1;
for (int i = size - 1; i >= 0; --i)
{
B[i] *= runningProduct;
runningProduct *= A[i];
}
for(int i = 0; i < size; ++i)
{
A[i] = B[i];
}
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
===================================
Explain the difference between Array Lists, Linked Lists, Vectors, Hash Maps, (from Java's JDK) etc. and when one choice is better of another.
=========================================
If you want to distribute a large file (gigabytes) in a large (100+ machines) park how do you do it?
Answers & Comments (5)
May 5, 2009
by Interview Candidate:
First I mentioned rsync, then shell scripts with lists of machines that copy the file via FTP or SFTP. Also dividing the network into a tree of machines that copy their file on to child-nodes would be possible. You could also split the files into smaller pieces and speed up the process this way. The problem may be nodes that are down or slow. Finally you could send the small pieces to random nodes until the big file has arrived everywhere.
Helpful Answer?
Yes | No
Inappropriate?
May 6, 2009
by Anonymous:
Bittorrent! Or via some gossip algo
Helpful Answer?
Yes | No
Inappropriate?
May 6, 2009
by Anonymous:
Since you have control over these machines and their network, you can impose the requirement of multicast support. Multicast file distribution is not uncommon. There will be some overhead for retries, but it should otherwise scale well.
Helpful Answer?
Yes | No
Inappropriate?
Jan 29, 2010
by Anonymous:
You distribute the file in tree-like fashion and keep the total number of copying tasks at any moment under a threshold because otherwise you slow down the network to a halting point.
Helpful Answer?
Yes | No
Inappropriate?
Aug 18, 2010
by Steve M:
Assuming you did not reserve a VLAN for the purpose of isolating your regular activities.. I would schedule the whole process at a good time (middle of night?). Use multicast if possible. And pace the data rate to a minimum. But, why the hack didn't you isolate your regular internal network traffic from service update traffic using VLAN?
========================================
Look for a string in a very long string - a needle in a haystack. Write the program in pseudo-code.
Answers & Comments (5)
1 of 2 people found this helpful
May 5, 2009
by Interview Candidate:
function isSubstring (needle, haystack) {
for(int i=0; ivalue < x) &&
(root->value < y))
return FindCommonRoot(root->right,x,y)
else if((root->value > x) &&
(root->value > y))
return FindCommonRoot(root->left,x,y)
else if(((root->value > x) && (root->value < y)) ||
((root->value < x) && (root->value > y)))
return root
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Nov 8, 2010
by lamont:
Node *Tree::LeastCommonRoot(x, y)
{
Node *runner = this->root;
while (runner)
if (x < runner->value && y < runner->value)
runner = runner->left;
else if (x > runner->value && y > runner->value)
runner = runner->right;
return runner;
}
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Dec 7, 2010
by Aytekin:
Dear Lamont,
You need another "else" statement which should return runner. Otherwise there will be an infinite loop in some cases (when one of x or y is equal to the current root).
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Dec 11, 2010
by Vladimir:
Here's a Java version:
// This method is in BSTNode class
BSTNode findLowestCommonAnsector(int va1, int val2) {
BSTNode root = this;
while(root != null) {
int val =root.value;
if(val > val1 && val > val2)
root = root.left;
else if(val < val1 && val < val2)
root = root.right;
else
return root;
}
return null;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 14, 2010
by lamont:
@Aytekin - D'oh! This code originally had an "else break" but I failed to type it in here. It's not like this is a special case. This is what happens when we find the common root and want to return it.
The top solution (Tal) has a similar problem. If x or y equals the current value, the function falls off the end without returning anything. I was trying to improve upon it and ended up making a bigger mistake. Sorry, folks.}}}
==========
Given an array of numbers, replace each number with the product of all the numbers in the array except the number itself *without* using division.
nswers & Comments (7)
4 of 4 people found this helpful
Sep 11, 2010
by Jordan:
O(size of array) time & space:
First, realize that saying the element should be the product of all other numbers is like saying it is the product of all the numbers to the left, times the product of all the numbers to the right. This is the main idea.
Call the original array A, with n elements. Index it with C notation, i.e. from A[0] to A[n - 1].
Create a new array B, also with n elements (can be uninitialized). Then, do this:
Accumulator = 1
For i = 0 to n - 2:
Accumulator *= A[i]
B[i + 1] = Accumulator
Accumulator = 1
For i = n - 1 down to 1:
Accumulator *= A[i]
B[i - 1] *= Accumulator
Replace A with B
It traverses A twice and executes 2n multiplicates, hence O(n) time
It creates an array B with the same size as A, hence O(n) temporary space
Helpful Answer?
Yes | No
Inappropriate?
Sep 25, 2010
by rotoiti:
# A Python solution (requires Python 2.5 or higher):
def mult(arr, num):
return reduce(lambda x,y: x*y if y!=num else x, arr)
arr = [mult(arr,i) for i in arr]
# O(n^2) time, O(n) space
Helpful Answer?
Yes | No
Inappropriate?
3 of 3 people found this helpful
Oct 6, 2010
by pflau:
Create two more arrays. One array contains the products of the elements going upward. That is, B[0] = A[0], B[1] = A[0] * A[1], B[2] = B[1] * A[2], and so on. The other array contains the products of the elements going down. That is, C[n] = A[n], C[n-1] = A[n] * A[n-1], and so on.
Now A[i] is simply B[i-1] * C[i+1].
Helpful Answer?
Yes | No
Inappropriate?
Oct 7, 2010
by xamdam:
def without(numbers):
lognums = [math.log10(n) for n in numbers]
sumlogs = sum(lognums)
return [math.pow(10, sumlogs-l) for l in lognums]
Helpful Answer?
Yes | No
Inappropriate?
1 of 3 people found this helpful
Jun 10, 2011
by narya:
Here are my 2 cents to do this in memory without creating temporary arrays. The simple solution , if division was allowed, was multiple all the elements of the array i.e.
tolal = A[0]*A[1]]*....*A[n-1]
now take a loop of array and update element i with A[i] = toal/A[i]
Since division is not allowed we have to simulate it.
If we say X*Y = Z, it means if X is added Y times it is equal to Z e.g.
2*3 = 6, which also means 2+2+2 = 6. This can be used in reverse to find how mach times X is added to get Z. Here is my C solution, which take pointer to array head A[0] and size of array as input
void ArrayMult(int *A, int size)
{
int total= 1;
for(int i=0; i< size; ++i)
total *= A[i];
for(int i=0; i< size; ++i)
{
int temp = total;
int cnt = 0;
while(temp)
{
temp -=A[i];
cnt++;
}
A[i] = cnt;
}
}
Speed in O(n) and space is O(1)
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jun 20, 2011
by Rohan:
#include
#define NUM 10
int main()
{
int i, j = 0;
long int val = 1;
long A[NUM] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Store results in this so results do not interfere with multiplications
long prod[NUM];
while(j < NUM)
{
for(i = 0; i < NUM; i++)
{
if(j != i)
{
val *= A[i];
}
}
prod[j] = val;
i = 0;
val = 1;
j++;
}
for(i = 0; i < NUM; i++)
printf("prod[%d]=%d\n", i, prod[i]);
return 0;
}
Helpful Answer?
Yes | No
Inappropriate?
Aug 25, 2011
by Devin:
void fill_array ( int* array, size ) {
int i;
int t1,t2;
t1 = array[0];
array[0] = prod(1, size, array );
for(i = 1; i < size; i++){
t2 = array[i];
array[i] = prod(i, array.size(), array)*t1;
t1 *= t2;
}
int prod(start, end, array){
int i;
int val(1);
for(i = start; i < end; i++ )
val *= array[i];
return val;
}
}}}}}}}}}}}}}}}}}}}
========================
How to select a random sample of size K from a stream of numbers.
http://en.wikipedia.org/wiki/Reservoir_sampling
========================
What is the strategy pattern in Java?
Strategy pattern allows encapsulates algorithms into objects and selects one at runtime depending on some filter like data type. ie:) When you're parsing a set of data; if the data set usually has smaller size you can use the strategy that parses all. If the data set is usually large you can choose a strategy that breaks it up into chunks
Wikipedia has good examples: http://en.wikipedia.org/wiki/Strategy_pattern#Java
=================
I had always wanted to work at Google, but I never thought I would get in. I'm 45 years old and I have a 2.2 GPA.
My friend at Google submitted my resume and I waited quite a while before I got a rejection letter. In retrospect, with them receiving 3000 resumes a day, it must be very easy to get lost in the shuffle unless your resume really stands out, and mine certainly did not. I waited a while and then contacted Google again and asked them to reconsider my resume, and they did. From that point on, it was an amazing process.
Right away I got an email asking when would be a good time for a recruiter to talk with me (HR screen). I said, "If not now, when?" and 60 seconds later I got a call from the recruiter. We talked for 45 minutes and mostly it seemed like just fun chitchat. She asked about my experience and what I liked to work on and what languages I preferred. Then she said she would find an engineer suitable for me and would call me back soon. She called the next day and we scheduled a phone interview (tech screen) for the following week. She also send me an email about what to expect and things to brush up on.
The next week I got the call from an engineer. We worked together in a Google Doc, and on the phone. He asked me about my resume, particularly my machine language experience. Then we did a bit manipulation problem, and I missed an obvious optimization. Then he asked me the main problem which was very clever. I came upon the solution very quickly, using recursion, but I screwed up on the complexity analysis. Afterwards, we chatted about Google life. It was a fun experience, but I figured I had blown it.
I got a call from the recruiter an hour later telling me that the feedback was positive and that we would move on to the on-site interview. I spent a month in front of my white board practicing problems, especially from Gayle Laakmann's book, Cracking the Coding Interview. I read through Introduction to Algorithms , but there was just too much information in there to cram into my brain.
At one point I was worried about my low 2.2 GPA and asked if I would be given a chance to explain the situation. I sent them an email and 30 seconds later one of the recruiters called me and said, basically, no one cares about your GPA. I get the impression that it's just a metric they use if there's nothing else on your resume to judge you by.
I am not going to describe the interviews here. Sorry. Not only did I sign an NDA, but I also don't want to spoil it for anyone. I will just say this much: Those people who said, "They asked me a simple CS101 question and I answered it and they still didn't hire me, those arrogant pricks!", well, dude you completely missed the point of the exercise. It's really not about getting the "right" answer.
The interviewers were all very cool. Some were reserved, and some were friendly and outgoing. I had a very fun time, but I missed a lot of simple things, didn't complete all of the problems, made simple syntax errors, and completely fumbled the interview that focused on Java. I left depressed, but feeling like I had been given a very fair chance.
I got a call from a recruiter two days later saying that the interview feedback was "pretty positive" and that he decided to forward it to the Hiring Committee. The following Monday the Hiring Committee gave me a "unanimous thumbs up". Another recruiter emailed me to say she would be contacting my references and my application would go through the Compensation Committee and the Executive Committee. I was given a questionnaire to fill out, asking about past employment details and such. It also asked about any past achievements I may want the Executive Committee to know about. They said I would probably hear something in the next few weeks.
Getting close to the end of the two week period, at 10:30pm, I got the email to "extend me an offer". When I replied to the email, she saw I was still awake so she called me on my cell phone at 11pm to give me the details as soon as possible. And the details were VERY generous, so I did not negotiate.
Overall, it was an awesome experience. Everyone was super nice and polite. The whole thing took two months, but a month of that was me asking for time to prepare. I've heard of cases where they can push it through in two weeks if you re really in a hurry. They kept asking me if I had any time constraint that they needed to work with. Also, yes, I asked, and Larry Page did review and sign off on my final approval. From his own words, he's gotten so good at it that it takes him less than a minute for each one.
I will only give this advice about the actual interview process: If you thought you aced it, you probably missed something. It's not about getting the "right" answer. It is about soooo much more. But, like I said, I don't want to spoil the fun.
======================
Given a set of strings, a number 'n', and a function that takes a string and gives back a score, find the n largest scored strings in the set.
Answers & Comments (5)
0 of 1 people found this helpful
Nov 30, 2011
by Steve:
Use a Max heap (a min heap where the x<=y operation is score(x) >= score(y)). It can be built in O(n) time. Extracting the maximum element (which is the root) take O(log(n)) , and you do it k times.
Anyway the idea is around sorting. There are tons of less efficient way but I am sure there is one or 2 more efficient way.
Helpful Answer?
Yes | No
Inappropriate?
Dec 1, 2011
by Anonymous:
{{{
int score(char *str)
{
int x = 0;
while (*str)
{
x += (int)*str++;
}
return x;
}
int partition(int *scores, char **s, int n)
{
int pivot = scores[0];
char *ps = s[0];
int small = n - 1;
int large = 1;
while (small > large)
{
if (scores[small] < pivot)
{
--small;
}
else if (scores[large] >= pivot)
{
++large;
}
else
{
int temp = scores[small];
scores[small] = scores[large];
scores[large] = temp;
char *st = s[small];
s[small] = s[large];
s[large] = st;
}
}
if (scores[small] < pivot)
{
--small;
}
scores[0] = scores[small];
s[0] = s[small];
scores[small] = pivot;
s[small] = ps;
return small;
}
char ** TopKScorer(char **s, int n, int k)
{
if (n <= k)
{
return s;
}
int *scores = new int [n];
for (int i = 0; i < n; ++i)
{
scores[i] = score(s[i]);
}
int goal = k;
char **cs = s;
int *c_scores = scores;
int length = n;
int current = -1;
while (1)
{
current = partition(c_scores, cs, length);
if (current == goal)
{
break;
}
if (current < goal)
{
goal -= (current + 1);
cs += (current + 1);
c_scores += (current + 1);
length -= (current + 1);
}
else if (current > goal)
{
length = current;
}
}
delete []scores;
return s;
}
}}}
Helpful Answer?
Yes | No
Inappropriate?
Dec 7, 2011
by Allen:
/*return the position of the ith smallest element(index start with 0). scores[index][0=str_key 1=value]*/
public static int quick_select(int[][] scores, int p, int r, int i) {
if(i > r || i < p) return -1;
if (p == r) {
return scores[p][0];
}
int q = partition(scores, p, r);
if (q == i) {
return scores[q][0];
}
if (q > i) /*ith is in the left pile*/ {
return quick_select(scores, p, q - 1, i);
}
return quick_select(scores, q + 1, r, i);
}
/*return the position of the selected pivot*/
private static int partition(int[][] scores, int p, int r) {
int x = scores[r][1];
int q = p;
for (int i = p; i < r; i++) {
if (scores[i][1] < x) {
int[] tmp = {scores[i][0], scores[i][1]};
scores[i][0] = scores[q][0];
scores[i][1] = scores[q][1];
scores[q][0] = tmp[0];
scores[q][1] = tmp[1];
q++;
}
}
int[] tmp = {scores[r][0], scores[r][1]};
scores[r][0] = scores[q][0];
scores[r][1] = scores[q][1];
scores[q][0] = tmp[0];
scores[q][1] = tmp[1];
return q;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 9, 2011
by Anonymous:
Depending on the size of the string set, you have multiple possibilities here.
1. If the number of strings is reasonable and you can store the score for each one of these. Then the method you guys described, by using the idea from QSORT is perfect! :)
Complexity:
Time: O(M)
Space: O(M)
M is the number of strings! Good when M is reasonable as size.
2. If the set size is really big, and also you assume the strings come to you 1 by one, then the most efficient solution that I can see is to implement a Double Ended Priority Queue of maximum size N (Nth element). This can be done by using a Min-Max Heap.
The total complexity will be in this case:
Time: O(M * log (N))
Space: O(N)
M is the number of strings and N the Nth Element we want. Good method when N< m);
HCF(m,n) = HCF (m%n , m )
Helpful Answer?
Yes | No
Inappropriate?
Oct 29, 2011
by Anon:
Create a loop that multiplies m by the loop counter
mod the mulitple of m by n and if the first modulus that is 0 is the least common multiple.
================
Given a graph, find if it represents a tree.
Add Tags [?]
See more for this Google Software Engineer Interview
Helpful Question?
Yes | No
Inappropriate? Facebook
Looking for a job? See featured jobs below or try Jobs in Istanbul
Software Engineer
Cadence Designs â San Jose, CA
From Cadence Designs â 12 days ago
Software Engineer
Texas Instruments â United States
From Texas Instruments â 24 days ago
Answers & Comments (3)
1 of 1 people found this helpful
Oct 15, 2011
by M H:
I think this can be done by traversing the graph in Breadth First manner, and if you happen to visit a node more than once, it is a graph, otherwise it is a tree
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 21, 2011
by mike:
a tree is a graph with N-1 edges (N = number of vertices). then i think you just need to pick 1 vertex and check if you can reach all the others from this one
Helpful Answer?
Yes | No
Inappropriate?
Dec 29, 2011
by pat:
it depends on your definition of a tree. Technically all you need to qualify as a tree is to have that tree's nodes be connected and have no cycles. That means you don't necessarily need all the nodes of the graph to be part of the tree (that's called a spanning tree)
=====================
How would you determine if someone has won a game of tic-tac-toe on a board of any size?
========================
Given a list of integers that fall within a known short but unknown range of values, how to find the median value?
=================
Given a list of generic items, describe/code the approach would you take to finding the most common item.
===============
Given a list of integers of at least length 7, print the average of each consecutive 7 number long subsequence (sliding window).
===================
Given a word that consists of two words such as "aman" give all the combination of valid two words. You are given a dictionary to test against.
Example: aman--> a man, am an. watermelon--> water melon
===============
Given a base 10 number, print the hexidecimal (base 16) representation of that number.
Answers & Comments (1)
Oct 22, 2011
by b:
public void printHex(int d) {
string s = "";
int m = 0;
int next = d;
int a[16];
a[10] = "a";
a[11] = "b";
a[12] = "c";
a[13] = "d";
a[14] = "e";
a[15] = "f";
while (next > 15) {
m = next % 16;
if (m > 9 && m < 16)
s = a[m] + s;
else
s = m + s;
next = next / 16;
}
system.out.println(s);
}
=======================
Sort a million 32 bit integers using only 2MB of RAM
Answers & Comments (2)
4 of 4 people found this helpful
Nov 9, 2010
by Anonymous:
1 million integers = 4MB which is > 2MB RAM.
solution: external sort - divide and conquer
1. read half the list into 2MB ram and sort using quicksort (quicksort uses logn space - however 0.5m integers is less than 2MB (2000kb v 2048kb) so this should be okay).
2. write sorted data to disk
3. repeat for next chunk
4. merging results: we need an output buffer. lets say this is 1MB. then we read 512KB from each of your chunks into input buffers. we then perform a 2-way merge of the data. when an input buffer becomes empty we can pull in the remainder of the chunk.
5. when the output buffer is full we write this to disk.
6. when the process completes we are left with 2x 1MB files sorted in the correct order.
notes:
- when choosing an input buffer size, the smaller we make it the more I/O operations we will need to perform which would significantly slow down our sorting. a smaller output buffer would also do the same. we would rather a smaller output buffer as multi-threading would allow sorting to continue while writing to disk.
- we could use an additional thread to load next chunk from disk when input buffer drops below half size.
- HDD mirror raid would increase sequential read and write speed to disk as well as HDD speed
- compression of input would also reduce I/O
- we choose quicksort over mergesort as mergesort requires O(n) space. quicksort therefore reduces the number of merge operations.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 12, 2010
by Anonymous:
1) divide those integers into 5 equal set of numbers, so each set is less than 2MB (very important for later)
2) sort them using qsort or something
3) find the medium of all those 5 sets
4) then you are left with arrays with following
ie:
... 2, 5, 7, (10), 13, 14, 19...
... 4, 5, 9, (12), 19, 20, 33...
... 1, 2, 10, (14), 22, 23, 43... <= medium of mediums
... 10, 11, 12, (17), 19, 20, 35...
... 1, 2, 19, (21), 24, 29, 33...
where everything left and above medium of mediums(14) is smaller than 14, and everythign right and bleow medium of mediums(14) is larger than 14.
then, you merge everything left and above of 14 to a set of number smaller than 14 (samller set), you merge everything right and below to a set of sorted number which larger than 14 (larger set)
then you sort remaining two group of numbers (right below and left above), take numbers smaller than 14 to merge with smaller set, and take numbers larger than 14 to merge with larger set.\\
================
Find 3 numbers in an array adding up to a given sum S.
nswers & Comments (1)
3 of 3 people found this helpful
Nov 9, 2010
by lamont:
This is called the 3SUM problem. Given an array a[n], find three elements a[i] + a[j] + a[k] = S (for distinct values of i, j, and k). The standard solution is O(n^2):
sort(a, n);
for (int i = 0; i < n; i++) {
int j = 0;
int k = n - 1;
while (j < k) {
float result = a[i] + a[j] + a[k];
if (j == i || result < s)
j++;
else if (k == i || result > s)
k--;
else
output("Solution found: a[%d] + a[%d] + a[%d] = %g\n", i, j, k, result);
}
}
Helpful Answ
===================
Questions in first round:
Write a method to pretty print a binary tree. Don't make any assumptions, i.e. the tree could be highly unbalanced.
Given a dictionary segment a piece of un-spaced text to find meaningful words. e.g "makemytrip"->make my trip
Answer Question
2nd Round:
A design question (don't remember) and another question on adversarial mini-max search
3rd Round:
Write a method to find the next ancestor of a node in a Binary Search Tree.
Write a recursive function to convert Binary Code of a number into its equivalent Gray's code and the other way round.
4th round:
Given two sorted arrays, find the kth minimum element of both.
Given a set of intervals, find the interval which has the maximum number of intersections.
5th round:
This one was focused on previous projects and experience and how good I was at what I had been doing.
================
Convert char string to integer.
Pay attention to integer ranges and negative numbers.
=============
Find occurrences of a number in sorted array (allow duplicates).
Answers & Comments (2)
Dec 30, 2011
by Interview Candidate:
O(logN) required
Helpful Answer?
Yes | No
Inappropriate?
Jan 3, 2012
by PixelPerfect3:
Use binary search to find the number (O(logN)). Once that is done you can search around that index. Though that could become O(N).
Better answer: run binary search again twice once you have found the number the first time. For the upper half and the lower half - so total run time is O(logN)
=================
If integer array used to store big integers (one integer store one digit), implement arithmetic operations.
E.g. ['1','2','3']+['2','9']=['1', '5', '2']
===========
To merge two sorted integer arrays.
=============
Given a generic tree, how would you pick a node at random with uniform probability?
===========
What is Google's mission?
===========
what's your favorite project and why?
================
how to build a heap?
==============
Returning the n-th element of a linked list.
===========
What was your favorite comp. sci class?
===========
What do you see as Google's short term and long term objectives?
=============
Find occurrences of a number in sorted array (allow duplicates).
Answers & Comments (2)
Dec 30, 2011
by Interview Candidate:
O(logN) required
Helpful Answer?
Yes | No
Inappropriate?
Jan 3, 2012
by PixelPerfect3:
Use binary search to find the number (O(logN)). Once that is done you can search around that index. Though that could become O(N).
Better answer: run binary search again twice once you have found the number the first time. For the upper half and the lower half - so total run time is O(logN)
=====================================
fibo
I learned a lot from http://knol.google.com/k/efficient-recursive-computation-of-fibonacci-numbers#
This may be the ultimate answer you want.
But I guess talking about 2 common methods (inefficient straightforward recursive way(O(2^N)?) and dynamic programming recursive (O(N))) are a minimal interviewers expect? I personally like the matrix way to solve the Fibonacci problem in O(LogN) time. The ma thematic way to compute in O(1) time may not be the answer CS people look for.
=================
Given a generic tree, how would you pick a node at random with uniform probability?
Flatten the tree into an array list, then generate a uniform random number from 0 to 1, and choose the corresponding index in the flattened array list.
================
How to randomly select a number with equal probability from an array with unknown size?
Keep a variable as the return result and current size of the array. Update the result with probability size-1/size, when getting new number.
=====================
when will 2hands of a clock point to the same position, C++, python
Not once every hour. By the time the minute hand meets the hour hand between 11 and 12, it would have been 12 already. So it is 11 times in any 12 hour period.
===================
where is your edge?
==================
To merge two sorted integer arrays.
===============
Find if a binary tree is the sub-tree of another.
===============
I applied online and get scheduled a phone interview consisted of 2 sessions of 45 mins each. The first interviewer is kind of tough and speaks really fast. She asked me to introduce myself and then ask me about the datastructures I am familiar with. Then she asked the time complexity analysis about BST and hashtables and asked me to code a program to check if a binary tree is the subtree of another.
The second interviewer goes straightly into technical questions and ask me to write a program to find the largest possible value of an integer array with limited number of swaps in the neighboring elements. Eg. an array of 1,2,3,4, the max value with 1 swap is 2,1,3,4, and with 2 swaps is 3,1,2,4. After that he ask me how to find the perfect numbers,which can be represented as a ^ m + b ^ n (a, b >= 1, m, n >= 2), between 1 and 1M. I was kinder of nervous coz this is my first interview with such a tough company and really didnt do well though the questions don't seem to be that hard. lol
Find the perfect numbers between 1 and 1M, details in my interview description.
=================
Really can not disclose any questions due to NDA. But a hint! Heap DataStructure is more important than most of us think of!
===============
What happens when you type www.google.com in your browser?
Answers & Comments (2)
Jul 22, 2010
by Andi Mullaraj:
A lot, depends how deep down you want to go detailing it:
1. The line gets parsed and the protocol, server, port, query gets retrieved
1.1. The mouse pointer is switched to hourglass
2. Browser connects to server at the default/specified port
2.1. If the server's name is in DNS cache then its ip address is retrieved
2.2. The DNS server (already set up) is queried to resolve the IP address of www.google.com
3. Browser sends a GET request followed a crlf sequence then by the headers all followed by respective crlf-s
3.1 If this server has already cached cookies, the browser sends them as cookie headers
3.2 If the browser supports compression it tells the server what compression is using (via headers) as well as what compression it could accept in return
3.3 Sends a content-length header set to value "0"
3.4. Sends a header instructing the server how to denote the end of its transmission stream. Connection: Close would be the most common
3.5 Sends a crlf sequence to mark the end of the headers (after eventual other headers are sent)
4. (Sends no message body)
5. Waits for the response which is composed by response code, status, crlf, headers all marked by separate crlf-s and the message body (same as during the send phase)
5.1. Parses the response code / status
5.2. If this response starts with 2 it caches cookies, decompresses (if header is mentioning compression) parses and displays the html content of message body (executing eventual scripts hooked to different DOM elements/events)
5.3 If the response code starts with 3 redirects t the server mentioned in the response (GOTO 1)
5.4 If the response code starts with 5 parses the response and displays it to the user
6. Mouse pointer is turned back from hourglass to normal
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 5, 2010
by duke coder:
I think we can merge the above with this
Step 1: Request a record
You begin by asking your computer to resolve a hostname, such as visiting 'http://www.google.com' in a web browser. The first place your computer looks is its local DNS cache, which stores DNS information that the computer has recently retrieved.
Step 2: Ask the Recursive DNS servers
If the records are not stored locally, your computer queries (or contacts) your ISP's recursive DNS servers. These machines perform the legwork of DNS queries on behalf of their customers. The recursive DNS servers have their own caches, which they check before continuing with the query.
Step 3: Ask the Root DNS servers
If the recursive DNS servers do not have the record cached, they contact the root nameservers. These thirteen nameservers contain pointers for all of the Top-Level Domains (TLDs), such as '.com', '.net' and '.org'. If you are looking for 'www.google.com.', the root nameservers look at the TLD for the domain - 'www.google.com'- and direct the query to the TLD DNS nameservers responsible for all '.com' pointers.
Step 4: Ask the TLD DNS servers
The TLD DNS servers do not store the DNS records for individual domains; instead, they keep track of the authoritative nameservers for all the domains within their TLD. The TLD DNS servers look at the next part of the query from right to left - 'www.google.com' - then direct the query to the authoritative nameservers for 'google.com'.
Step 5: Ask the Authoritative DNS servers
Authoritative nameservers contain all of the DNS records for a given domain, such as host records (which store IP addresses), MX records (which identify nameservers for a domain), and so on. Since you are looking for the IP address of 'www.google.com', the recursive server queries the authoritative nameservers and asks for the host record for 'www.google.com'.
Step 6: Retrieving the record
The recursive DNS server receives the host record for 'www.google.com' from the authoritative nameservers, and stores the record in its local cache. If anyone else requests the host record for 'www.google.com', the recursive servers will already have the answer, and will not need to go through the lookup process again until the record expires from cache.
Step 7: The Answer!
Finally, the recursive server gives the host record back to your computer. Your computer stores the record in its cache, reads the IP address from the record, then passes this information to the web browser. Your browser then opens a connection to the IP address '72.14.207.99' on port 80 (for HTTP), and our webserver passes the web page to your browser, which displays Google
================
Pick any Google product and tell me how you would improve it
===============
Explain how quick sort and merge sort work
================
How would you sort an array of one millions integers?
Answers & Comments (4)
1 of 2 people found this helpful
Oct 4, 2010
by Swapnil Dipankar:
The trick here is to ask whether the entire array fits into memory all at the same time:
- If it fits in memory all at once, use quicksort - O(n log n)
- If it does not, divide the array into chunks that does, sort the chunks individually using quicksort and store them on the disk. Then read the sorted lists, merge them and save them on the disk - O(n log n) + n = O(n log n)
Helpful Answer?
Yes | No
Inappropriate?
Oct 5, 2010
by Bartosz Milewski:
For some bonus points you can discuss how to implemented sorting using multiple machines.
- Send chunks of the array to multiple machines.
- On each machine perform merge sort (or quick sort, if the chunk fits in memory).
- Odd-numbered machines send their sorted chunks to even-numbered machines
- Even-numbered machines merge their own chunks with the ones sent to them
- Repeat the same with machines numbered in multiples of 4, 8, etc, until the final merge is performed.
If the number of machines is not a power of two, some machines will have no neighbor to send their chunk to. They will be idle in the next iteration and should change their number to that of their missing neighbor.
Helpful Answer?
Yes | No
Inappropriate?
Oct 7, 2010
by vsp:
One million integers is less than 4Mb can probably fit into memory. I would further ask about the rexpected range of numbers. If it is sufficiently small (e.g. ages, SSNs, etc) then sort could be done in O(n) time.
Helpful Answer?
Yes | No
Inappropriate?
Oct 26, 2010
by Babji Chetty:
I will use "Merge Sort" and map-reduce it (or use any grid based framework...or code my own stuff). Do you guys think it's right approach?
================
Write code to check the validity of a suduko square
boolean checkSudoku(int[][] a, int n)
{
int s1, s2, s3;
for(int i = 0; i < n ^ n; i++)
{
s1 = s2 = s3 = 0;
for(int j = 0; j < n ^ n; j++)
{
if(((s1 & a[i][j]) //on line
| (s2 & a[j][i]) // on column
| (s3 & a[i%n][j%n]) //on a square
) > 0)
return false;
s1 |= a[i][j];
s2 |= a[j][i];
s3 |= a[i%n][j%n];
}
}
return true;
}
}
============
Print all shortest paths in a grid (Cartesian), given the starting and the ending point.
Answers & Comments (3)
Sep 21, 2010
by Interview Candidate:
Be aware of the margins
Helpful Answer?
Yes | No
Inappropriate?
Jan 17, 2011
by Victor:
You should not care about the margins since you are given 2 points and these points are on the grid. Since you just work with shortest paths, you will only work in the rectangle (or line) defined by the given points. This is an example of implementation (recursive):
public class GridShortestPaths {
private static int sign(int a)
{
return a < 0 ? -1 : 1;
}
public static void solve(int sx, int sy, int ex, int ey, Vector v)
{
if(sx == ex && sy == ey)
{
for(int i = 0; i < v.size(); i++)
{
System.out.print("(" + v.get(i).x + "," + v.get(i).y + "), ");
}
System.out.print("(" + sx + "," + sy + ")");
System.out.println(" ");
return;
}
int xdir = 0;
int ydir = 0;
if(sx > ex)
{
xdir = -1;
}
else if (sx < ex)
{
xdir = 1;
}
if(sy > ey)
{
ydir = -1;
}
else if(sy < ey)
{
ydir = 1;
}
v.add(new Point(sx,sy));
if(xdir != 0)
{
solve(sx + xdir, sy, ex, ey, v);
}
if(ydir != 0)
{
solve(sx, sy + ydir, ex, ey, v);
}
v.remove(v.size() - 1);
}
public static void main(String[] args) {
solve(1,2,4,5, new Vector());
}
}
The problem solved from (1,2)to (4,5). The results are:
(1,2), (2,2), (3,2), (4,2), (4,3), (4,4), (4,5)
(1,2), (2,2), (3,2), (3,3), (4,3), (4,4), (4,5)
(1,2), (2,2), (3,2), (3,3), (3,4), (4,4), (4,5)
(1,2), (2,2), (3,2), (3,3), (3,4), (3,5), (4,5)
(1,2), (2,2), (2,3), (3,3), (4,3), (4,4), (4,5)
(1,2), (2,2), (2,3), (3,3), (3,4), (4,4), (4,5)
(1,2), (2,2), (2,3), (3,3), (3,4), (3,5), (4,5)
(1,2), (2,2), (2,3), (2,4), (3,4), (4,4), (4,5)
(1,2), (2,2), (2,3), (2,4), (3,4), (3,5), (4,5)
(1,2), (2,2), (2,3), (2,4), (2,5), (3,5), (4,5)
(1,2), (1,3), (2,3), (3,3), (4,3), (4,4), (4,5)
(1,2), (1,3), (2,3), (3,3), (3,4), (4,4), (4,5)
(1,2), (1,3), (2,3), (3,3), (3,4), (3,5), (4,5)
(1,2), (1,3), (2,3), (2,4), (3,4), (4,4), (4,5)
(1,2), (1,3), (2,3), (2,4), (3,4), (3,5), (4,5)
(1,2), (1,3), (2,3), (2,4), (2,5), (3,5), (4,5)
(1,2), (1,3), (1,4), (2,4), (3,4), (4,4), (4,5)
(1,2), (1,3), (1,4), (2,4), (3,4), (3,5), (4,5)
(1,2), (1,3), (1,4), (2,4), (2,5), (3,5), (4,5)
(1,2), (1,3), (1,4), (1,5), (2,5), (3,5), (4,5)
Helpful Answer?
Yes | No
Inappropriate?
Nov 26, 2011
by mike:
probably the question had other issues like you can't use some of the grid cells
================
Write an algorithm to test if n is power of 2
Google Interview Question
Post an Interview
Web: www.google.com | HQ: Mountain View, CA
Overview
|
Salaries
|
Reviews
|
Interviews
|
Photos
|
Jobs
1,017 Interview Reviews |
Back to all Google Interviewsiew Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
Sep 20, 2010
Write an algorithm to test if n is power of 2
Add Tags [?]
See more for this Google Software Engineer Interview
Helpful Question?
Yes | No
Inappropriate? Facebook
Looking for a job? See featured jobs below or try Jobs in Istanbul
Software Engineer
Cadence Designs â San Jose, CA
From Cadence Designs â 12 days ago
Software Engineer
Texas Instruments â United States
From Texas Instruments â 24 days ago
========================
Given a directory with lots of files, find the files that have the same content (the file names are different). I think file format is not considered, since when I said the size of the file with the same content should be the same, the interviewer did not deny it.
Answers & Comments (2)
3 of 4 people found this helpful
Oct 11, 2010
by EricT:
For files with the same size, generate a checksum. Files with the same checksum are likely to have identical content (you can then compare the actual file contents to be sure).
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jan 21, 2011
by v:
Map> map = new HashMap>();
for (String file : listDirFiles()) {
String hash = computeHash(file);
List files = map.get(hash);
if (files == null) map.put(hash, files = new ArrayList();
files.add(file);
}
for (Map.Entry> entry : map.entrySet()) {
List files = entry.getValue();
if (files.size() > 1) reportFilesWithTheSameContent(files);
})}
========================
write a program to do carry out one of your favorite sorting algorithms
=======================
How would you sort a file which is too large to fit in memory.
Answers & Comments (3)
0 of 1 people found this helpful
Oct 18, 2010
by Interview Candidate:
Use mergesort.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Nov 10, 2010
by Anonymous:
the correct answer is an external sorting algorithm which is more complex than just mergesort. see external sort on wikipedia.
Helpful Answer?
Yes | No
Inappropriate?
Feb 25, 2011
by Anonymous:
Split the file into k chunks of size n. Sort them in time k(n log n). Then you can merge them in log k layers in a binary tree sort of structure, taking time kn for each layer.
Total time will be k(n log n) + kn(log k) = kn (log n + log k) = kn(log kn).
=======================
How do you find the median of a set of numbers?
nswers & Comments (16)
Oct 21, 2010
by Interview Candidate:
I know that, tons of answers to this problem exist, but I choose to directly go for the O(n) solution of getting the kth number from an unsorted array. It seems, the interviewer is not aware of this answer.
Helpful Answer?
Yes | No
Inappropriate?
Oct 22, 2010
by Anonymous:
I don't quite get it... can you explain the solution a bit more? What do you mean by finding the kth element and n/2th element...?
Helpful Answer?
Yes | No
Inappropriate?
Oct 23, 2010
by Anonymous:
Thanks for your comments.
Here is the link to the solution I am referring to: http://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_general_selection_algorithm
Let me know if you need further clarification.
Helpful Answer?
Yes | No
Inappropriate?
Oct 23, 2010
by Anonymous:
Oh, interesting. I hadn't heard of this algorithm, thank you!
I would think the interviewer perhaps expected a solution involving hash table, by which it's possible to find the median in linear time on an unsorted list...
Helpful Answer?
Yes | No
Inappropriate?
Oct 23, 2010
by Anonymous:
Sorry, it can't be done in linear time using hash table, sorry for the confusion...
Helpful Answer?
Yes | No
Inappropriate?
Oct 24, 2010
by Interview Candidate:
I think the Interviewer first wanted me to say that I would sort the elements and get middle one. Then he would perhaps ask me to update on that if more numbers and requests come in. I guess he was taken aback to hear me propose this solution which he obviously haven't heard before.
Helpful Answer?
Yes | No
Inappropriate?
0 of 3 people found this helpful
Oct 29, 2010
by sai:
i can be solved by single formula (n/2)+1
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 29, 2010
by Interview Candidate:
@sai, are you sure?
The array is not sorted. In that case, your best hope is an O(n) expected time.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 7, 2010
by Anonymous:
Given an unsorted array of values, you can use a partitioning method. You can start from using the n/2th value as the initial pivot and depending on where it ends up, you pick the next pivot in the area around the center of the array until the processed pivot ends up in the n/2th spot. This will be your median.
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2010
by Interview Candidate:
This is my answer too. The link I posted earlier describes this algorithm. Funny thing is, the interviewer didn't know this method.
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2010
by Anonymous:
A problem with the partitioning method is that it could potentially share the worst case for quicksort, which is O(n^2), so you'd be better off sorting the whole list using mergesort or a similar O(nlogn) algy.
Helpful Answer?
Yes | No
Inappropriate?
Nov 8, 2010
by Interview Candidate:
Yes, thats a good point also. However, a good interviewer would have accepted the answer and then ask about any issues regarding this method. But the case here is, he wasn't aware of the method and that would cause any one to frown, having to hear this from an Engineer working for Google.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Nov 12, 2010
by Anonymous:
assume you have a lot memory to do bucket sort
1) Sort the number with bucket sort with counting repeating number (O(n)).
2) iterate from first number until you find the bucket with all numbers before bucket is n/2 (O(n)).
best case, worst case O(n)
If you can't fit everything into memory, then you have to use medium of mediums theory to find the approx medium, then work from there, that's a lot more complicated.
Helpful Answer?
Yes | No
Inappropriate?
Nov 13, 2010
by Interview Candidate:
Thanks for sharing your idea. Your answer once again confirms that there are multiple solution for finding median in O(n) time. I wish the interviewer guy knew this.
Helpful Answer?
Yes | No
Inappropriate?
Dec 5, 2010
by Anonymous:
Also, consider this approach. Build a BST of the array of numbers. We can then find the median by traversing the BST using Morris Inorder traversal (a variation of the normal inorder traversal. You can look it up on google search). The advantage of this is that if the more and more new numbers are added to BST we dont have to resort everytime.
The complexity is O(n) + O(logn) for the traversal and insertion respectively which is infact O(n). This might sound a little convoluted but it is just another approach for a scenario where you have a frequent addition of new numbers and want to find the median at regular intervals.
Helpful Answer?
Yes | No
Inappropriate?
Dec 5, 2010
by Interview Candidate:
That would be the ideal way of doing it if numbers kept on coming. And this too is yet another O(n) method. How could the Interviewer be not aware of any O(n) method?
==================
What are the issues with floating point calculation? For example, 1.0f + e-30, is there any issue with the statement.
nswers & Comments (3)
Oct 21, 2010
by Interview Candidate:
I said, floating point numbers lose precisions and as far as possible we should avoid them until the moment we can't do without them. The question was in relation to some other question.
Helpful Answer?
Yes | No
Inappropriate?
Nov 10, 2010
by Anonymous:
there are also overflow issues when casting an unsigned integer to a float (single-precision decimal)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 11, 2010
by Interview Candidate:
Thanks for the reply. This question was actually asked in conjunction with another question. Let me state that now:
We can calculate the variance of a set of number by first finding the average and then getting square of the differences with each number. Another way of doing this is to actually find the summation of square of all the numbers and then deducting an expression involving square of the average. The question was, what the flaw of using the second approach.
================================
What steps would you take to determine the source of a slow web site?
Answers & Comments (3)
0 of 1 people found this helpful
Oct 26, 2010
by Interview Candidate:
Lots of approaches, discuss all of the possible causes and how to troubleshoot them.
Helpful Answer?
Yes | No
Inappropriate?
4 of 4 people found this helpful
Nov 9, 2010
by Anonymous:
- 1st check the connection speed to remove that variable
- run yslow (cheeky) + firebug or chrome developer tools profiler
- profiling - check load times of resources css, js, images - isolate bottleneck
- check number of http requests and speed - AJAX is common these days
solutions:
- reduce http requests by bundling them together where possible
- make javascript and css external
- minify jscript
- compress css and javascript
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Feb 25, 2011
by Anonymous:
press command-U
Helpful Answer?
Yes | No
Inappropriate?
==================
If you had a list of appointments (each appointment has a begin time, an end time, and a boolean hasConflict), how would you efficiently go through them and set the hasConflict boolean for each. You cannot assume they are sorted in any way. Keep in mind that one appointment may be very long, etc.
Answers & Comments (6)
5 of 5 people found this helpful
Nov 8, 2010
by Mike:
Simplistic answer, O(n*n) best/worst/average
=================================
for x in appointments:
for y in appointments:
if (not x.hasConflict) and (x.end >= y.start) and (x.start <= y.end):
x.hasConflict = y.hasConflict = True
Better answer, O(n log n) best/average, O(n * n) worst
=================================
# This version starts with an in-place quicksort
# (which is O(n log n) in the best/average case, and O(n*n) in the worst case)
# and finishes with an iteration that is O(n) for the best/average case
# with no large conflicts, and O(n*n) for the worst case (all n appointments
# are involved in one large conflict).
# Best/average: O(n log n) + O(n) = O(n log n)
# Worst: O(n*n) + O(n*n) = O(n*n)
# Let's call the appointment list "A" for simplicity
quicksort(A) # Order by ascending start times, O(n log n) best/average
# Iterate over the sorted list
for x in range(0, len(A)):
for y in range(x, len(A)):
if (A[x].end >= A[y].start) and (A[x].start <= A[y].end):
A[x].hasConflict = A[y].hasConflict = True
# Keep iterating over y; x may still conflict with later appts
elif A[y].start > A[x].end:
# No conflict, and x cannot conflict with later appts, so skip them
break
The second method is certainly an improvement over the first, but there may still be a further improvement I'm not seeing. I don't like the fact that my worst case is still O(n*n)...
Helpful Answer?
Yes | No
Inappropriate?
Nov 9, 2010
by Anonymous:
Another method would be to use a bit vector.
find timespan between min begin time and max end time
create a bit vector (array of bytes) the size of the number of minutes in timespan
for x in appointments
calculate then length in minutes between x.start and x.end and create a bit vector representing that - this would be a bit hacky i expect
OR this with the timespan bit vector left shifted accordingly
if the result > 0 then set flag.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 27, 2010
by Arnab:
I agree with Mike's solution. Anonymous, lets say we create the bit vector. Every appointment would have the hasConflict variable set to true since its time window has all bits set to 1 in the bit vector.
Helpful Answer?
Yes | No
Inappropriate?
Jan 5, 2011
by Fish:
I got confused:
If appointment A and appointment B are overlapped, we set both A and B's hasConflict variable to be true or just one of them to be true?
Helpful Answer?
Yes | No
Inappropriate?
Feb 25, 2011
by Anonymous:
Here is another O(n log n + m) solution, where m is the number of conflicts. Well, first of all, nobody is noting that there are O(n^2) conflict booleans to set, but anyway...
Step 1: heapsort the appointments by start time.
Step 2: Set up a priority queue Q based on the end time of appointments. Earlier end time -> higher priority.
Step 3: Go through the appointments in order of start time:
For appointment i,{
Dequeue the first element of the priority queue while it ends before appointment i begins.
Set appointment i to be in conflict with every appointment in the priority queue, and vice-versa.
Enqueue appointment i.
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Mar 4, 2011
by mb:
Sort by start time. For each appt[i], all following appts with start time < appt[i] end time are in conflict. If you track the max end time of the conflicting appts to compare against subsequent appts, you need to visit each appt only once. O( n log n + n )
Helpful Answer?
Yes | No
Inappropriate?
================
Find a sequence with max sum in an array of negative and positive real numbers.
Answers & Comments (14)
0 of 4 people found this helpful
Nov 9, 2010
by Charles:
You construct a sub-sequence within the array where all entries are >= 0.0. Trick question.
Helpful Answer?
Yes | No
Inappropriate?
4 of 5 people found this helpful
Nov 9, 2010
by lamont:
Given an array a[n], find the subsequence with the greatest sum (without reordering the elements).
Let p[i] = the max sum of elements up to and including a[i]. It may or may not include a[i-1], a[i-2], etc. but it must include a[i]. Then p[i+1] = max(a[i+1], p[i] + a[i+1]). The basis is p[0] = a[0]. This recurrence is simple enough to perform in O(n) time and O(1) space. At each step, we need only decide whether to extend the current run or start a new one.
float bestsum = sum = a[0];
int i, besti = 0;
int len, bestlen = 1;
for (i = 1; i < n; ++i) {
if (sum < 0) {
sum = a[i];
len = 1;
}
else {
sum += a[i];
++len;
}
if (sum > bestsum) {
bestsum = sum;
besti = i;
bestlen = len;
}
}
printf("Elements %d through %d sum to %g\n", besti, besti + bestlen - 1, bestsum);
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 10, 2010
by monkeysdown:
function bestSum (array a):
size = count of items in array
bestsum = a[0] + a[1] //this assumes zero-indexed arrays
for (i=0; i < size; i++)
sum = a[i];
for (j=i+1; j < size; j++)
sum += a[j]
if sum > bestsum
bestsum = sum
endfor
endfor
return bestsum
end function
Helpful Answer?
Yes | No
Inappropriate?
0 of 3 people found this helpful
Nov 11, 2010
by Anonymous:
lamont, your solution assumes that all elements are positive.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 11, 2010
by lamont:
No. The (sum < 0) condition accounts for negative elements. My solution does assume that sequences of length 1 are allowed. In the case of ALL negative input, it chooses the single largest element (i.e. the one closest to zero).
I tested it against monkeysdown's O(n^2) solution on a variety of mixed positive/negative inputs. They produce the same results except in the case mentioned above.
The only error in my solution was the printf. It should read:
printf("Elements %d through %d sum to %g\n", besti - bestlen + 1, besti, bestsum);
Helpful Answer?
Yes | No
Inappropriate?
3 of 3 people found this helpful
Nov 11, 2010
by lamont:
If the minimum sequence length is 2, then it's still possible to solve in O(n). Briefly:
float sum = a[0] + a[1];
float bestsum = sum;
for (int i = 2; i < n; ++i) {
if (sum < a[i-1])
sum = a[i-1] + a[i];
else
sum += a[i];
if (sum > bestsum)
bestsum = sum;
}
return bestsum;
Helpful Answer?
Yes | No
Inappropriate?
2 of 4 people found this helpful
Nov 12, 2010
by Anonymous:
1) convert the sequence of pos/neg numbers into another sequence of pos/neg numbers where pos/neg numbers are alternating.
ie:
original sequence
2, -1, 3, 4, -5, -1, 10, 2
into
2, -1, 3+4, -5 + (-1), 10 + 2 ==> 2, -1, 7, -6, 12
with the new sequence, start with first number, as long as next pair of pos/neg number adds together is more than 0, then keep using those numbers in the sub-sequence.
The result is O(n) for worst case.
It's little more complicated to program.
Helpful Answer?
Yes | No
Inappropriate?
Nov 17, 2010
by Anonymous:
public static double maxSequenceSum(double[] array) {
double maxSum = Double.MIN_VALUE;
double maxElm = Double.MIN_VALUE;
double curSum = 0;
for(int i = 0; i < array.length; i++) {
maxElm = array[i] > maxElm ? array[i] : maxElm;
maxSum = curSum > maxSum ? curSum : maxSum;
if(curSum + array[i] >= 0)
curSum += array[i];
else
curSum = 0;
}
maxSum = maxElm > maxSum ? maxElm : maxSum;
return maxSum;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 17, 2010
by Anonymous:
small correction to my previous answer!
public static double maxSequenceSum(double[] array) {
double maxSum = Double.NEGATIVE_INFINITY;
double maxElm = Double.NEGATIVE_INFINITY;
double curSum = 0;
for(int i = 0; i < array.length; i++) {
if(curSum + array[i] >= 0) {
curSum += array[i];
maxSum = curSum > maxSum ? curSum : maxSum;
} else {
curSum = 0;
maxElm = array[i] > maxElm ? array[i] : maxElm;
}
}
maxSum = maxElm > maxSum ? maxElm : maxSum;
return maxSum;
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 4 people found this helpful
Nov 19, 2010
by Pat:
I can't believe they would still ask this question - easiest in the book.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jan 5, 2011
by jinxed_4_ever:
huh! dynamic programming written all over it!
Helpful Answer?
Yes | No
Inappropriate?
Jan 27, 2011
by Viet Nguyen:
public int computeDP() {
int[] V = new int[L.length];
V[0] = L[0];
int max = -1;
for(int i = 1 ; i < L.length; i++) {
if(L[i] > V[i-1] + L[i]) {
V[i] = L[i];
} else {
V[i] = V[i-1] + L[i];
if(V[i] > max) {
max = V[i];
}
}
}
return max;
}
Helpful Answer?
Yes | No
Inappropriate?
Feb 14, 2011
by Anonymous:
public void maximumSumSubsequence(int [] array){
int currentMaxSum = 0;
int startIndex = 0;
int maxSum = 0;
int maxStartIndex = 0, maxEndIndex = 0;
for (int i = 0; i < array.length; i++){
currentMaxSum += array[i];
if ( currentMaxSum >= maxSum ){
maxSum = currentMaxSum;
maxEndIndex = i;
maxStartIndex = startIndex;
}
if ( currentMaxSum < 0 ){
startIndex = i + 1;
currentMaxSum = 0;
}
}
System.out.println ("Current max sum " + maxSum );
System.out.println("current start index " + maxStartIndex);
System.out.println("End index " + maxEndIndex);
}
Helpful Answer?
Yes | No
Inappropriate?
Feb 15, 2011
by shawn:
The answer to this problem is the submaxarray algorithm. Find it here:
http://en.wikipedia.org/wiki/Maximum_subarray_problem
Helpful Answer?
Yes | No
Inappropriate?
=================}
Remove a node from a singly linkedlist without knowing the head node. All you have is the node itself.
if node is the last one, there no way to properly remove it, otherwise just copy next value and next->next pointer from the following node and delete next node
Helpful Answer?
Yes | No
Inappropriate?
4 of 4 people found this helpful
Nov 9, 2010
by Anonymous:
How about shifting all the contents/data of the node up one and deleting the last node?
ie, node->data = node->next->data, etc.
One issue I could see with this is if the nodes are being tracked any other way. If all the node pointers are in an array or something, it could become useless since their contents have changed.
Helpful Answer?
Yes | No
Inappropriate?
3 of 3 people found this helpful
Nov 14, 2010
by Anonymous:
boolean removeNode(Node * p){
Node * temp;
if (NULL == p){
return FALSE;
}
if (NULL == p.next) { // p is last element in list
free(p)
} else { // p is non-last element
temp = p.next;
p.value = temp.value;
p.next = temp.next;
free(temp);
}
return TRUE;
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Apr 16, 2011
by XX:
The above code has a bug. If p is the last element, and you free it, the element before it still points to this freed element, so when iterating through the list you'll access this freed memory while thinking there is valid data stored at that location.}}}}}}}}}}}}}}}}}}}}}}}}}}}}
=========================
It is a phone interview. Given a box of pencils with different colors, design an algorithm to find the duplicate pencils with the same color.
I didn't get the question at the first. I was thinking there was a box of box pencils and find the duplicated pencil. finally when I realized the question, the interview was at the very end...hash table works.
========================
You are given a text file too large to fit in memory and 3 strings A, B, C. For each string, you have a sorted array listing the positions of the string in the file (e.g., inverted indices). Find the smallest window containing the 3 strings. Order of appearance does not matter.
Answers & Comments (5)
0 of 6 people found this helpful
Nov 19, 2010
by Interview Candidate:
I have provided a solution using time O(sum of lengths of the arrays) and space O(1).
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Nov 27, 2010
by Arnab:
Maintain 3 position counters, one for each array. At every iteration, increment the counter of the array containing the minimum value.
This is a greedy algorithm that tries to minimize the distance between the 3 elements.
Helpful Answer?
Yes | No
Inappropriate?
Jan 20, 2011
by Anonymous:
@Arnab: I'm not sure if that will work. I think it will not work for cases like this
A = 1, 2, 1000000000
B = 3, 4, 5, 6, 7, 8
C = 9
Although I am curious if there is a solution that is better than O(n^2 logn). One way it could be solved is to compute all of the possible pairs between the 2 shortest lists (n^2). Then perform a binary search on the 3rd list (log n).
Helpful Answer?
Yes | No
Inappropriate?
Feb 13, 2011
by Anon:
Here is the naive implementation in Java. It is naive because it does not try to be efficient, it just iterates on all the possible combinations and returns the smallest distance. At least it works, it's better than nothing!
public class Test {
public static int[] findSmallestWindow(int[] a, int[] b, int[] c) {
int[] res = new int[3];
int window = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
for (int k = 0; k < c.length; k++) {
int[] sorted = sort3(a[i], b[j], c[k]);
int curWindow = sorted[2] - sorted[1];
if (curWindow < window) {
res[0] = i;
res[1] = j;
res[2] = k;
window = curWindow;
}
}
}
}
return res;
}
public static int[] sort3(int a, int b, int c) {
int[] res = new int[3];
if (a <= b) {
if (b <= c) {
res[0] = a;
res[1] = b;
res[2] = c;
} else {
if (a <= c) {
res[0] = a;
res[1] = c;
res[2] = b;
} else {
res[0] = c;
res[1] = a;
res[2] = b;
}
}
} else {
if (b <= c) {
if (a <= c) {
res[0] = b;
res[1] = a;
res[2] = c;
} else {
res[0] = b;
res[1] = c;
res[2] = a;
}
} else {
res[0] = c;
res[1] = b;
res[2] = a;
}
}
return res;
}
public static final void main(String[] av) {
int[] a = new int[] {1, 2, 1000000000};
int[] b = new int[] {3, 4, 5, 6, 7, 8};
int[] c = new int[] {9};
int[] res = findSmallestWindow(a, b, c);
System.out.println("Result: a[" + res[0] + "]=" + a[res[0]]
+ " b[" + res[1] + "]=" + b[res[1]]
+ " c[" + res[2] + "]=" + c[res[2]]);
System.out.println("");
}
}
Helpful Answer?
Yes | No
Inappropriate?
Mar 11, 2011
by Bart:
Here is a solution in O(|A| + |B| + |C|)
Let's call the 3 arrays: Aa, Ab, Ac
Consider having 3 cursors called Ca, Cb, Cc, one for each array.
In pseudo C++ :
int Ca = Cb = Cc = 0;
int bestWindow = INT_MAX;
int best[3] = {-1, -1, -1};
while(Ca < Aa.size() && Cb < Ab.size() && Cc < Ac.size()) {
// find max and min values amongst data pointed by cursors
int maxVal = max(Aa[Ca], max(Ab[Cb], Ab[Cc]));
int minVal = min(Aa[Ca], min(Ab[Cb], Ab[Cc]));
// if we found a better window update best window variables
if((maxVal - minVal) < bestWindow) {
bestWindow = maxVal - minVal;
best[0] = Ca; best[1] = Cb; best[2] = Cc;
}
// move the cursor pointing to smallest value
// This is actually not as trivial as it seems. If someone has a good idea I am interested.
// Here I don't provide the code.
Cx++;
}
}
============
1. Given a sorted array A[1..n] with n integers, and an integer t, find all pairs (x,y) of elements in A such that x+y is smaller than t. 2. Can we do better if we seek (x,y) for which x+y=t?
Answers & Comments (6)
0 of 2 people found this helpful
Nov 19, 2010
by Interview Candidate:
My solutions:
1. You can do that in time O(n log n) and O(1) space.
2. Yes, the cost can be reduced to O(n) time using O(n) additional space.
Helpful Answer?
Yes | No
Inappropriate?
4 of 4 people found this helpful
Nov 20, 2010
by lamont:
Suppose t is so large that all pairs x+y are smaller than t. If we are to find ALL pairs, then the size of the solution is O(n^2). It's going to take O(n^2) time just to generate the output:
for (i = 0; i < n - 1 && A[i] + A[i+1] < t; i++)
for (j = i + 1; j < n && A[i] + A[j] < t; j++)
printf("%d and %d sum to %d\n", A[i], A[j], t);
For the second question (x+y=t) you can put all elements of A into a hash table and then lookup t-x in O(n) time and space. Be careful to skip the case x+x=t unless x actually does appear twice in A.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Nov 21, 2010
by Anonymous:
Yeah, good point! Probably the question was to return the number of such pairs. Thanks for making me notice it.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 27, 2010
by Arnab:
The generalized version of this problem is worth studying: the Subset Sum problem which is recognized as being an NP complete decision problem: http://en.wikipedia.org/wiki/Subset_sum_problem
Helpful Answer?
Yes | No
Inappropriate?
Dec 21, 2010
by deveffort:
Array A[i...n]. t is the given value.
Create a hash of size t assuming t <= n and 1 < t.
Iterate the array to create a hash O(t) (t < n).
The key of the hash should be the value A[i] and value of the hash should be (t - A[i]).
Iterate again over the array again (which is O(t)).
Look up every key in hash matching the value of A[i]. Check if there is an existing key in the hash table which matches value of the A[i].
The hash lookups are constant time. The overall complexity is 2n.
Helpful Answer?
Yes | No
Inappropriate?
Nov 24, 2011
by mike:
for 2) there is no need for hashing because the array is already sorted. A simple solution in O(N) is achieved by having 2 pointers: one at the beginning and the other at the end of the array. Then at each step one of the pointers is increased/decreased
Array A[0..n-1], val t
i = 0 , j = n-1;
while (i < j ) {
x = A[i] + A[j];
if ( x == t )
// pair A[i], A[j]
else if ( x > t ) // x is too large, so decrease the largest value (A[j])
j--;
else // x is too small, so increase the smallest value (A[i])
i++;
}
=================
What's the difference between abstract and interface in Java
Answers & Comments (3)
Dec 5, 2010
by Anonymous:
An abstract class may have some functions already defined where as an interface will not have any function defined. The extending(implements) class must define every function declared in the interface. With Abstract class, the extending class may override some of the functions defined in the abstract class.
Helpful Answer?
Yes | No
Inappropriate?
Dec 13, 2010
by Anonymous:
Corrections to previous poster:
1. The extending class must define every function declared in te interface unless it is an abstract class
2. The extending class can extend multiple interfaces but only one class, abstract or not.
Helpful Answer?
Yes | No
Inappropriate?
Feb 8, 2011
by Osama Hamed:
The interviewer does not require you to give syntax related answers, instead:
1- In general, the interfaces are favoured over calsses.
2- However, we use abstract classes in cases we want to enforce some implementations in subclasess
Helpful Answer?
Yes | No
Inappropriate?
=====================
How would you sort an array of size N?
===================
Take an array of numbers and replace each item with the product of all the other items in the array.
Answers & Comments (5)
1 of 1 people found this helpful
Dec 9, 2010
by teo:
in JAVA
Instead of using two inner loops compute only the product for the first element.
Then the next products can be computed by dividing the previous product with the previous element and multiply by the current element. Complexity O(n) time O(n) space.
public int[] replace(int[] list){
int[] nlist = new int[list.length];
nlist[0] = list[1];
for(int i=2;i 0 ? product / numbers[i] : 0;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Apr 11, 2011
by Tumblidou:
Sorry, slight bug on the previous answer:
public void ReplaceIntsWithProductOfOtherInts(int[] numbers)
{
int product = 1, zeroIndex = -1;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == 0)
if (zeroIndex != -1)
product = 0;
else
zeroIndex = i;
else
product *= numbers[i];
}
for (int i = 0; i < numbers.Length; i++)
{
if (i == zeroIndex)
numbers[i] = product;
else if (zeroIndex != -1)
numbers[i] = 0;
else
numbers[i] = numbers[i] != 0 ? product / numbers[i] : 0;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this
===================
Create a Java class that receives a collection of collections as parameter and provides basic iterator functions, that is next() and hasNext(). The inner structure (collection of collections) must be hidden by the external interface. The next() method must thus iterate over all the elements of all the collections, starting with the next one if the current ends.
Answers & Comments (1)
Feb 13, 2011
by Anon:
public static class CollectionIterator implements Iterator {
private Iterator mMetaIt;
private Iterator mCurrentIt;
public CollectionIterator(Collection c) {
mMetaIt = c.iterator();
}
public boolean hasNext() {
if (mCurrentIt == null) {
if (!mMetaIt.hasNext()) {
return false;
}
mCurrentIt = ((Collection) mMetaIt.next()).iterator();
}
while (true) {
boolean hasNext = mCurrentIt.hasNext();
if (hasNext) {
return true;
}
if (!mMetaIt.hasNext()) {
return false;
}
mCurrentIt = ((Collection) mMetaIt.next()).iterator();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
public Object next() {
boolean hasNext = hasNext();
if (!hasNext) {
throw new NoSuchElementException();
}
return mCurrentIt.next();
}
}\\
=========================
An example questions was: If you had a days worth of queries, how would you sort the queries by the letter q, and then return a sufficiently random sample of 1000 queries. How do you ensure randomness?
=============
Reverse an sequence, or array
1. Swap elements from two ends till the middle element is reached.
2. Use an outer stack as buffer.
3. If the sequence is represented as a linked list, we can also manipulate the pointers of the nodes to reverse the direction.
===================
Design an algorithm, which can record the largest number in an ever-upgrading sequence.
Depending on the size of the sequence, how about:
1. If the sequence is small, just scan the sequence and return the largest number
2. If the sequence is large, use a max-heap (implemented as priority_queue in C++STL for example). After each element add, add the element also to the end of the heap and do 'max-HEAPIFY' on that node to maintain the max-heap property. After each element removal, move the last element of the heap to the removed node and do 'max-heapify" on that node also maintain the max-heap property. The largest number of the whole sequence is always the first/top element.
3. If the sequence is large, can also use a set (RB tree, std::set) to store all the elements, return the max element from the set.
I suspect #2 is what they expect, but just to make a point, if the sequence is really small, #1 can be better although it is dumb,
==================
Why am I meeting you?
I am a candiate for a software engineering position and I believe you are one of the interviewers in my interview loop.
=====================
How to choose pivot in quicksort
nswers & Comments (2)
Aug 30, 2010
by AnonJ:
In simple quicksort you use the first element as the pivot. In randomized quicksort, you pick an element at random and swap it to the beinning of the array.
Helpful Answer?
Yes | No
Inappropriate?
Nov 16, 2010
by Anonymous:
median of 3: take first, middle and last element; choose median among these - ensures you never choose the smallest or largest element as your pivot (i.e., make progress on each quicksort iteration).
==============
How to efficiently sort a pivoted array
Answers & Comments (2)
Sep 25, 2010
by Alan:
Array is already sorted so
1) find the pivot point (use modified binary search)
2) since it is a array, block copy data using temporary buffer to reconstruct the sorted array
Helpful Answer?
Yes | No
Inappropriate?
Oct 21, 2010
by BDutta:
1. Find the pivot.
2. Reverse the left side until the pivot.
3. Reverse the right side after pivot.
4. Reverser the whole array.
No need for extra storage and it's still O(n).
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on t
==================
Reverse a linked list in place
Answers & Comments (4)
0 of 3 people found this helpful
Aug 26, 2010
by Anonymous:
How did you get the result of you interview? Did they call you or mail you? How much time it takes for the result to come?
Helpful Answer?
Yes | No
Inappropriate?
Aug 30, 2010
by AnonJ:
Pseudocode
reverselist(head):
currhead=head;
next1=curr->next;
while(next1!=null):
tmp=next1->next;
next1->next=currhead;
currhead=next1;
next1=tmp
return currhead;
Helpful Answer?
Yes | No
Inappropriate?
Aug 30, 2010
by Maxi:
You forgot to make NULL at the end of new list. You should add currhead->next=null before the loop.
Helpful Answer?
Yes | No
Inappropriate?
Oct 7, 2010
by xamdam:
#include "stdafx.h"
#include
#include
struct LNode
{
char val;
LNode* next;
};
LNode* make_list(const std::string& s)
{
LNode* root = 0;
LNode* last = 0;
for(std::string::const_iterator it=s.begin();it!=s.end();++it)
{
LNode* n = new LNode();
n->val = *it;
if(!root)
{
root = n;
}
else last->next = n;
last = n;
}
return root;
}
LNode* reverse(LNode* node, LNode* next = 0)
{
if(!node->next)// last node
{
node->next = next;
return node;
}
LNode* reversed = reverse(node->next, node);
node->next = next;
return reversed;
}
LNode* reverse1(LNode* root)
{
LNode* front = 0;
LNode* cur = root;
LNode* nxtcur = 0;
while(cur)
{
nxtcur = cur->next;
cur->next = front;
front = cur;
cur = nxtcur;
}
return front;
}
int _tmain(int argc, _TCHAR* argv[])
{
LNode* node = make_list("test list");
node = reverse(node);
while(node)
{
std::cout<val;
node=node->next;
}
std::cout<<:endl node='make_list("test' list1 while std::cout>val;
node=node->next;
}
std::cout<<:endl return given a search terms find the minimum window containing all words answers comments of people found this helpful aug by interview candidate: had general idea but could not elaborate answer. i knew it can be done in linear time get to code it. answer yes no inappropriate santos: is dyn programming least common subsequence problem apr anon: think following will work. say there are three w1 w2 w3 we care about which occur as part sequence a0 a1 .... an among other well. maintain indices i1 i2 i3. if word ak equals update and likewise or then i3 with value k. don any these none interested in. for every k having max min that each were already encountered at once now so just keep track expression when iterating through algorithm o members comment on question join free sign web system gets disconnected how would you debug also where add resources maximise throughput some constraints.="================" grid contains rectangles write function overlap other. sep anonymous: reduce connected components undirected graph use dfs solve rectangle means nodes overlapping edges. jan victor: too expansive build graph. looping vertices vertex represented why set flag those have degree> 0?
Building some kind of segment tree in O(n log n) is the solution I guess. In each node of the tree put a rectangle (given by the left-top and the right-bottom points). If the x-coordinate is greater or equal than the one of the current node, then put in the right; otherwise in the left side. When search, it will take O(log n) for each node.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jan 17, 2011
by Victor:
Using some kind of interval tree:
public class OverlappingRectangles
{
public static int max(int a, int b)
{
return a < b ? b : a;
}
public static RectangleNode add(RectangleNode root, Point top, Point bottom, Vector vector)
{
if(root == null)
{
RectangleNode rn = new RectangleNode(top, bottom);
vector.add(rn);
return rn;
}
if(top.x < root.top.x)
{
root.left = add(root.left,top,bottom,vector);
root.maxX = max(root.maxX, root.left.maxX);
root.maxY = max(root.maxY, root.left.maxY);
}
else
{
root.right = add(root.right,top,bottom,vector);
root.maxX = max(root.maxX, root.right.maxX);
root.maxY = max(root.maxY, root.right.maxY);
}
return root;
}
public static void solve(int[] topx, int[] topy, int[] bottomx, int[] bottomy)
{
RectangleNode root = null;
Vector vector = new Vector();
for(int i = 0; i < topx.length; i++)
{
root = add(root, new Point(topx[i],topy[i]), new Point(bottomx[i],bottomy[i]),vector);
}
for(int i = 0; i < vector.size(); i++)
{
vector.get(i).active = false;
System.out.println(search(root,vector.get(i).top,vector.get(i).bottom));
vector.get(i).active = true;
}
}
public static boolean search(RectangleNode root, Point top, Point bottom)
{
RectangleNode index = root;
RectangleNode look = new RectangleNode(top, bottom);
while(index != null && (
!index.overlaps(look)
|| !index.active
))
{
if(index.left != null && (index.left.maxX >= top.x || index.left.maxY >= top.y))
{
index = index.left;
}
else
{
index = index.right;
}
}
if(index != null)
return true;
return false;
}
public static void main(String[] args) {
int[] a = {0,1,6};
int[] b = {0,1,7};
int[] c = {3,4,8};
int[] d = {3,5,9};
solve(a,b,c,d);
}
}
class RectangleNode implements Comparable
{
public Point top;
public Point bottom;
public int maxX;
public int maxY;
public boolean active = true;
public RectangleNode left, right;
public RectangleNode(Point top, Point bottom)
{
this.top = top;
this.bottom = bottom;
this.maxX = bottom.x;
this.maxY = bottom.y;
}
@Override
public int compareTo(RectangleNode o)
{
return top.x < o.top.x ? -1 : (top.x > o.top.x ? 1 : 0);
}
public boolean overlaps(RectangleNode o)
{
if(
(top.x >= o.top.x && top.x <= o.bottom.x && top.y >= o.top.y && top.y <= o.bottom.y)
|| (o.top.x >= top.x && o.top.x <= bottom.x && o.top.y >= top.y && o.top.y <= bottom.y)
)
return true;
return false;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Feb 3, 2011
by â³â³â³â³â³â³â³â³
This post has bee}}}
===============
Initial Question Write a function in your language of choice to check if a given string matches a given pattern as a non-contiguous substring: that is, all the characters in the pattern appear in the text string in the same order, but possibly not all in a row. (eg: pwdp matches passwordparser.h and pwdafterpepper.cc) Continuation: How can this be made more efficient (so as you add to the search string, you don't have to redo the whole problem)? Continuation 2: How could results be sorted by relevance?
Answers & Comments (1)
1 of 1 people found this helpful
Aug 8, 2010
by Interview Candidate:
For the initial match, just iterate through characters of the string. If the character matches the current character of the substring, then advance to the next character of the substring at the same time.
For the continuation, use a class to keep track of the last matched character (so when you add a character to the substring, you can start searching from the end of the current match)
For relevance, first sort by the number of "gaps" in the string (less is better). Then, sort by the number of characters skipped during the gaps (less is better). Finally, sort by length of string (shorter is better).
==============
Write a function to return if a number is a palindrome (eg, 113848311)
Add Tags [?]
See more for this Google Software Engineer Interview
Helpful Question?
Yes | No
Inappropriate? Facebook
Looking for a job? See featured jobs below or try Jobs in Istanbul
Software Engineer - C++ Developer â new
VMware â Pleasant Grove, UT
From VMware â 2 days ago
Software Development Engineer
Autodesk â Pune (India)
From Autodesk â 21 days ago
Answers & Comments (3)
0 of 1 people found this helpful
Aug 8, 2010
by Interview Candidate:
Count the digits, loop inwards from the outside edges to the center.
Helpful Answer?
Yes | No
Inappropriate?
Nov 28, 2011
by Alec:
bool isPaldrome(int n) {
int r = 0;
for (int num = n; num; num /= 10)
r = r * 10 + (num % 10);
return r == n;
}
Helpful Answer?
Yes | No
Inappropriate?
Nov 28, 2011
by Alec:
Explanation: Make another int variable that adds to the end what gets knocked off the input int. Then just return if they match. Sample program flow for 12321 would be:
12321, 0
1232, 1
123, 12
12, 123
1, 1232
0, 12321
================
Write a function to return the number with the longest collatz sequence in a given range: int longestCollatz(int lower, int upper);
Answers & Comments (3)
Aug 8, 2010
by Interview Candidate:
Wikipedia was allowed:
http://en.wikipedia.org/wiki/Collatz_conjecture
Code is simple. Wrote a recursive function to calculate the length of a given sequence, called it for each number in the range.
Helpful Answer?
Yes | No
Inappropriate?
Aug 11, 2010
by interviewee:
this was for a phone interview ? first or second ?
Helpful Answer?
Yes | No
Inappropriate?
Nov 20, 2010
by interviewee:
An optimization is having a cache for already calculate sequence lengths. this is a good idea because whenever you reach the same number the sequence is going to look the same from that point on. In other works, the problems share many common subproblems from which you can reuse solutions.
==================
How would you implement Google spelling correction algorithms?
What about keeping a dictionary of all words in all acceptable spellings. Then hashing all the words to create a list of valid hashes to link to matching words. Every time one finishes to type a word, the hash of the new word would be found in the dictionary, then the word match confirmed.
=============
Suppose you have an arbitrarily connected graph with n nodes. Come up with an algorithm to identify each set of connected nodes (i.e. identify all the islands in the graph). What's the complexity? Can you find a solution in O(n log n)?
Answers & Comments (5)
Aug 12, 2010
by Anonymous:
Make each node a class with a list of it's connecting nodes. Add every node to a doubly linked list. Call this list "main" The node should have the list pointers in it (prev and next).
Now iterate through the list:
Get a node and add all of it's neighbors that are still in the main list (prev and next are not null) to a new list called "curNodes". Then remove that node from the "curNodes" and add it to a new list of lists of nodes called islands. Also remove this node and it's connecting nodes from the list main. Repeat until there are no more nodes in "curNodes"
Continue to the next node in "main"
I believe this runs in O(n) time.
The problem with this algorithm is that it involves a lot of memory allocation for making the lists. Also the interviewer may not be happy with having the nodes in a doubly linked list and could perhaps set up the problem for you differently (i.e. connections are in a matrix). If he doesn't like a doubly linked list for main. That's ok. You could remove nodes from main by setting them to null and then you just have to skip past the null nodes on your way to the next node. However I believe this counts as O(nlogn) then, because your iterating through dead nodes technically, I'm not sure. As for the connecting nodes being set up in a matrix, that would probably require a different solution which I may post later if I think of a good answer...
Helpful Answer?
Yes | No
Inappropriate?
Aug 12, 2010
by Anonymous:
I believe the above algorithm is O(n^2) complexity. In a fully connected graph, each of the n nodes requires n operations (checks).
Helpful Answer?
Yes | No
Inappropriate?
4 of 4 people found this helpful
Aug 14, 2010
by Anonymous:
First of all, it's not clear what the "n" in O(nlogn) is referring to: is it the number of vertices or the number of edges?
Anyway, the standard algorithm for connected components is to run a DFS on the graph starting at an arbitrary node. Each DFS tree represents a connected component. This takes O(V + E) time.
If the graph is directed, you need to find *strongly connected components*. To do this, do a DFS on graph G, as well as a DFS on a graph G' which is just G with the edges reversed.
Also O(V + E) time.
Helpful Answer?
Yes | No
Inappropriate?
Aug 16, 2010
by Anonymous:
Add each node into a set. Call make_set(i) on node i belongs to V
Then examine each edge, If edge (u,v) if u and v belong to different set then merge the two sets and so on
complexity = O(mlogn) m=no of edges n= no of nodes
Helpful Answer?
Yes | No
Inappropriate?
Sep 1, 2010
by Anonymous:
Is it directed graph?
============================
Reverse bits of a digit
int reverse(int x)
{
x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
x = ((x & 0x33) >> 2) | ((x & 0xCC) << 2);
x = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);
return x;
}
}
================================
You have all of the prices for a given stock for the next year. You can buy once and sell once in that year. How do you determine when to buy and sell to maximize your profit?
Answers & Comments (11)
2 of 2 people found this helpful
Aug 6, 2010
by gaurav:
Assuming the prices are sorted on their dates
1. start from the last entry (i.e price on the last date)
make it as selling price.
2. From last but one entry to first entry
{
if price > sell price
sell price = that price
else
{
diff = sell price - price;
if diff > max then max = diff;
}
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Aug 6, 2010
by Anonymous:
gaurav your answer is not correct if you can only sell after buying. assume you have this prices
1 99 100 10 50
In this case, the optimal answer would be buy at 1 and sell at 50, but your algorithm cannot find that answer.
This problem can be solved transforming the input and executing the so called maximum-subarray-algorithm
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 6, 2010
by @Anonymous, by Gaurav:
Wont the optimal answer be buy at 1 and sell at 100? The profit in this case is 99, where as in ur case its 50(buy @ 1 and sell @ 50, the profit is 49). So I will choose to buy at 1 and sell at 100. Any way,
1. set sell price at last entry = 50(lets call sell price as sp), set profit = lowest possible value
2. then set i = last but one entry = 3 (ie index of 10)
3. array[i] < sp so diff = sp - array[i] (50 - 10) = 40,
diff > profit so profit = diff = 40
i--
4. i = 2
array[i] > sp, so sp = 100
i--
5. i = 1
arrayi] < sp, so diff = sp - array[i] (which is 100 - 99 = 1)
since profit(=40)> diff, we dont change the profit value
i --;
6. i = 0;
array[i] < sp so diff = sp - array[i] (which is 100 - 1 = 99)
diff(=99) > profit(40) so set profit = diff
END OF LOOP
ans = profit = 99.
Hope this helps u
Helpful Answer?
Yes | No
Inappropriate?
Aug 15, 2010
by cagatay:
current min , current max = first price
keep track current min , current max, iterate
when you find something smaller than current min
record if diff is the best diff
set current min current max to this price and iterate.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Sep 11, 2010
by Jordan:
Outside the box: just find the minimum/maximum. If the minimum is before the maximum, buy it and sell it as usual. If the minimum is after the maximum, short it and buy it back later.
Helpful Answer?
Yes | No
Inappropriate?
Sep 28, 2010
by Anonymous:
void printBuySell(int[] l) {
int maxDiff = 0, maxStart = 0, maxEnd = 0;
int start = 0, end = 0;
for (int i = 1; i < l.length; i++) {
if (l[i] < l[start]) {
int diff = l[end] - l[start];
if (diff > maxDiff) {
maxStart = start;
maxEnd = end;
maxDiff = diff;
}
start = i;
end = i;
}else {
if (l[i] > l[end])
end = i;
}
}
System.out.println(l[maxStart] + " " + l[maxEnd]);
}
Helpful Answer?
Yes | No
Inappropriate?
Oct 6, 2010
by xamdam:
def buy_low_sell_high(prices):
return max((prices[j]-prices[i], i, j) for i in range(len(prices)) for j in range(i+1, len(prices)))
# go python!
Helpful Answer?
Yes | No
Inappropriate?
Nov 18, 2010
by Bhaskar:
I agree with Jordan's answer...
Find the (max,min) from the price list.
If "min" occurs earlier than "max" => buy at instant "min" occurs and sell at "max"
If "max" occurs earlier than "min" => sell at instant "max" and buy back at "min"
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Nov 24, 2010
by Jacob:
The question is equivalent to the following problem:
Find a sequence with max sum in an array of negative and positive real numbers s.t the numbers in this case are the delta between two consecutive prices.
Helpful Answer?
Yes | No
Inappropriate?
Jan 20, 2011
by foo:
Its the maximum subsequence problem where the new array is the deltas of the stock prices every day.
Helpful Answer?
Yes | No
Inappropriate?
Oct 13, 2011
by highway_star:
To add to what Jacob said above:
1. List out the stock prices at discrete intervals
2. Compute the cumulative sums
3. Start two pointers: an "explorer", and a "stabilizer" at node 0.
4. Find the largest "up tick" using the foll. algorithm:
a) Move the explorer ahead of the stabilizer. Compute the delta; if the delta is larger than the stored delta, update your 'maximum delta'.
b) move stabilizer to the right only if that takes it to a lower value.
c) move explorer to the right till it reaches a higher value.
d) when either b) or c) are true, compute a new delta and compare to your saved away maximum
When stabilizer reaches the right most node, you're done.
============================
Write a method that finds depth of a (non-balanced) binary tree.
Answers & Comments (3)
Jul 27, 2010
by Interview Candidate:
One way is to record each node's depth as it is added in a separate field, implementing it as node.parent.depth() + 1. Then keep track of the max.
Alternatively, do a BFS traversal, incrementing depth of each node every time its parent is selected. Store those depths in a queue; the last element is the overall tree depth. Not pretty, but it should work.
Helpful Answer?
Yes | No
Inappropriate?
3 of 3 people found this helpful
Jul 29, 2010
by Anonymous:
Want an elegant solution? Here it goes.
class Node {
Node left;
Node right;
// other data members relevant to node, e.g. element.
// constructors, getter/setters, etc.
}
class BinaryTree {
Node root;
int height() {
calcDepth(root);
}
}
int calcDepth(Node N) {
if (N == null) return 0;
return Math.max(calcDepth(N.left)+1,calcDepth(N.right)+1);
}
calcDepth is the method that computes the depth (or height) of a tree.
Helpful Answer?
Yes | No
Inappropriate?
Jul 29, 2010
by Anonymous:
Very nice, but I doubt Google generally takes kindly to recursive solutions.
=}}}
=================
Given unsorted sequence of billions of numbers that cannot all fit in memory at the same time, find the median of these values.
Answers & Comments (3)
0 of 2 people found this helpful
Jul 27, 2010
by Interview Candidate:
Feel free to take a stab at this one.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Aug 6, 2010
by gaurav:
This link points to a nice ppt:
http://www.google.com/url?sa=t&source=web&cd=3&ved=0CCMQFjAC&url=http%3A%2F%2Franger.uta.edu%2F~gdas%2FCourses%2FFall2004%2FadvAlgos%2Fstudent_slides%2FW6Presentation.ppt&ei=yKZcTJ6iG5OgsQOj9aAn&usg=AFQjCNHC5V6faOYf8vHe4E6DhHiEqJVRog&sig2=t_gyNN7hr2yhBp4CSEEIeg
Helpful Answer?
Yes | No
Inappropriate?
Sep 12, 2010
by Anonymous:
An approximate method: estimate an empirical probability distribution from a bunch of randomly sampled numbers from the big list, then compute the median of the distribution.
=======================================
Implement a method that matches an entire string with star wildcard pattern, e.g. returns true for ("*ogle", "Google"), but false for ("fragile*", "agile") - without using regular expression language support.
Following code should resolve the problem:
Consider that there can be only one '*' symbol in first pattern string
boolean match (String a, String b) {
boolean match = true;
if(!a.contains("*")) {
return a.equals(b);
} else {
String prefix = a.substring(0, a.indexOf('*'));
String suffix = a.substring(a.indexOf('*')+1);
if (StringUtils.isNotEmpty(prefix) && !b.startsWith(prefix)) {
match = false;
}
if (StringUtils.isNotEmpty(suffix) && !b.endsWith(suffix)) {
match = false;
}
}
return match;
}
none of used class String methods use regular expression language support
===================
How do you efficiently reverse the order of the words in a string?
Answers & Comments (2)
1 of 1 people found this helpful
Jul 29, 2010
by Anonymous:
Just need to polish the boundary cases, but the main algorithm is basically this. Runs in O(n), where n is the number of characters in the string.
reverseWords(String phrase) {
char[] array = phrase.toCharArray();
reverse(array, 0, array.length);
int i = 0, j = 0;
while (i < array.length) {
while (i < array.length && Char.isWhiteSpace(array[i])) i++;
j=i;
while (j < array.length && !Char.isWhiteSpace(array[j])) j++;
reverse(array,i,j-1);
}
}
reverse(char[] array, int j, int k) {
for (int i = 0 ; i < (k-j)/2 ; i++)
swap(array, j+i, k-i);
}
swap(char[] array, int j, int k) {
char swap = array[j];
array[j] = array[k];
array[k] = swap;
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Aug 11, 2010
by alex:
I would have to ask for the criteria of efficiency (number of operations? memory utilization?). I'd push the sentence into a stack word by word, then construct a new string by popping words from a stack....but is it efficient? depends on the criteria, right?
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this question â Join Now (It's Free) or Sign In
}}}
======================
Design the back-end for facebook.
This was really the only interesting challenge, as it was open-ended. We wound up talking mostly about the scalability challenges.
==========================
Give the descending order of the following 4 terms, assume that n is infinite. n!(n factorial), n^n, 2^n, n^(google)
Answers & Comments (2)
2 of 3 people found this helpful
Jul 23, 2010
by Interview Candidate:
I think the order is n^n>n!>2^n>n^(google)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 7, 2010
by Bartosz Milewski:
I assume n is finite but very large. The first three are easy, from smallest to largest:
1. 2^n is a product of n twos
2. n! is also a product of n numbers which, except for one, are all >= 2. The largest is n.
3. n^n is also a product of n numbers, all of them equal to n
What about n^googol. Googol is a humonguos number (10^100). So n^G is a product of a humongous number of n's. But if n itself is much larger than googol than both n! and n^n beat it. The tricky one is 2^n. How much does 2^n increase when you increase n by 1? It doubles. How much does n^G increase? You have to divide (n +1)^G / n^G. The numerator is a binomial: n^G + (G 1)*n^(G-1) + ... 1. Division gives us 1 + (G 1)* n^(-1) + ... n^(-G). For large n the sum after 1 gets tinier and tinier (like 1/n), so in fact 2^n beats n^googol.
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this question â Join Now (It's Free) or Sign In
==============================================
Convert decimal number 99 to base 7.
Uh, I think you meant 201 - perhaps this is why you didn't get the job.
99 = 2 * 7 * 7 + 1 = 2 * 7 ^ 2 + 0 * 7 ^ 1 + 1 * 7 ^ 0 = 201
Here's the code that does this in general:
String convertToBase(int num, int radix)
{
StringBuilder sb = new StringBuilder();
int n = num / radix;
int lsd = num % radix;
do
{
sb.insert(0, lsd);
lsd = n % radix;
n /= radix;
}
while (n > 0);
sb.insert(0, lsd);
return sb.toString();
}
Helpful Answer?
Yes | No
Inappropriate?
May 3, 2011
by dantepy:
convert(n, r)
if (n than the key, do the binary search between 1 and 1024. If it's less keep doubling your number (2048, ...).
If at any point we overshoot the end of dictionary, we have to reduce the last segment. This depends of how the dictionary responds to an overshoot--it might give us the end of dictionary, or some other signal. In the latter case we continue halving the last segment.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Oct 22, 2010
by Anonymous:
In an unbounded dictionary, words probably are not sorted.
Helpful Answer?
Yes | No
Inappropriate?
Apr 18, 2011
by Anon:
To reply to the above, by "unbounded" here it is probably meant "very large, and with unknown size". As such, it can be sorted. First poster is correct.
===========================
a. Given a function double f(double x), 0<=x<=1, f(x) is increasing. f(0)<0, f(1)>0. Find x s.t. f(x)\approx 0.
Answers & Comments (4)
Jul 12, 2010
by Interview Candidate:
Just be careful that x is discrete
Helpful Answer?
Yes | No
Inappropriate?
Jul 16, 2010
by Steve M:
double min = 0.0;
double max = 1.0;
double x = 0.0;
double y = 0.0;
for(;;)
{
// mean calculation could be optimized
// depending on what we think we are dealing with
x = (min + max) / 2.0;
y = f(x);
if ( (y > -0.001) && (y < 0.001) )
break;
if ( y >= 0.001 ) // too high
max = x;
else // too low
min = x;
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 16, 2010
by Ryan:
Use bineary search.
#define ZERO 0.00001
double find() {
double low = 0.;
double high = 1.;
while (true) {
double mid = (low + high) / 2;
double val = f(mid);
if (val > ZERO)
high = mid;
else if (val < -ZERO)
low = mid;
else
return mid;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Aug 5, 2011
by Vagrant:
Silly people. Just use Newton's Method:
double funcTest(double x) {
return exp(x)-2;
}
double root(double (*f)(double)) {
double x=1.0;
while (true) {
double dy = (f(x)-f(x-0.01))/0.01;
x = x - f(x)/dy;
double y = f(x);
if (fabs(y)<0.01) break;
}
return x;
}}}}}}}}
===================================
What is the fastest way to sort 1 million integers when integers are from the range [1,100]?
Answers & Comments (5)
1 of 2 people found this helpful
Jul 12, 2010
by somebody:
Bucketsort (used only when you know the range of your input, and the range is reasonably sized)
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2010
by Steve M:
Counting sort (also known as math sort).
Helpful Answer?
Yes | No
Inappropriate?
Jul 16, 2010
by Ryan:
Use bitmap.
void sort(int[] ints) {
// Initialize an array of 100 ints
int[] buff = new int[100];
for (int i = 0; i < buff.length; i++)
buff[i] = 0;
// Scan the input ints once, count them.
// Cost: O(N)
for (int i = 0; i < ints.length; i++)
buff[i]++;
// Output the sorted ints
// Cost: O(N)
for (int value = 0, i = 0; value < buff.length; value++) {
for (int j = 0; j < buff[value]; j++)
ints[i] = value;
}
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 17, 2010
by Daniel:
None of the above. You should use radix sorting, where r=100.
Helpful Answer?
Yes | No
Inappropriate?
Jul 27, 2010
by Anonymous:
Is this some sort of trick question? If not, then set up an array like this:
int [] sorted = new int[100];
Now iterate over the input number sequence, placing values into their respective array elements, i.e. let N be the number, then:
if (N > 100 || N < 1) continue;
sorted[N-1] = N;
After processing the input:
ArrayDeque gapless = new ArrayDeque(sorted.length);
for (int i: sorted)
{
if (i > 0) gapless.add(i);
}
return gapless;
Complexity is now O(n). Am I missing something here?
}
===================
Imagine dropping a Rubik's Cube into a bucket of paint. How many of the cubes will get paint on them?
Answers & Comments (7)
0 of 1 people found this helpful
Jul 12, 2010
by Keith:
20, 8 corners, 8 middle edges, 4 centers. the cube in the middle does not get painted.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 13, 2010
by James:
26, or all of them. since the rubik's cube is as a 3x3 and the core is basically none existent, this is only if all the individual cubes are actually cubes. but since each individual piece is not actually a cube, but a puzzle piece that is cube like, you can technically say 1 cube gets paint on it. the whole rubik's cube
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Jul 13, 2010
by Steve M:
26: 8 corners, 12 middle edges, 6 centers. middle cube does not get paint. 3x3x3-1
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2010
by Charles:
OK, now what's the answer for a 4x4x4 cube? What about the general nxnxn case?
Helpful Answer?
Yes | No
Inappropriate?
5 of 5 people found this helpful
Jul 13, 2010
by Steve M:
total number of cubes - number of cubes in the middle
= N x N x N - ( (N - 2) x (N - 2) x (N - 2) )
= N^3 - (N-2)^3
for a 4x4x4 cube:
4^3 - 2^3
= 64 total number of cubes - 8 cubes in the middle
= 56
Helpful Answer?
Yes | No
Inappropriate?
0 of 3 people found this helpful
Jul 14, 2010
by Doug:
Zero. Neither the rubik's cube nor any of its components is actually a cube.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 31, 2010
by Scott:
Have any of you people ever disassembled a Rubik's cube? There are no cubes on the inside, just the assembly to hold and manipulate the exterior together.
====================================
Writing the code to convert numeric amount of price into English words.
Answers & Comments (3)
Jul 1, 2010
by Interview Candidate:
You should code a module with a data structure that will contains invariant conversion. The module should contain parse the number and map into the data structure in a way of separating units (e.g., thousand, hundred, cents) while considering any exceptions.
Helpful Answer?
Yes | No
Inappropriate?
Jul 5, 2010
by Anonymous:
I would use 2 string arrays. The first array contains an empty string for a 0 placeholder, then "one"-"nineteen". The second contains empty string then the tens strings to "ninety". The function consumes a double, uses floor and ceil to separate dollars from cents, then uses a switch statement to index the arrays. From there you can do what you want to format the strings, and I might use recursion, but Google might not like that.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 13, 2010
by Steve M:
char *basics[] = {
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
};
char *tens[] = {
"zero",
"ten",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
};
// [0-99]
char *basic(char *buf, int n)
{
if (n <= 19)
return basics[n];
strcpy(buf, tens[n/10]);
if (n%10)
sprintf(buf, "%s %s", buf, basics[n%10]);
return buf;
}
void printPrice(double price)
{
int N = (int) price; // dollars
int M = 100 * (price + 0.005 - (double)N); // cents
// extracting the different parts
int num_million_thousand = N / (1000000 * 1000);
N -= num_million_thousand * (1000000 * 1000);
int num_million_hundred = N / (1000000 * 100);
N -= num_million_hundred * (1000000 * 100);
int num_million_basic = N / 1000000;
N -= num_million_basic * 1000000;
int num_thousand_hundred = N / (1000 * 100);
N -= num_thousand_hundred * (1000 * 100);
int num_thousand = N / 1000;
N -= num_thousand * 1000;
int num_hundred = N / 100;
N -= num_hundred * 100;
int num_basic = N;
// printing the different parts
char buff[81] = "";
if (num_million_thousand)
printf(" %s thousand", basic(buff, num_million_thousand));
if (num_million_hundred)
printf(" %s hundred", basic(buff, num_million_hundred));
if (num_million_basic)
printf(" %s", basic(buff, num_million_basic));
if ((int)price / 1000000)
printf(" million");
if (num_thousand_hundred)
printf(" %s hundred", basic(buff, num_thousand_hundred));
if (num_thousand)
printf(" %s thousand", basic(buff, num_thousand));
if (num_hundred)
printf(" %s hundred", basic(buff, num_hundred));
if (num_basic && ((int)price / 10) || !((int)price / 10))
printf(" %s", basic(buff, num_basic));
printf(" dollars %s cents", basic(buff, M));
}}}}}}}}
=============================
How would you count the frequency of letters in a word/ file?
=======================
finding the biggest sum of subset in an int array.
Answers & Comments (4)
Jul 16, 2010
by somebody:
What are the specifics to this question? Are we asked to find the subset with number of elements k from a superset of size n, that has the largest sum? ... should just sort the set and sum the largest k elements. O(whatever you choose, if you know the range and its small, counting sort, otherwise nlogn)
Helpful Answer?
Yes | No
Inappropriate?
Oct 23, 2010
by Anonymous:
No sorting, it takes O(n) time.
Helpful Answer?
Yes | No
Inappropriate?
Jan 18, 2011
by Victor:
Just iterate through the array and add positive numbers to the sum. I don't think this was the problem..
Helpful Answer?
Yes | No
Inappropriate?
Jan 30, 2011
by Salaam Bombay:
Iterate through the subset once and find the two biggest numbers. Add them to get your answer
==================
Implement Queue based on a stack
Answers & Comments (2)
Jul 16, 2010
by somebody:
Do insertions need to be the same running time? Off the top of my head, I would say once insertions to the queue are finished, pop everything off of stack A and push onto stack B. To remove from the queue, pop from stack B. To insert to the queue, pop everything off of stack B, push onto A, push the new insertion onto A, then move everything back to B.
Helpful Answer?
Yes | No
Inappropriate?
Jul 16, 2010
by somebody:
That means insertions are no longer O(1), but O(n).
======================
Calculate the nth number of the fibonacci series
Answers & Comments (5)
Jun 26, 2010
by Interview Candidate:
do not use recursion
Helpful Answer?
Yes | No
Inappropriate?
Jul 5, 2010
by Anonymous:
double fibonacci(double n){
double x = 0;
double y = 1;
double c = 0;
double temp = 2;
while(temp currMax) {
// I have found the local optimized solution, so save the how much I'll be making
currMax = A[i] - A[ V[i-1] ];
// save the buy and sell dates
buyIndex = i;
sellIndex = V[i-1];
}
// update the minimum value seen up to this day
if(A[ V[i-1] ] < A[i]) {
V[i] = A[i];
} else {
V[i] = V[i-1];
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 24, 2011
by WheezardX:
Given the complexities of the answers above, I'm not sure I understand the question. Here is my answer as I understand the question.
void FindSellDates (const float prices[], int size) {
int minIndex = 0;
int maxIndex = 0;
float minPrice = (float)HUGE_VAL;
float maxPrice = -(float)HUGE_VAL;
for (int index = 1; index < size; index==) {
if (prices[index] > maxPrice) {
maxIndex = index;
maxPrice = prices[index];
}
else if (prices[index] = minPrice) {
minIndex = index;
minPrice = prices[index];
}
// MinIndex == Buy Date.
// MaxIndex == Sell Date.
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 27, 2011
by Anonymous:
@WheezardX
I think Viet is assuming that you cannot sell before you buy. Your solution suggests that you are trying to find the minimum and maximum values for the whole dataset, which could potentially end up in a situation where you attempt to sell before you buy (e.g. 9, 1, 2, 3). Viet's solution is trying to find the minimum values for days BEFORE a certain buy date. His solution is using dynamic programming.
Helpful Answer?
Yes | No
Inappropriate?
Feb 20, 2011
by NehaGupta:
It looks strange to me but I thing I can do it in linear ...
9 1 2 3 4 6 1 5 7 9
Approach : Get Min Till Today, sell it today. Get Diff. If Diff is greater than max diff then update dates.
buyIndex = 0
sellIndex=1
GlobalMax = 0
MinIndex =0
A[]={9, 1 ,2 ,3 ,4 ,6 ,1 ,5 ,7 ,9}
for(i=0;i<10;i++)
{
if(A[i]-A[MinIndex]>GlobalMax)
{
buyIndex=MinIndex;
sellIndex = i;
}
if(A[MinIndex]>A[i])
{
MinIndex = i;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Apr 7, 2011
by mattie:
Understandably there are two completely different answers, depending on how you understand the question. Better ask the interview to clarify the question by giving an actual buy/sell scenario. That would make it fairer, wouldn't it.
}}}
=======================
words are given to you in "alphabetical" order (this is not the same as the usual a, b, c, d, ... order) find that order
It depends if you are able to find or not that order.
E.g.: B A C, B L D, A S C, AS L, then you only know that b < a < l but also that c < l but nothing about a, c or b ,c.
====================
What are the complexity characteristics of all the operations that you can perform on the data structures that you can think of?
========================
Check two leafs of graph connected or not, how we can optimize algo
Answers & Comments (4)
1 of 1 people found this helpful
Feb 20, 2011
by NehaGupta:
-This is NP problem
-Starting node 1 , do a bfs if you hit node 2 then connected else not.
Helpful Answer?
Yes | No
Inappropriate?
May 27, 2011
by Lucy:
what does bfs stand for?
Helpful Answer?
Yes | No
Inappropriate?
Jun 30, 2011
by Saurabh:
bfs = breadth first search.
Helpful Answer?
Yes | No
Inappropriate?
Nov 24, 2011
by mike:
this was probably a tree and not a graph (question mentions leaf and not vertex). it would make more sense because that way you could start with a dfs/bfs and then improve to a LCA (lowest common ancestor)
=================================
Given a number N and a very large file containing natural numbers, find the N minimum numbers in this file.
Given a number N and a very large file containing natural numbers, find the N minimum numbers in this file.
You can use a max-heap of size N.
Initialize it with the first N numbers. Then when a new number x is read, check if x is less than the maximum number from heap. If so, remove the max, and insert x in max-heap. This operation takes O(log N) as time.
Afterwards, the entire algorithm is O( m * logN), where m is the size of the big array.
==============================
How to build a distributed algorithm to compute the balance of the parathenses?
===============================================
write a string splitting function that did not copy the string
==============================================
Design the Twitter.
===============================================
Compress a given string. Input: aaaaabbccc Output: a5b2c3
Answers & Comments (7)
Dec 22, 2010
by Interview Candidate:
Simply iterate over the input and count the repeating chars and then append to the output.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Jan 14, 2011
by Victor:
I would use Huffman code.
Helpful Answer?
Yes | No
Inappropriate?
Jan 14, 2011
by NehaGupta:
#include
#include
using namespace std;
int main()
{
string str;
cin << str;
int k=0;
int shiftCount = 0;
for(i=1;in. We have the recurrence V(i) = V(i+1) + V(i + 2), The result is V(0).
Time complexity is O(n)
Helpful Answer?
Yes | No
Inappropriate?
Jan 12, 2011
by Interview Candidate:
I proposed them a recursive solution but they didn't accept it and ask me for a formula.
Helpful Answer?
Yes | No
Inappropriate?
Jan 14, 2011
by Victor:
F(n) = F(n-1) + F(n-2).
Where F(n) - the ways to go on top to the last n stairs.
function fibb(int n)
{
int x0 = 0, x1 = 1, x2;
for(int i = 2; i <= n; i++)
{
x2 = x0 + x1;
x0 = x1;
x1 = x2;
}
return x1;
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jan 20, 2011
by The Answer Man:
When Google insisted on a formula, you should immediately have know this was not a Fibonacci series! You can solve it with recursion, but solving it recursively for n=4 should lead you to the formula. As an example of the recursive way, suppose n=40. How many different ways are there, following the rules of the question to get there? There are exactly 2 ways to get to the 40th step, either take a single step from 39 to 40 or a single step from 38 to 40. Our total so far is 2. Lets repeat for n=39, now our total is 4. This continues to work until you get to n=1, the special case, since you can only get to it by a single small step from the ground. You probably notice that the formula is f(n) = 2n -1.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Jan 21, 2011
by v:
The Fibonacci is the right answer ... almost
It is true, that F(n) = F(n-1) + F(n-2), but Fibonacci sequence is also defined by the rule F(1) = F(2) = 1. In our case, for n = 1 step we have just one way { 1 }, so F(1) = 1. However, for n = 2 steps, we have two ways { 11, 2 }, so F(2) = 2.
Therefore, the answer is F(1) = 1, F(2) = 2, F(n) = F(n-1) + F(n-2).
It does not hurt to check this formula for small n:
f(1) = 1 : { 1 }
f(2) = 2 : { 11, 2 }
f(3) = 3 : { 111, 12, 21 }
f(4) = 5 : { 1111, 112, 121, 211, 22 }
f(5) = 8 : { 11111, 1112, 1121, 1211, 2111, 122, 212, 221 }
Obviously, the recursive formula works, while Answer Man's formula f(n) = 2n -1 does not.
Helpful Answer?
Yes | No
Inappropriate?
Jan 28, 2011
by lamont:
I agree with v that it's almost Fibonacci.
This question has come up three times in the last two months here on Glassdoor. My answer has been that for n stairs there are Fib(n+1) ways to climb them. This fixes the "off by one" problem and establishes that there is one way to climb zero steps (which seems as good an answer as any).
}
===============================
There are n pots with different # gold coins in them. Two players play a game, where each player can select a pot at either ends. maximize the gold
Answers & Comments (7)
0 of 1 people found this helpful
Aug 16, 2010
by Interview Candidate:
Use dynamic programming to solve the same. Could explain the logic, but again did not find the time to code it up.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Aug 18, 2010
by Steve M:
What does "maximize the gold" mean in this game? If it means to keep the heavier pots for the end of the game and keep the two sides balanced, then I think you need to sort the N pots and redistribute so that the heaviest is in the middle and the two sides are balanced. Since a pot can contain only a limited number of gold, I would use a count sort algorithm for an average time of O(N+k). When re-distributing, I would balance the two sides starting by the heaviest pot, according to the individual sides's weight.
For example:
1, 4, 10, 2, 3, 4, 2
Counting sort:
1:.
2:..
3:.
4:..
5:
6:
7:
8:
9:
10:.
Sorted list:
1, 2, 2, 3, 4, 4, 10
If K is odd, remember the heaviest = 10
Re-distributing by weights:
4, 3, 1
4, 2, 2
Final list:
1, 3, 4, 10, 4, 2, 2
Helpful Answer?
Yes | No
Inappropriate?
Aug 18, 2010
by Anony:
To maximize the gold means, each player wants to maximize the amount of gold the player gets by selection of one pot at a time (either leftmost or rightmost). Player 1 selects a pot, followed by player 2, followed by player 1 etc. How does the player select picking Left or right one ? Maximize gold means sum of the gold coins of all the pots selected by a player.
I did not follow how sorting helps
Helpful Answer?
Yes | No
Inappropriate?
Sep 2, 2010
by Anonymous:
How about take differences and get the side that gives you a better gain.
For example:
8 7 4 6
Take 6
Then take 7
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Sep 11, 2010
by Jordan:
I think the idea is that each person takes turns choosing the currently leftmost or rightmost pot and tries to maximize the sum of all the pots they take. You can't be greedy because of situations like this:
10, 100, 10, 5
If you were greedy, you would take 10 first, and the other person would take 100. If you instead took 5, they would be forced to take one of the 10's, leaving the 100 available for you to take.
The recursive idea here is minimax. The maximum I get from X to Y is the maximum of either the gold at X + what's left over when the other player takes from X+1 to Y, or the gold at Y + what's left over when the other player takes from X to Y-1. As an implementation note, we should keep track of the amount both players get over each interval. If the other player gets R gold, with T gold leftover for me, when choosing from the subrange X+1 to Y, then from the range X to Y, I can easily say that if I choose to take the gold from X, I get T + gold[X] gold, leaving R gold for the other person. This makes the code much simpler.
Since each case is based only on subcases of a smaller length (e.g. from X to Y, which is length Y - X, only depends on X to Y-1 and X+1 to Y, both of length Y-X-1), we can build up the cases in order of length. C++ DP implementation would look something like this:
pair dp[n][n];
for (int i = 0; i < n; ++i) dp[i][i] = make_pair(gold[i], 0);
for (int len = 1; len < n; ++len) {
for (int i = 0; i < n - len; ++i) {
pair L = dp[i + 1][i + len];
pair R = dp[i][i + len - 1];
if (gold[i] + L.second > gold[i + len] + R.second)
dp[i][i + len] = make_pair(gold[i] + L.second, L.first);
else
dp[i][i + len] = make_pair(gold[i + len] + R.second, R.first);
}
}
The amount of gold I get is dp[0][n - 1].first
Helpful Answer?
Yes | No
Inappropriate?
Oct 6, 2010
by Bartosz Milewski:
Use induction: Suppose that I know how to play best with N arbitrary pots. What's my best move with N+2 pots? Trivial cases: N=0 and N=1. With N+2 pots, I can chose L or R. After that my opponent chooses L or R. Then it's my turn again, but this time, with N pots, I know how to play, by induction hypothesis.
So what's the best move? It's the one that maximizes the worst case scenario (that is, my opponent playing her best).
What's the worst if I pick the left? It's the value of the left pot plus the minimum of two scenarios:
1. the opponent picks L and I do my best with what's left and
2. the opponent picks R and I do my best with what's left.
I do the same calculation assuming that I take the right first. The best of the two worst scenarios maximizes my goal. Here's the code in C++:
enum Move ( L, R, E }; // left, right, end of game
Move BestMove(int const * left, int const * right, int & minGain) {
if (left == right) // there's nothing left in between
{
minGain = 0;
return E;
}
if (right - left == 1) // just one left
{
minGain = *left;
return L; // arbitrary choice
}
// I take left, she takes right
int xLL;
BestMove(left + 2, right, xLL);
// I take the left, she takes the right, or vice versa
int xLR;
BestMove(left + 1, right - 1, xLR);
// I take the right, she takes the right
int xRR;
BestMove(left, right - 2, xRR);
// my worst if I take left
int wLeft = *left + std::min(xLL, xLR);
// my worst if I take right
int wRight = *(r-1) + std::min(xLR, xRR);
// the better of the two
minGain = std::max(wLeft, wRight);
return (wLeft >= wRight)? L: R;
}
void main()
{
int pots[] = { 2, 4, 10, 2, 3, 1 };
int minGain;
Move m = BestMove(a, a + 6, minGain);
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 17, 2011
by Victor:
Dynamic programming
public class GoldPots
{
public static int max(int a, int b)
{
return a < b ? b : a;
}
public static int solve(int[] a, int player)
{
int n = a.length;
int[][] m = new int[n][n];
int[] sums = new int[n];
sums[0] = a[0];
for(int i = 1; i < n; i++)
{
sums[i] = sums[i-1] + a[i];
}
for(int i = 0; i < n; i++)
{
m[i][i] = a[i];
}
int sumij;
for(int k = 1; k < n - 1; k++)
{
for(int i = 0; i < n - k; i++)
{
for(int j = i + k; j < n; j++)
{
sumij = sums[j] - sums[i] + a[i];
m[i][j] = max(sumij - m[i + 1][j], sumij - m[i][j-1]);
}
}
}
return m[0][n-1];
}
public static void main(String[] args) {
int[] a = {1,9,5,3,6,2};
System.out.println(solve(a,0));
}
})})})}})})}
=============================
Given the pre-order and in-order traversing result of a binary tree, write a function to rebuild the tree.
Answers & Comments (4)
Jun 24, 2010
by alexb_sf:
Here is the algorithm (I am too lazy to write the whole program).
Let's number the nodes of in-order traversing sequentially (1,2,3, etc.). Then take the list of nodes of pre-order traversing.
The first one is the root.
While their numbers (from in-order list) decreasing, connect them as left-hand children, one by one.
If the next number is greater, find the node with the max number (less than this one) and connect this one to it as right-hand child. Etc.
Helpful Answer?
Yes | No
Inappropriate?
Jul 4, 2010
by magyar:
I think they meant any "binary tree" not a binary search tree; but ALL values must be different (imagine a tree with n 1's; it has a Catalan(n) configurations and the same pre- and in-order traversals). So here is a solution:
node* rec(const std::vector& PRE, const std::vector& IN) {
node * r = new node(0,PRE[0]); // root
node * v = r; // what we want to return
bool l = PRE[0] != IN[0]; // do I go left?
std::set path; // ancestors
path.insert(PRE[0]);
for(int p=1, i=l ? 0 : 1; p!=(int)PRE.size(); ++p) {
node * n = new node(r,PRE[p]);
r = l ? r->_left = n : r->_right = n;
l = true; // revert to left
if (PRE[p] == IN[i]) { // must go right or up
++i;
while(i < (int)(IN.size())) {
if (path.find(IN[i]) == path.end()) { // not an ancestor
l = false;
break;
} else {
for(;;) {
path.erase(r->_v);
r = r->_up;
if (r->_v == IN[i]) {
++i;
break;
}
}
}
}
}
path.insert(PRE[p]);
}
return v;
}
The idea is that the pre-order is basically a depth-first search order, which is convenient to build the tree (it is always connected at every interim stage). The in-order is used to decide whether to move right or up. BTW, you can guess the definition of "node".
Helpful Answer?
Yes | No
Inappropriate?
Jul 11, 2010
by Stefan T:
I have done something in Java. Maybe this might help:
import java.util.Arrays;
import java.util.TreeMap;
import javax.management.RuntimeErrorException;
public class BinaryTrees {
public static class Node {
Node right;
Node left;
char value;
// preorder
// public String toString() {
// return (value + " ") + (this.left == null ? "" : this.left)
// + (this.right == null ? "" : this.right);
//
// }
// in order
// public String toString() {
// return (this.left == null ? "" : this.left) +(value + " ") +
// (this.right == null ? "" : this.right);
//
// }
// post order
public String toString() {
return (this.left == null ? "" : this.left) + ""
+ (this.right == null ? "" : this.right) + (value + " ");
}
}
private static final char[] preOrderStr = new char[] { 'u','f','A','C','M','h','s','9','6' };
private static final char[] inOrderStr = new char[] { 'A','f','C','u','s','h','M','9','6' };
public static void main(String... args) {
BinaryTrees trees = new BinaryTrees();
Node root = trees.rebuildTree(inOrderStr, preOrderStr);
System.out.println(root);
}
public Node rebuildTree(char[] inOrderS, char[] preOrderS) {
Node root = new Node();
root.value = preOrderS[0];
int index = getIndex(inOrderS, root.value);
char[] leftInOrderS = new char[index];
char[] rightInOrderS = new char[inOrderS.length - index - 1];
char[] leftPreOrderS = new char[index];
char[] rightPreOrderS = new char[preOrderS.length - index - 1];
System.arraycopy(inOrderS, 0, leftInOrderS, 0, index);
System.arraycopy(inOrderS, index + 1, rightInOrderS, 0, inOrderS.length
- index - 1);
System.arraycopy(preOrderS, 1, leftPreOrderS, 0, index);
System.arraycopy(preOrderS, index+1, rightPreOrderS, 0, preOrderS.length
- index -1);
if (leftInOrderS.length != 0 && leftPreOrderS.length != 0)
root.left = rebuildTree(leftInOrderS, leftPreOrderS);
if (rightInOrderS.length != 0 && rightPreOrderS.length != 0)
root.right = rebuildTree(rightInOrderS, rightPreOrderS);
return root;
}
public int getIndex(char[] chars, char ch) {
for (int i = 0; i < chars.length; i++)
if (ch == chars[i])
return i;
throw new RuntimeException("No char " + ch + " in the vector");
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 18, 2011
by Victor:
package datastructures.trees;
public class BuildTreeInorderPreorder {
public static void buildTree(int[] inorder, int[] preorder)
{
TreeNode root = createNode(preorder,inorder,0,preorder.length-1,0,inorder.length - 1);
printPostOrder(root);
}
private static TreeNode createNode(int[] preorder, int[] inorder, int ps, int pe, int is, int ie)
{
if(ps > pe || is > ie)
{
return null;
}
TreeNode newNode = new TreeNode(preorder[ps]);
int i;
for(i = is; i <= ie; i++)
{
if(preorder[ps] == inorder[i])
{
break;
}
}
newNode.left = createNode(preorder, inorder, ps + 1, ps + i - is, is, i - 1);
newNode.right = createNode(preorder, inorder, ps + i - is + 1, pe, i + 1, ie);
return newNode;
}
private static void printPostOrder(TreeNode node)
{
if(node == null)
{
return;
}
printPostOrder(node.left);
printPostOrder(node.right);
System.out.print(node.x + "");
}
public static void main(String[] args) {
int[] preorder = {1,2,4,7,8,5,3,6,9,10,11,12};
int[] inorder = {7,4,8,2,5,1,3,9,6,10,12,11};
buildTree(inorder,preorder);
}
}
class TreeNode
{
int x;
TreeNode left, right;
public TreeNode(int x)
{
this.x = x;
}
}}}}}}}}
================================
How to reverse a tree
================================
"Design a utility similar to Google suggest. How can you do it?"
My first guess would be to use a trie tree, which also keeps a count of searches at each node. As the user types, you can suggest the most common completions from the trie using a search.
However, that might be a lot of processing for a large scale system, such as a website like Google. I'd half to think a little about whether or not this is the case, or whether they would be some way of indexing to speed up processing.
================
write a function to calculate X^N
int pow(int x, int n){
return x*1<= Y. No recursion needed.
Also, if Y is a power of 2, you can use a right-shift to get the answer...even faster. If the number space is sufficiently small, you can use a lookup table.
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2010
by Steve M:
int positionOfFirstAndOnlyBitSet(int m) {
int pos = -1;
int x = 0;
for (; x < 32; x++) {
if ((m >> x) & 1)
if (pos == -1)
pos = x;
else
return -1; // found more than one bit
}
return pos;
}
int divide(int n, int m) {
if (m == 1)
return n;
if (m == n)
return 1;
if (m > n)
return 0;
int pos = positionOfFirstAndOnlyBitSet(m);
if (pos != -1)
return n >> pos;
// how manny times one can multiply m before going over n
int x = 1;
int mm = m;
while (mm <= n) {
mm += m;
x++;
}
return x - 1;
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 16, 2010
by somebody:
assuming you want to be able to handle doubles, I like the idea of x * pow(y,-1.0); ... why make the answer more difficult for yourself than it needs to be?
Helpful Answer?
Yes | No
Inappropriate?
Nov 5, 2010
by someone:
I got this question in facebook interview as well.
You usually are not allowed to use floats, or pow(), or %
And also you have to consider both +, - integers, so Steve M answer is not valid.
Helpful Answer?
Yes | No
Inappropriate?
Jan 18, 2011
by Victor:
public static int divide(int a, int b)
{
if(a < b)
return 0;
int div = b;
int k = 1;
while((div<<1) <= a)
{
div = div<<1;
k = k<<1;
}
return k + (div == a ? 0 : divide(a-div,b));
}
Helpful Answer?
Yes | No
Inappr
}
=====================================
There is a parking lot of cars that is full except for a single spot. Write some code to take it from one arbitrary configuration to another moving only one car at a time into the empty spot. Analyse the time complexity, how would you improve it, etc.
====================
You have a simple search consisting of search terms that are OR'ed together, ie: Cats AND Dogs. You have a set of documents possibly containing those terms and you have the positions of those terms in each document. How would you search for Cats AND Dogs?
Various answers possible. One answer is to construct a postings list for each term. To answer the AND query, need to merge the two postings lists (the one for Cats and the one for Dogs).
===========================
Given two arrays, print all common elements
You can sort the shortest array first and for each element of the longest array, find that element in the fist array. When found if it is not marked, then print it and mark it.
================================
How would you sort 10 million phone numbers?
============================
How would you implement a singleton in the language of your choice?
======================
Write a function in C/C++ that returns the number of zeros contained in the factorial of the number that is passed to it.
Answers & Comments (5)
0 of 2 people found this helpful
May 30, 2010
by George:
Number of zeros == number of 5s in the prime factorization. Answer : divide the parameter by 5
def number_of_zeros( n ):
return n / 5
Helpful Answer?
Yes | No
Inappropriate?
Jun 5, 2010
by Anonymous:
works for 20 but not for 30...
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Jun 20, 2010
by Anonymous:
The answer is simply:
int func(int number_to_get_factorial_of) {
return 0;
}
Helpful Answer?
Yes | No
Inappropriate?
Jun 20, 2010
by Anonymous:
Assuming "int" can hold the whole factorial:
int func(int x) {
int factorial = 1;
int zeros = 0;
while (x) {
factorial *= x--;
}
while (factorial) {
zeros += (factorial % 10 == 0);
factorial /= 10;
}
return zeros;
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 1, 2011
by Ethelbert:
The previous poster is correct, but would fail for large numbers.
George is right that you just need the number of 5's in the prime factorization (there will always be lots of 2's), but dividing n by 5 does not quite give that to you.
You need n/5 + n/25 + n/125 + ..... In time the terms become 0 and you can stop.
}
==========================
Find the maximal and minimal number in an array of integers
Answers & Comments (6)
1 of 2 people found this helpful
May 21, 2010
by Girish:
max = min = first element of array.
Walk the array one element at a time.
Is the current element smaller than min?
yes, min = current element
Is the current element bigger than max?
yes, max -= current element.
here is the C code
int main()
{
int array[] = { 0, 1, 2, 4, 6, 5, 10 };
int nLen = sizeof(array)/sizeof(array[0]));
int max = array[0];
int min = array[0];
for( int nCount = 1; nCount < nLen; nCount++ )
{
if( array[nCount] < min )
min = array[nCount];
if( array[nCount] > max )
max = array[nCount];
}
printf("Min is [%d]\n", min);
printf("Max is [%d]\n", max);
return 0;
}
Helpful Answer?
Yes | No
Inappropriate?
May 27, 2010
by Anonymous:
Recursive
Helpful Answer?
Yes | No
Inappropriate?
Jun 26, 2010
by Anonymous:
This can be done in sub-linear time using order statistics. (Look up "median find")
Helpful Answer?
Yes | No
Inappropriate?
Jul 20, 2010
by somebody:
I'm assuming you mean to use a Heap or Priority Queue to find the minimim and maximum? But the problem is that the definition states the data comes to us in the form of an array. If you assume the array represents a priority queue or heap, then yes, this is possible in O(log n) time, or constant time. But, if you assume it is an unordered array of numbers, then it must be O(n).
Helpful Answer?
Yes | No
Inappropriate?
Aug 18, 2010
by userisyo:
Complete python program to demonstrate the recursive solution to get the min, max numbers in the given array.
Algorithm: divide and conquer. Divide the array in the middle into two parts, and apply each portion the same algorithm until you get the basic cases of slices of one or two elements.
Complexity: O(n)
------
import random
def min2(a, b): return a if a < b else b
def max2(a, b): return a if a > b else b
def minmax(arr):
def recursive_minmax(i, j):
""
Recursive funtion to get the min and max numbers in array 'arr' in the range [i, j)
""
m = (i + j) / 2
if i == m:
return arr[i], arr[i]
if j == m:
return min2(arr[i], arr[j]), max2(arr[i], arr[j])
left, right = recursive_minmax(i, m), recursive_minmax(m, j)
return min2(left[0], right[0]), max2(left[1], right[1])
return recursive_minmax(0, len(arr))
numbers = [random.randint(-100, 100) for x in range(10)]
print 'array:', numbers
print 'min, max:', minmax(numbers)
Helpful Answer?
Yes | No
Inappropriate?
Oct 27, 2010
by Anonymous:
I believe it is unsorted array.
Finding either Max or Min takes O(n) time.
The trick here is finding both Max and Min takes less than O(2n) time. Easy to prove.
}
=================================
How would you implement a stack to achieve constant time for "push", "pop" and "find mininum" operations?
Answers & Comments (2)
1 of 2 people found this helpful
May 15, 2010
by Interview Candidate:
The catch is to use another stack to remember the minimum. The other operations already take constant time.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Sep 17, 2010
by spas:
to the last poster, actually, depending on how you implement it, push and pop might NOT be constant...that's the problem right? you could implement a stack with an array and pushes and pops WOULDN'T be constant.
I think a possible solution would be to use a linkedlist. pushes and pops are constant because you're just adding another node to the head.
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or c
====================
Given an array of integers where each element points to the index of the next element how would you detect if there is a cycle in this array?
Answers & Comments (8)
May 15, 2010
by Interview Candidate:
The catch is to realize that if there is a cycle, it will result in an infinite loop
Helpful Answer?
Yes | No
Inappropriate?
May 17, 2010
by Anonymous:
What as the time and space complexity of the best solution? Can you do it in O(n) time and O(1) space?
Helpful Answer?
Yes | No
Inappropriate?
May 21, 2010
by Girish:
One possible solution is to keep a list for all visited positions.
If we hit a position that is already in the list, we've detected a cycle.
For this solution, time complexity is O(n) and space complexity is O(n).
How to do this in O(n) time and O(1) space?
Helpful Answer?
Yes | No
Inappropriate?
May 26, 2010
by Anonymous:
use the contents of a position as an index into array and while traversing the contents, negate the contents after you visit it. if at any time you find the contents of a position as negative (given that every element points to the next element in array, you cannot have -ve numbers in array) this will run in o(n) with constant space
e.g.
array = [1,2,3,4,5,2] (zero based index)
a[0]=1
go to a[1] and negate a[0] to -1
a[1]=2
go to a[2] and negate a[1] to -2
like this when you hit a[5] =2 and then you see a[2] = -3, which is already visited so there is a loop/cycle
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 1, 2010
by Anonymous:
The problem is imprecisely stated. If every element a[i] contains a value that is an index into a (i.e. a value in the range 0..length(a)), then there *must* be at least 1 cycle, assuming a is of finite size. On the other hand, if a is allowed to contain values that are not valid indexes (negative, or >= length(a)), then it indeed takes some work to determine if a has cycles. So let's assume the latter.
If a is allowed to contain negative values to start with, then the negate-as-you-see-it solution doesn't work.
To determine if there is a cycle starting at any given element (isCycle(elemindex)) in O(1) space and O(n) time, you could walk 2 pointers starting at elemindex. One would go at normal speed (nextelem = a[thiselem]) and one would go at double speed (nextelem=a[a[thiselem]]). If the 2 pointers meet, isCycle() returns true. However, since you'd have to run isCycle(index) on every index to ask if there is a cycle *anywhere* in the array, this algorithm is O(n**2) in time. I'd have to ponder if there's an O(1) space / O(n) time algorithm for this...
Helpful Answer?
Yes | No
Inappropriate?
Jul 24, 2010
by Jimmy:
if the array is not "full," then it must contain sentinel values which represent NULL references. You could use Integer.MIN (in Java parlance) or just -a.length.
this fixes the above criticism of the negate-as-you-see-it approach. What it doesn't fix is the fact that that the "graph" can be disconnected.
for instance [1,2,NULL,4,5,1]
a[0]->a[1]->a[2]->NULL
a[3]->a[4]->a[5]->a[1]->a[2]->NULL
in this case there are multiple references to element a[1], but it's not a cycle.
I think you're stuck with the N^2 solution.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Oct 28, 2010
by Anonymous:
Define two pointers
One pointer move one step each time, The other pointer move two steps each time.
If the pointers ever meet together (besides the start point) before one of the pointer reaches the end, then there is a loop. Otherwise, there isn't.
This takes O(n) time and O(1) space.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 14, 2010
by Anonymous:
if there is a loop then that means that is a number repeated in the array. put the number in the array into a hashmap and compare the size of the hashmap to the size of the array. if less than there is a loop
===========================================
Interviewed Mar 2010 in New York, NY (took 6 weeks)
In preparation for my interview, I browsed through peoples' experiences here and elsewhere on the web and practiced as many sample questions and coding exercises as I could find. I often found this intimidating, because I regularly found questions that looked daunting and beyond anything I thought I could answer within the space of an interview. That plus an endless list of "Interviewed, No Offer" experiences related on this site made the prospect of successfully navigating this gauntlet seem diim.
So when my (in-person) interview came around, I was surprised how well everything went. It wasn't perfect. I botched a few things to the point of embarrassment. But I consistently found I was facing fairer and more manageable questions than much of what I found on the web. And since I had really focused on my core data structures and algorithms, I was well prepared to tackle them.
Let me repeat that last point: probably the most important thing you can do is study, in detail, your core data structures and algorithms. Trees, linked lists, hash tables, and graphs (don't forget graphs; they're important and relevant). Common searching and sorting and path-finding algorithms. Big O notation. Focus on these fundamentals. Write programs that implement them. This will take you 85% of the way to where you need to be.
You'll fill in the remaining 15% by reviewing the major concepts in computer architecture, networking / internet design, programming languages, concurrency, and distributed algorithms. Know how source code turns into instructions on a CPU. Know the algorithmic benefits and drawbacks of different memory types. Know how the internet works, the OSI stack, and what's important about TCP. Know what's good and bad about your preferred programming language. Don't expect to master these subjects (especially distributed algorithms); there's way too much content to completely review. Just focus on the basics.
Hopefully you'll see a theme here. Google is a company that processes massive amounts of data through the use of thousands of network-connected commodity computers. Think of the kinds of programming challenges this entails and the modes of thinking it requires and you'll see the driving focus behind the interview questions and how to prepare for them. So spend as much time as you like practicing sample questions from the internet and reading about other peoples' experiences. But don't fret about them. As long as you maintain this underlying focus and prepare with it in mind, you'll be in great shape.
For in-depth preparation, I found the book "Algorithms in a Nutshell" and relevant Wikipedia articles very helpful (don't forget about Wikipedia, it's very detailed and it's free!). I also recommend Steve Yegge's "Get that job at Google" blog post for a good overview. Good luck!
==========================================
Define an algorithm that converts a string to an integer without using a built in method like int()
Answers & Comments (2)
Jun 3, 2010
by DVD:
in Java:
String f = "2456";
int length = f.length();
double result = 0;
for (int i = 0; i < length; i++) {
char c = f.charAt(i);
int x = c - 48;
double exp = Math.pow(10,length-1-i);
result = result + (exp*x);
}
int myInt = (int)result;
Helpful Answer?
Yes | No
Inappropriate?
Aug 19, 2010
by userisyo:
Complete python program to convert from string to int.
Complexity: o(n), where n is the number of digits of s.
----
s = '2456'
n = 0
p10 = 1
for d in reversed(s):
n += p10 * (ord(d) - ord('0'))
p10 *= 10
Helpful Answer?
Yes | No
Inappropriate?
============================
Given a list, return the first pair of duplicates in the list.
Hashmap with list values as keys and counters as values. As soon as you hit one you've already seen before, it's a dup.
========================
One independent survey showed that 70% on people asked like coffee. Another independent survey showed that 80% of people like tea. What is the upper and lower bound of peoples who likes both coffee and tea
Answers & Comments (12)
10 of 10 people found this helpful
May 8, 2010
by Interview Candidate:
Upper: 70%
Lower: 50%
Helpful Answer?
Yes | No
Inappropriate?
0 of 6 people found this helpful
May 9, 2010
by Anonymous:
20, 80
Helpful Answer?
Yes | No
Inappropriate?
3 of 5 people found this helpful
May 9, 2010
by Anonymous:
50, 70
Helpful Answer?
Yes | No
Inappropriate?
0 of 6 people found this helpful
May 9, 2010
by Anonymous:
It is 70% Both High & Low.
Any higher and people don't like Coffee, any lower and they don't like coffee.
This is assuming 0% margin of error and a perfect survey.
Helpful Answer?
Yes | No
Inappropriate?
18 of 18 people found this helpful
May 10, 2010
by Anonymous:
Take 100 people. 1-100. Assume, 1st 70 likes coffee (1-70) and 1st 80 likes tea(1-80). So, atmost 70 can like both tea and coffee. Now, take the same 100 people. Assumed, 1st 70 likes coffee and last 80 likes tea(21-100). So, that make atleast 50 people likes both coffee and tea. So, upper is 70 and lower is 50.
Helpful Answer?
Yes | No
Inappropriate?
6 of 6 people found this helpful
May 18, 2010
by Jordan:
Only 70% of people like coffee, so that would be the upper bound since they need to like both coffee and tea. 80% of people like tea, which leaves 20% that don't like tea. Once again, they need to like both coffee and tea, so you subtract the 20% that don't like tea from the upper bound which leaves 50% for the lower bound. This assumes the survey was 100% accurate and had 0% margin of error, which means they would have had to interview the same 100 people in both surveys and the results are only valid for the 100 people surveyed.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 18, 2010
by Jordan:
Only 70% of people like coffee, so that would be the upper bound since they need to like both coffee and tea. 80% of people like tea, which leaves 20% that don't like tea. Once again, they need to like both coffee and tea, so you subtract the 20% that don't like tea from the upper bound which leaves 50% for the lower bound. This assumes the survey was 100% accurate and had 0% margin of error, which means they would have had to interview the same 100 people in both surveys and the results are only valid for the 100 people surveyed.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
May 26, 2010
by Joe:
The fact that these are two independent surveys suggests that they were not conducted on the same group of people. Therefore, if we were to extrapolate this survey data for people in general, you can only conclude that the upper limit is 70% but the lower limit can be zero since 100% of the set of people who like coffee may not like tea.
Helpful Answer?
Yes | No
Inappropriate?
Jun 4, 2010
by Rock:
Seventy percent of people like coffee so the upper bound is limited by that seventy.
80 percent of the people who like tea multiplied by 70 percent who may like coffee is 56 percent, so 56 lower 70 upper.
Helpful Answer?
Yes | No
Inappropriate?
Jul 18, 2010
by somebody:
This problem reminds me of a convolution operation. Convolve 1111111000 with 1111111100 and you sortof get your answer.
Helpful Answer?
Yes | No
Inappropriate?
3 of 3 people found this helpful
Sep 13, 2010
by thegal:
Assuming the two independent surveys have been done on the same sample of people, following a consistent set of rules:
n(AUB) = n(A)+ n(B) - n(A intersection B)
Assuming a population of 10 people:
10 = 7 + 8 - x
or, x= 5 or, 50% = lower limit
And of course the max will the min(coffee lovers, tea lovers) = min(7,8)= 7 ~ 70%
Helpful Answer?
Yes | No
Inappropriate?
Nov 5, 2011
by LateToAnswer:
Rock has it right. The trick is that it is; two independent studies, not we asked the same group. 70% is the easy part but of those 70% that like coffee 80% like tea so that means at least 56% like both
===================================
Write a function Brackets(int n) that prints all combinations of well-formed brackets. For Brackets(3) the output would be ((())) (()()) (())() ()(()) ()()()
Answers & Comments (10)
0 of 3 people found this helpful
May 8, 2010
by Interview Candidate:
public class Parenth2 {
static int total = 3;
static private void Brackets(String output, int open, int close, int pairs) {
if ((open == pairs) && (close == pairs) && output.length() == total * 2) {
System.out.println(output);
} else {
if (open < pairs)
Brackets(output + "(", open + 1, close, pairs);
if (close < open)
Brackets(output + ")", open, close + 1, pairs);
}
}
public static void main(String[] args) {
Brackets("", 0, 0, total);
}
}
Helpful Answer?
Yes | No
Inappropriate?
May 11, 2010
by Interview Candidate #2:
You almost got thte answer, just a couple of errors...
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Owner
*/
public class Parenth4 {
static private void Brackets(String output, int open, int close, int pairs, boolean opened, boolean closed, int total) {
if ((open == pairs) && (close == pairs) && output.length() == total * 2) {
System.out.println(output);
} else {
if ((open < pairs))
Brackets(output + "(", open + 1, close, pairs,true, closed, total);
if ((close < open)&& opened)
Brackets(output + ")", open, close + 1, pairs,opened,closed, total);
}
}
public static void Brackets(int total) {
Brackets("", 0, 0, total,false,false, total);
}
public static void main(int number){
Brackets(number);
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 11, 2010
by shards:
This is a DP/memoization question, I believe. The base case is 0 and 1 bracket (the answer is empty or (). The recurrence is:
bracket(n) =
all combination of results from bracket(n-1) and from bracket (1)
from bracket(n-2) and bracket(2)
.
.
from bracket(1) and bracket(n-1)
lastly, '(' . bracket(n-1) ')'
The DP version of the above recurrence is straightforward. (Btw, this recurrence obviously will produce duplicate, but it's not hard to produce a modification that does not produce duplicate.) ;)
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 13, 2010
by Horia:
Here is a F# implementation:
let rec Br total output openp closep =
if openp = total && closep = total
then
printfn "%s" output
else
if openp < total then Br total (output + "( ") (openp + 1) closep
if closep < openp then Br total (output + " )") openp (closep + 1)
let Brackets total =
Br total "" 0 0
Brackets 5
let read = System.Console.ReadLine()
Helpful Answer?
Yes | No
Inappropriate?
May 17, 2010
by marcos:
void parens(int nPairs) {
parens("", nPairs, nPairs);
}
void parens(string ans, int leftCount, int rightCount) {
if (leftCount==0 && rightCount==0) {
cout << ans << endl;
return;
}
if (leftCount>0) {
parens(ans+"(", leftCount-1, rightCount);
}
if (rightCount>leftCount) {
parens(ans+")", leftCount, rightCount-1);
}
}
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 21, 2010
by Rohan Dhapodkar:
To Remove duplicates simply use java Set :)
public static String bracket(int a) {
Set s = new TreeSet();
bracketIntern(s, a, "", "");
System.out.println(s);
return s.toString();
}
public static void bracketIntern(Set set,int a, String preFix,String suffix) {
if(a == 1) {
set.add(preFix+"()"+suffix);
return;
}
bracketIntern(set, a-1, preFix+"()", suffix);
bracketIntern(set, a-1, preFix+"(", ")"+suffix);
bracketIntern(set, a-1, preFix, "()"+suffix);
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 20, 2010
by somebody:
I think you can also build a trie, and the traverse the trie to print out all the combinations.
Helpful Answer?
Yes | No
Inappropriate?
Aug 19, 2010
by userisyo:
Complete python program to print the all combinations of well-formed brackets.
How to calculate its Big-o?
The recursive recurrence seems a little bit complicated.
----
def brackets(n):
sol = []
li = [' ' for x in range(n*2)]
def recu_brackets(opened, closed):
if n - opened:
li[opened + closed] = '('
recu_brackets(opened + 1, closed)
if n - closed and opened > closed:
li[opened + closed] = ')'
recu_brackets(opened, closed + 1)
if opened == n and closed == n:
sol.append(''.join(li))
recu_brackets(0, 0)
print ' '.join(sol)
brackets(3)
Helpful Answer?
Yes | No
Inappropriate?
Aug 25, 2010
by xster:
wasn't all that neat. o well
public class MakeBrackets{
static List make(int number){
List list = new LinkedList();
if (number == 0) {list.add(""); return list;}
if (number == 1) {list.add("()"); return list;}
for (int i = 0; i < number; i++){
for (String item : make(i)){
for (String item2 : make(number - 1 - i)){
list.add("(" + item + ")" + item2);
}
}
}
return list;
}
public static void main(String[] args){
System.out.println(make(Integer.parseInt(args[0])));
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jun 1, 2011
by anon:
def brackets(n):
return bracketsPrefix("", n, n)
def bracketsPrefix(prefix, opens, closes):
total = 0
assert opens<=closes
if opens==0 and closes==0:
total = 1
print prefix
if closes>opens:
total += bracketsPrefix(prefix+")", opens, closes-1)
if opens>0:
total += bracketsPrefix(prefix+"(", opens-1, closes)
return total
if __name__=="__main__":
for i in range(6):
n = brackets(i)
print i,n
x = raw_input("** ")
Helpful Answer?
Yes | No
Inappr}
============================
Find shortest substring in a string that contains all of a set of characters.
Answers & Comments (5)
Jul 19, 2010
by somebody:
Would probably store the set of characters as a red-black tree. Then search and delete characters from the tree as they occur in the string. Return when the red-black tree is empty. O(n log n)
Helpful Answer?
Yes | No
Inappropriate?
Oct 17, 2010
by Anonymous:
Not sure how the previous comment's method would find the shortest... I would scan the string once, counting the # of occurrences of each of the desired chars. Then I would start two pointers at each end of the string and march them inward element by element, decrementing the corresponding char count if the pointer pass over one of the chars in the set. As soon as one of the counts hits zero for a pointer, say the left one, I know that is the left limit of the smallest substring. Ditto for the right. Overall O(n) algorithm.
Helpful Answer?
Yes | No
Inappropriate?
Jan 2, 2011
by Ethelbert:
That doesn't quite work either. Your method finds the first string such that: its first character does not occur anywhere to its left. But this is not guaranteed to be the shortest.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Jan 2, 2011
by Ethelbert:
If you approach this the simplest way:
For all substrings, test it to see if it has all the characters. For those that pass, take the shortest. There are O(n^2) substrings, and the test takes O(n) time, so we have O(n^3).
However, we are doing some work over and over. I.e. some substrings are tested, and then retested as parts of other substrings. If we avoid this duplication, we can get down to O(n^2). I'm guessing that's the best we can do.
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Apr 20, 2011
by Anon:
Let the string to searched be A. Let the set we want to find be S.
Find beg, the first position in A such that A[beg] is in S. Find the smallest value named end such that A[beg], ..., A[end] has all the characters in S. The length of the substring found so far is end - beg + 1 (assuming this operation succeeded).
Increment beg until A[beg] is again in S. Increment end until we again have in the substring all characters in S (we just need to get back the character we lost when we incremented beg). We found another solution.
Keep on incrementing beg and end. Keep track of the shortest solution.
Overall it is an O(n) algorithm. An actual implementation needs to take into account what data structures to use to hold the needed data.
===================
Write a program to find depth of binary search tree without using recursion
Answers & Comments (2)
0 of 1 people found this helpful
May 17, 2010
by Anonymous:
Q.enqueue rootNode,1
depth=0
while q,count>0
[n,d] = q.dequeue
depth = max(d,depth)
if n.left q.enqueue(n.left,d+1)
if n.right q.enqueue(n.right, d+1)
end
return depth
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 20, 2010
by userisyo:
Python implementation using a stack.
def depth(root):
st = [(root, 0)]
maxd = 0
while len(st):
node, dpt = st.pop()
maxd = max(maxd, dpt)
if node['left']:
st.append((node['left'], dpt + 1))
if node['right']:
st.append((node['right'], dpt + 1))
return maxd
==================================
Design and write a sudoku solver.
Take a cell which is not filled. Get a number from 1 to 9 which is not in the row or the column of that cell, and is not in the 3x3 square containing that cell either. If there is no such number, return. If there is such number, put it in that cell, and let this algorithm call itself for another empty cell. If there is more than one such number, repeat the algorithm for that number.
In short, use backtracking. Iterate through all possible partial solutions gradually filling up each solution or returning to a less complete solution if a dead end is encountered.
=======================================
Question about scalability: How would you sort a huge file - one that can not fit in memory?
Try external Sorting algorithm
N- way merge sort algorithm.
Or tell Google if they let you work there you would use Map Reduce :P
Helpful Answer?
Yes | No
Inappropriate?
Jul 20, 2010
by somebody:
Well, I don't know what the optimal algorithm would be... depends on the algorithms that handle disk read/write I would imagine, though it's been a while for me on this. But off the top of my head, I could see MergeSort as working for this, because you can take small chunks and sort those piece by piece.
============================
In-place string reversal.
char *str_rev(char *str){
char *p1, char *p2;
if( ! str) return NULL
for(p1 = str, p2= str + strlen(str) - 1; p2 > p1; ++p1, --p2){
*p1 ^= *p2;
*p 2^ = *p1;
*p1 ^ = *p2;
}
return str;
}
==============================
Given two strings (say string A, string B). Write a function that returns string A - string B.
Answers & Comments (2)
May 10, 2010
by quasar:
Look at the problem in the following way.
both strings A and B are set of characters
so you are looking at set difference
string set_difference(string a, string b){
map store;
string ret;
for(int i=0; i < a.size(); i++){
store[a[i]] = true;
}
for(int i=0; i < a.size(); i++)
{
if(store[b[i]] == true) continue;
ret += b[i];
}
return ret;
}
something more ?? looking for symmteric set difference
i.e. (A-B) U (B-A)
here you go
vector symmetric_diff(vector s1, vector s2){
map store;
vector ret;
for(int i=0; i < s1.size(); i++){
store[s1[i]] = true;
}
for(int i=0; i < s2.size(); i++){
if(store[s2[i]] == true)
{
store[s2[i]] = false;
continue;
}
else ret.push_back(s2[i]);
}
for(int i=0;i by a String that should work!!
Cheers :)
Helpful Answer?
Yes | No
Inappropriate?
Aug 3, 2010
by yaskil:
here you have O(n^2) complexity and strlen(s2) bytes storage complexity. You can solve this problem with O(n) complexity without any storage requirement.
First sort both strings (sorting requires O(nlogn) complexity)
Then compare both strings in a loop. This loop requires O(n) complexity.
==========================
For a n-node tree, you are given a left leaf node pointer and right leaf node pointer. Write a function to find the number of nodes between the leaves pointed by the left and the right pointer.
Find the first common ancestor(fca) of both nodes.
From the fca->right chlid-> left child make a tree traversal and count the number of nodes
From the fca->left child -> right child make a tree traversal and count the number of nodes
==============
What is the biggest software project that you have worked on and how.
===========
Out of 10 coins, one weighs less then the others. You have a scale.
How can you determine which one weighs less in 3 weighs?
Now how would you do it if you didn't know if the odd coin weighs less or more?
===========
Given inputs from Google Search, you have K chunks. Each chunk is individually alphabetically ordered (apple, banana, cat) ... (*apple, *banan, *cat). You want to merge all chunks into a single list. How would you do it? What limitations are there to your approach?
It's on an x86 processor, what does that mean and how does that affect your approach?
==========
How would you sort an array of one millions integers?
Answers & Comments (4)
1 of 2 people found this helpful
Oct 4, 2010
by Swapnil Dipankar:
The trick here is to ask whether the entire array fits into memory all at the same time:
- If it fits in memory all at once, use quicksort - O(n log n)
- If it does not, divide the array into chunks that does, sort the chunks individually using quicksort and store them on the disk. Then read the sorted lists, merge them and save them on the disk - O(n log n) + n = O(n log n)
Helpful Answer?
Yes | No
Inappropriate?
Oct 5, 2010
by Bartosz Milewski:
For some bonus points you can discuss how to implemented sorting using multiple machines.
- Send chunks of the array to multiple machines.
- On each machine perform merge sort (or quick sort, if the chunk fits in memory).
- Odd-numbered machines send their sorted chunks to even-numbered machines
- Even-numbered machines merge their own chunks with the ones sent to them
- Repeat the same with machines numbered in multiples of 4, 8, etc, until the final merge is performed.
If the number of machines is not a power of two, some machines will have no neighbor to send their chunk to. They will be idle in the next iteration and should change their number to that of their missing neighbor.
Helpful Answer?
Yes | No
Inappropriate?
Oct 7, 2010
by vsp:
One million integers is less than 4Mb can probably fit into memory. I would further ask about the rexpected range of numbers. If it is sufficiently small (e.g. ages, SSNs, etc) then sort could be done in O(n) time.
Helpful Answer?
Yes | No
Inappropriate?
Oct 26, 2010
by Babji Chetty:
I will use "Merge Sort" and map-reduce it (or use any grid based framework...or code my own stuff). Do you guys think it's right approach?
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this question â Join Now (It's Free) or Sign In
You might also be inter
===========================
Write code to check the validity of a suduko square
boolean checkSudoku(int[][] a, int n)
{
int s1, s2, s3;
for(int i = 0; i < n ^ n; i++)
{
s1 = s2 = s3 = 0;
for(int j = 0; j < n ^ n; j++)
{
if(((s1 & a[i][j]) //on line
| (s2 & a[j][i]) // on column
| (s3 & a[i%n][j%n]) //on a square
) > 0)
return false;
s1 |= a[i][j];
s2 |= a[j][i];
s3 |= a[i%n][j%n];
}
}
return true;
}
Helpful Answer?
Yes | No
Inappropriate?
Members can}
===================
Given inputs from Google Search, you have K chunks. Each chunk is individually alphabetically ordered (apple, banana, cat) ... (*apple, *banan, *cat). You want to merge all chunks into a single list. How would you do it? What limitations are there to your approach? It's on an x86 processor, what does that mean and how does that affect your approach?
===========================
How to find the max number of a shift buffer queue. For instance, there is an array like 5, 6,8,11,1,2, how to find the max number, which is 11 in this example.
Answers & Comments (6)
0 of 2 people found this helpful
Dec 7, 2011
by Interview Candidate:
Binary search.
Helpful Answer?
Yes | No
Inappropriate?
Dec 16, 2011
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
0 of 1 people found this helpful
Dec 19, 2011
by Gabriel:
Of course you can use binary search! :) Think about it! You just have to know where you are!
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
int[] list = new int[]{5, 6, 8, 11, 1, 2};
int max = list[0];
for(int i = 1; i < list.length; i++)
{
if (i > max)
{
max = i;
}
}
return max;
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
I see a couple of people suggested use binary search to find the max above, In order to do perform binary search, the list needs to be sorted. If the list is already sorted, you don't need a binary search to find the max number since it's located at the end of the list.
Helpful Answer?
Yes | No
Inappropriate?
Jan 15, 2012
by Liron:
int[] arr = new int[]{5,6,8,11,1,2};
int max = arr[0];
for (int i =0; i list1 = new ArrayList();
for (int i=0; i list2 = new ArrayList();
for (int i=0; i=0; index--) {
worseSell[index] = Math.min(worseSell[index+1], ticks[index]);
}
int lose = 0;
for (int index = 0; index < ticks.length; index++) {
lose = Math.max(lose, ticks[index] - worseSell[index]);
}
System.out.println(lose);
}
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Dec 1, 2011
by NoOne:
double WorstSell(double *values, int n)
{
double maxBuySeenSoFar = 0.0;
double minprofit = 0.0;
// in-order lose most. we need to buy high and sell low. we can only sell after buying.
for (int i = 0; i < n; ++i)
{
if (values[i] > maxBuySeenSoFar)
{
maxBuySeenSoFar = values[i];
}
else if (maxBuySeenSoFar - values[i] < minprofit)
{
minprofit = maxBuySeenSoFar - values[i];
}
}
return minprofit;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 7, 2011
by Allen:
Recursive way to solve this in n logn
public static int[] findMaxLost(int[] prices) {
return rFindMaxLost(prices, 0, prices.length-1);
}
private static int[] rFindMaxLost(int[] prices, int p, int r) {
if (p == r) {
int[] ml_pos = new int[2];
ml_pos[0] = p;
ml_pos[1] = p;
return ml_pos;
}
int q = (p + r) / 2;
int[] l_ml_pos = rFindMaxLost(prices, p, q);
int[] r_ml_pos = rFindMaxLost(prices, q + 1, r);
/*find the max_min cross the center point q*/
int[] m_ml_pos = new int[2];
m_ml_pos[0] = findMax(prices, p, q);
m_ml_pos[1] = findMin(prices, q + 1, r);
if ((l_ml_pos[0] - l_ml_pos[1]) >= (m_ml_pos[0] - m_ml_pos[1])
&& (l_ml_pos[0] - l_ml_pos[1]) >= (r_ml_pos[0] - r_ml_pos[1])) {
return l_ml_pos;
} else if ((m_ml_pos[0] - m_ml_pos[1]) >= (r_ml_pos[0] - r_ml_pos[1])) {
return m_ml_pos;
} else {
return r_ml_pos;
}
}
private static int findMax(int[] prices, int p, int q) {
int pos = 0;
for (int i = p + 1; i <= q; i++) {
if (prices[pos] < prices[i]) {
pos = i;
}
}
return pos;
}
private static int findMin(int[] prices, int q, int r) {
int pos = 0;
for (int i = q + 1; i <= r; i++) {
if (prices[pos] > prices[i]) {
pos = i;
}
}
return pos;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 8, 2011
by vinicius:
reader writer pointer soution. O(n)
public class MaxLose {
public static void main(String[] args) {
MaxLose m = new MaxLose();
int[] a = new int[]{10, 3, 20, 10, 12, 5, 20, 7, 5, 3};
int max = m.maxLose(a);
System.out.println(max);
}
private int maxLose(int[] a) {
int b = 0, max = 0;
for (int s = 1; s < a.length; s++) {
if (a[b] <= a[s])
b = s;
else
max = a[b] - a[s] > max ? a[b] - a[s] : max;
}
return max;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 17, 2011
by anonymus:
Most answers here are in correct. Here is the algorithm. You first identify all buy canditaes, and all sell candidates. A buy canditate is: a point which is bigger than everything on its left and also bigger than the next point on its right. A sell candiate is a point that is smaller than everything on its right and also smaller than the point on its left.
Then you match buy canditates to sell candidates, for every buy candidate the matching sell canditate is the first sell candidate on its left. (multiple buy candidates can match multiple sell) After they are matched the pair with maximum difference will give you the max loss. O(n) needed to find candidates, les than O(n) neded to match pairs.
Helpful Answer?
Yes | No
Inappropriate?
Dec 17, 2011
by Anonymous:
Most answers here are in correct. Here is the algorithm. You first identify all buy canditaes, and all sell candidates. A buy canditate is: a point which is bigger than everything on its left and also bigger than the next point on its right. A sell candiate is a point that is smaller than everything on its right and also smaller than the point on its left.
Then you match buy canditates to sell candidates, for every buy candidate the matching sell canditate is the first sell candidate on its right. (multiple buy candidates can match multiple sell) After they are matched the pair with maximum difference will give you the max loss. O(n) needed to find candidates, les than O(n) neded to match pairs.}
======================
Given two sorted integer arrays, write an algorithm to get back the intersection.
vector SortedIntersection(int *a, int an, int *b, int bn)
{
vector result;
// assuming asscending order.
int *aend = a + an;
int *bend = b + bn;
while (a != aend && b != bend)
{
int candidate = *a;
++a;
while (*b < candidate && b != bend)
{
++b;
}
if (b != bend && candidate == *b)
{
result.push_back(candidate);
++b;
}
}
return result;
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Dec 2, 2011
by dmn:
It can be solved in O(nlogn) . For each number in the 1st array, do a binary search in the second one, if found - try comparing the two subsets.
Helpful Answer?
Yes | No
Inappropriate?
Dec 8, 2011
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
1 of 3 people found this helpful
Jan 3, 2012
by chandra shekhar:
for(int i=0,j=0; i < ar1.length && j < ar2.length;){
if( ar1[i] == ar2[j] )
System.out.println( ar1[i]);
if( ar1[i] < ar2[j])
i++;
else if ( ar1[i] > ar2[j])
j++;
else {
i++; j++;
}
}
Helpful Answer? }
===================
Given a set of strings, a number 'n', and a function that takes a string and gives back a score, find the n largest scored strings in the set.
Answers & Comments (5)
0 of 1 people found this helpful
Nov 30, 2011
by Steve:
Use a Max heap (a min heap where the x<=y operation is score(x) >= score(y)). It can be built in O(n) time. Extracting the maximum element (which is the root) take O(log(n)) , and you do it k times.
Anyway the idea is around sorting. There are tons of less efficient way but I am sure there is one or 2 more efficient way.
Helpful Answer?
Yes | No
Inappropriate?
Dec 1, 2011
by Anonymous:
{{{
int score(char *str)
{
int x = 0;
while (*str)
{
x += (int)*str++;
}
return x;
}
int partition(int *scores, char **s, int n)
{
int pivot = scores[0];
char *ps = s[0];
int small = n - 1;
int large = 1;
while (small > large)
{
if (scores[small] < pivot)
{
--small;
}
else if (scores[large] >= pivot)
{
++large;
}
else
{
int temp = scores[small];
scores[small] = scores[large];
scores[large] = temp;
char *st = s[small];
s[small] = s[large];
s[large] = st;
}
}
if (scores[small] < pivot)
{
--small;
}
scores[0] = scores[small];
s[0] = s[small];
scores[small] = pivot;
s[small] = ps;
return small;
}
char ** TopKScorer(char **s, int n, int k)
{
if (n <= k)
{
return s;
}
int *scores = new int [n];
for (int i = 0; i < n; ++i)
{
scores[i] = score(s[i]);
}
int goal = k;
char **cs = s;
int *c_scores = scores;
int length = n;
int current = -1;
while (1)
{
current = partition(c_scores, cs, length);
if (current == goal)
{
break;
}
if (current < goal)
{
goal -= (current + 1);
cs += (current + 1);
c_scores += (current + 1);
length -= (current + 1);
}
else if (current > goal)
{
length = current;
}
}
delete []scores;
return s;
}
}}}
Helpful Answer?
Yes | No
Inappropriate?
Dec 7, 2011
by Allen:
/*return the position of the ith smallest element(index start with 0). scores[index][0=str_key 1=value]*/
public static int quick_select(int[][] scores, int p, int r, int i) {
if(i > r || i < p) return -1;
if (p == r) {
return scores[p][0];
}
int q = partition(scores, p, r);
if (q == i) {
return scores[q][0];
}
if (q > i) /*ith is in the left pile*/ {
return quick_select(scores, p, q - 1, i);
}
return quick_select(scores, q + 1, r, i);
}
/*return the position of the selected pivot*/
private static int partition(int[][] scores, int p, int r) {
int x = scores[r][1];
int q = p;
for (int i = p; i < r; i++) {
if (scores[i][1] < x) {
int[] tmp = {scores[i][0], scores[i][1]};
scores[i][0] = scores[q][0];
scores[i][1] = scores[q][1];
scores[q][0] = tmp[0];
scores[q][1] = tmp[1];
q++;
}
}
int[] tmp = {scores[r][0], scores[r][1]};
scores[r][0] = scores[q][0];
scores[r][1] = scores[q][1];
scores[q][0] = tmp[0];
scores[q][1] = tmp[1];
return q;
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 9, 2011
by Anonymous:
Depending on the size of the string set, you have multiple possibilities here.
1. If the number of strings is reasonable and you can store the score for each one of these. Then the method you guys described, by using the idea from QSORT is perfect! :)
Complexity:
Time: O(M)
Space: O(M)
M is the number of strings! Good when M is reasonable as size.
2. If the set size is really big, and also you assume the strings come to you 1 by one, then the most efficient solution that I can see is to implement a Double Ended Priority Queue of maximum size N (Nth element). This can be done by using a Min-Max Heap.
The total complexity will be in this case:
Time: O(M * log (N))
Space: O(N)
M is the number of strings and N the Nth Element we want. Good method when N< st;
st.push_back(s);
while (!st.empty())
{
Point r = st.top();
if (solutions[r.i][r.j] != -1)
{
st.pop();
}
else
{
int solved = 1;
int c = 0;
if (r.i + 1 < n && a[r.i+1][r.j])
{
if (solutions[r.i+1][r.j] == -1)
{
st.push(Point(r.i+1, r.j));
solved = 0;
}
else
{
c += solutions[r.i+1][r.j];
}
}
if (solved && r.j + 1 < m && a[r.i][r.j + 1])
{
if (solutions[r.i][r.j+1] == -1)
{
st.push(Point(r.i, r.j + 1));
solved = 0;
}
else
{
c += solutions[r.i][r.j+1];
}
}
if (solved)
{
solutions[r.i][r.j] != c;
}
}
}
// need to de-allocate memory.
return solutions[s.i][s.j];
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 7, 2012
by Anonymous:
Since the question is finding all the paths, use DFS instead of BFS and don't end the search upon finding the first path.
=}}}
======================
Reverse all the words in a string
Answers & Comments (5)
Dec 1, 2011
by Anonymous:
package asaf;
public class ReverseWordsInString {
public static void main(String[] args) {
System.out.println(reverse("Reverse all the words in a string"));
}
private static String reverse(String s) {
String result = "";
String space = "";
for (String word : s.split(" ")) {
result = word + space + result;
space = " ";
}
return result;
}
}
Helpful Answer?
Yes | No
Inappropriate?
Dec 1, 2011
by â³â³â³â³â³â³â³â³
This post has been removed. Please see our Community Guidelines or Terms of Service for more information.
Dec 1, 2011
by another version:
This is another version that will reverse each word in place
package asaf;
public class ReverseWordsInString {
public static void main(String[] args) {
System.out.println(reverse(new StringBuffer("Reverse all the words in a string!")));
}
private static StringBuffer reverse(StringBuffer s) {
int fromIndex = 0;
int toIndex;
boolean reachTheEnd = false;
do {
toIndex = s.indexOf(" ", fromIndex);
if (toIndex == -1) {
reachTheEnd = true;
toIndex=s.length();
}
reverseWord(s, fromIndex, toIndex-1);
fromIndex = toIndex + 1;
} while (!reachTheEnd);
return s;
}
private static void reverseWord(StringBuffer s, int start, int end) {
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start++, s.charAt(end));
s.setCharAt(end--, temp);
}
}
}
// will print "esreveR lla eht sdrow ni a !gnirts"
Helpful Answer?
Yes | No
Inappropriate?
Jan 13, 2012
by Something different using String Buffers:
public class hello {
public static void main( String[] args) {
//reverse all words in a string
String reverseString =null;
StringBuffer reverseWord = null;
String string = "my name is hello";
String[] newstring = string.split(" ");
int i, j;
int wordLength = 0;
StringBuffer sb = new StringBuffer();
for (i = 0; i0;j--){
char character= newstring[i].charAt(j-1);
reverseWord =sb.append(character);
}
reverseWord = reverseWord.append(" ");
reverseString = reverseWord.toString();
}
System.out.print(reverseString);
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 15, 2012
by Liron:
String toRev = "I am very nice";
char[] toRevChar = toRev.toCharArray();
String res ="";
String word ="";
for (int i=0; i j){
return -1;
}
int mid = (i+j)/2;
if (arr[mid] == num){
return mid;
}
if (arr[mid] < num{
return binSer(mid+1,j,num,arr)
}
else {
return binSer(i,mid,num,arr)
}
})}
==========================
Analyze quick sort.
===============
Implementing a system for fast anagrams retrieval given a large file of words
Process the large file first. Create a hash table with key : sorted characters in the word. values : words from the large file.
Now all you gotta do is , take the word for which you want to find anagrams, sort the characters , lookup the hash table.
================
explain binary search, running time, when is it advantageous
=============
Write a code to find out if two string words are anagrams
Answers & Comments (3)
Oct 17, 2011
by Interview Candidate:
First way is to use HashMaps (quick but not memory use effective)
Second is to use arrays (memory effective but slower).
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 4, 2011
by Srini:
Sort the characters in the words. Compare them.
Complexity : O(n log n) depending on the sort algorithm.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Nov 12, 2011
by rob:
boolean areAnagrams?( String s1, String s2)
{
int s1Length = s1.length(), s2Length = s2.length();
if(s1Length != s2Length ) return false;
int[] frequencies = new int[128]; //assuming ascii. make a hash table for unicode
for( int i = 0; i < frequencies.length; i++)
{
frequencies[ i ] = 0;
}
for(int i = 0; i < s1Length; i++)
{
frequencies[ (int)s1.charAt(i) ]++;
}//now we have an int array corresponding to letter frequencies
for(int i = 0; i < s2Length; i++)
{
frequencies[ (int)s2.charAt(i) ]--;
}//now, if they are anagrams, all will be zero
for(int = 0; i < s1Length; i++)
{
if( frequencies[ (int)s1.charAt(i) ] )
{//evaluates to true for anything but zero
return false;
}
}
return true;
}}
=============
write a program to translate alphanumeric phone number to numbers only
Answers & Comments (3)
0 of 1 people found this helpful
Oct 17, 2011
by Interview Candidate:
Actual translation is easy. Store information is a hashmap (key,value) for example (abc, 2), (def,3) ...(wxyz, 9). You can get the information back very easily in O(1) time. Even when you have 20 characters in the alphanumeric string: 1(800)gofedex. It would still be very efficient O(20) etc...But extracting the information you need is somewhat complicated because you can't control what a user enters...lots of cases to consider...not in a 30 minute phone interview.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 21, 2011
by Greg:
Why wouldn't you map ..... ..? it reduces complexity of retrieval.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Oct 26, 2011
by Async:
You're saying you can't come up with a 10 line solution in 30 minutes but want a job at google? Once you came up with the crazy hashmap idea you had already failed the interview .... the solution to every problem is not a hashmap, especially when a simple lookup table will do.
======================
Create a graph class and graph traversal algorithms.
====================
've been contacted by their recruiters every 6 months or year for the past 6 or 7 years. Finally I was in the right place in my career to actually interview there, so I agreed.
The first step was a phone interview. The recruiter suggested a whole lot of studying material. I kinda skimmed "Programming Interviews Exposed", but I don't think it really made much of a difference at any point in the interview process. I feel like you either know your CS fundamentals or you don't and reading a book about them at the last minute isn't going to help much. Maybe I'm wrong.
This is my best tip for interviewing!: don't just discount your first answer because you think it's "too obvious"! It very well might be the right answer, and now you'll be lost searching for an even better answer that doesn't exist! If you think it's not right, just say "there might be a better way to do this, but I'm just brainstorming", and then explain what you're thinking. If there's a better way to do it, they'll let you know. I made this mistake twice in my interviews.
First there was a 45 minute phone interview. It was just two questions, one coding, and one more conceptual. It was pretty straightforward. The coding one was just something basic like implementing a binary search with a few tweaks.
Despite all the scary things people say, I felt like the in-person interview wasn't especially difficult, but I probably just lucked out with the group of interviewers I pulled. My friend told me he knows a ton of really smart people who didn't pass the in-person, so I shouldn't take it personally if I didn't either. That helped me relax and realize I just had to go in there and do my best and see what happened. I wasn't really nervous then and the interview mostly just felt like I was discussing interesting problems with co-workers. I think being relaxed really helped me get the job, so if you can... chill out. :)
Then things got really boring. At this point, it had been six weeks since I first started talking to the recruiter. Within three days, I was told that I'd passed the hiring committee. And after the I didn't get the offer for FOUR AND A HALF MORE WEEKS. That's 2.5 months total. The recruiter was very nice and apologetic about the whole process, but I feel like they need to do something to speed it up. It was a frustrating experience, knowing I'd passed the hiring committee and was probably hired, but then things just kept getting held up for weird reasons passing through all the other processes.
When the offer finally came, however, it was a good offer and I accepted immediately.
Negotiation Details
I didn't negotiate because the offer was above what I was hoping for. (I know I probably should have negotiated anyway, but I wimped out.)
=========================
What is the data structure behind hashmap
array of pointers.
if using open chaining it will be array of pointer to linked lists.
if using close chaining it will be just arrays.
=======================
Maximum contiguous sub sequence sum problem.
Detailed analysis and solution are available on the blog:
http://codercareer.blogspot.com/2011/09/no-03-maximum-sum-of-all-sub-arrays.html
======================
How would you reverse a linked-list?
Answers & Comments (3)
1 of 1 people found this helpful
Oct 3, 2011
by Anonymous:
http://www.teamten.com/lawrence/writings/reverse_a_linked_list.html
Element *reverse(Element *head)
{
Element *previous = NULL;
while (head != NULL) {
// Keep next node since we trash
// the next pointer.
Element *next = head->next;
// Switch the next pointer
// to point backwards.
head->next = previous;
// Move both pointers forward.
previous = head;
head = next;
}
return previous;
}
Helpful Answer?
Yes | No
Inappropriate?
Oct 5, 2011
by rumberobueno:
Good explanation in the comments.
Helpful Answer?
Yes | No
Inappropriate?
Oct 30, 2011
by Harry:
There are detailed analysis and solution in the blog:
http://codercareer.blogspot.com/2011/10/no-18-reverse-linked-list.html
=================
Find the most frequent letters in a string.
=======================
How to find anagrams in a sentence ?
Use Hashmaps with words as key to find anagrams
Helpful Answer?
Yes | No
Inappropriate?
Sep 29, 2011
by Anonymous:
1. prep your lexicon, sort each word of your dictionary, the resort the whole dictionary.
2. all duplicate entries are anagrams, make a list of duplicates.
3. sort each word in your sentence, and check if it exists in your new lexicon. A hashmap is a good way to go, but a binary search will work fine in a pinch.
4. consider building a couple indexes to make the process more robust.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Sep 30, 2011
by Kaustubh:
Hey
Take all alphabet and map with a prime number.
Like A = 2, B=3, C=5, D=7, E=11 etc.
Now read each word in the sentence and each word char by char and make a product of those with mapping prime num.
And store them in a map with key as product.
Each anagram will have same product of prime numbers.
====================
What's the complexity of insert in hashtable ?
O(1) average
==================
Given a number, and in a sorted list of permutations by the digits of the given number, what's the rank of the given number?
==========================
I had always wanted to work at Google, but I never thought I would get in. I'm 45 years old and I have a 2.2 GPA.
My friend at Google submitted my resume and I waited quite a while before I got a rejection letter. In retrospect, with them receiving 3000 resumes a day, it must be very easy to get lost in the shuffle unless your resume really stands out, and mine certainly did not. I waited a while and then contacted Google again and asked them to reconsider my resume, and they did. From that point on, it was an amazing process.
Right away I got an email asking when would be a good time for a recruiter to talk with me (HR screen). I said, "If not now, when?" and 60 seconds later I got a call from the recruiter. We talked for 45 minutes and mostly it seemed like just fun chitchat. She asked about my experience and what I liked to work on and what languages I preferred. Then she said she would find an engineer suitable for me and would call me back soon. She called the next day and we scheduled a phone interview (tech screen) for the following week. She also send me an email about what to expect and things to brush up on.
The next week I got the call from an engineer. We worked together in a Google Doc, and on the phone. He asked me about my resume, particularly my machine language experience. Then we did a bit manipulation problem, and I missed an obvious optimization. Then he asked me the main problem which was very clever. I came upon the solution very quickly, using recursion, but I screwed up on the complexity analysis. Afterwards, we chatted about Google life. It was a fun experience, but I figured I had blown it.
I got a call from the recruiter an hour later telling me that the feedback was positive and that we would move on to the on-site interview. I spent a month in front of my white board practicing problems, especially from Gayle Laakmann's book, Cracking the Coding Interview. I read through Introduction to Algorithms , but there was just too much information in there to cram into my brain.
At one point I was worried about my low 2.2 GPA and asked if I would be given a chance to explain the situation. I sent them an email and 30 seconds later one of the recruiters called me and said, basically, no one cares about your GPA. I get the impression that it's just a metric they use if there's nothing else on your resume to judge you by.
I am not going to describe the interviews here. Sorry. Not only did I sign an NDA, but I also don't want to spoil it for anyone. I will just say this much: Those people who said, "They asked me a simple CS101 question and I answered it and they still didn't hire me, those arrogant pricks!", well, dude you completely missed the point of the exercise. It's really not about getting the "right" answer.
The interviewers were all very cool. Some were reserved, and some were friendly and outgoing. I had a very fun time, but I missed a lot of simple things, didn't complete all of the problems, made simple syntax errors, and completely fumbled the interview that focused on Java. I left depressed, but feeling like I had been given a very fair chance.
I got a call from a recruiter two days later saying that the interview feedback was "pretty positive" and that he decided to forward it to the Hiring Committee. The following Monday the Hiring Committee gave me a "unanimous thumbs up". Another recruiter emailed me to say she would be contacting my references and my application would go through the Compensation Committee and the Executive Committee. I was given a questionnaire to fill out, asking about past employment details and such. It also asked about any past achievements I may want the Executive Committee to know about. They said I would probably hear something in the next few weeks.
Getting close to the end of the two week period, at 10:30pm, I got the email to "extend me an offer". When I replied to the email, she saw I was still awake so she called me on my cell phone at 11pm to give me the details as soon as possible. And the details were VERY generous, so I did not negotiate.
Overall, it was an awesome experience. Everyone was super nice and polite. The whole thing took two months, but a month of that was me asking for time to prepare. I've heard of cases where they can push it through in two weeks if you re really in a hurry. They kept asking me if I had any time constraint that they needed to work with. Also, yes, I asked, and Larry Page did review and sign off on my final approval. From his own words, he's gotten so good at it that it takes him less than a minute for each one.
I will only give this advice about the actual interview process: If you thought you aced it, you probably missed something. It's not about getting the "right" answer. It is about soooo much more. But, like I said, I don't want to spoil the fun.
=====================
Given a graph, find if it represents a tree.
Answers & Comments (3)
1 of 1 people found this helpful
Oct 15, 2011
by M H:
I think this can be done by traversing the graph in Breadth First manner, and if you happen to visit a node more than once, it is a graph, otherwise it is a tree
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Nov 21, 2011
by mike:
a tree is a graph with N-1 edges (N = number of vertices). then i think you just need to pick 1 vertex and check if you can reach all the others from this one
Helpful Answer?
Yes | No
Inappropriate?
Dec 29, 2011
by pat:
it depends on your definition of a tree. Technically all you need to qualify as a tree is to have that tree's nodes be connected and have no cycles. That means you don't necessarily need all the nodes of the graph to be part of the tree (that's called a spanning tree)
======================
Find the longest word in a dictionary, such that the word can be built one character at a time, and all substrings are words in the dictionary. A new character can be added anywhere.
===============
Deep search binary tree, what is the worst case memory requirement using Queue.
==============================
Given a large web query log file, how to find the most frequent K queries
=====================
Given a string of characters, find the character with the highest frequency.
Consider hashmap of counters approach, or array of counters depending on the range of valid characters.
===================
Design a networked 'snake' multiplayer game. What are the problems and issues to be solved? When the network 'splits' I want the game to continue for all players.
=====================
implement dijkstras algorithm
===================
Describe a data structure of your choice. (I chose a hash table) Followed up with questions about collision, Big O time of various operations.
==================
Write a function to convert a collection of strings into a single string and a function to convert it back.
==================
Given a bitmap of open and closed cells, where you can traverse through open cells but not closed ones and a set of origin points on the bitmap, write a program to find the shortest path to every reachable open cell from any of the origin points.
==================
how would you validate an xml?
====================
you have a file which contains no. from 100 to 999999999, but some nos. are missing. how would you find the missing nos.? - loading the whole file or keeping the file open for long time isn't desirable.
Answers & Comments (5)
0 of 2 people found this helpful
Aug 2, 2011
by Anonymous:
First I would ask if the numbers in the file are sorted, if yes a thread pool might be a good idea with indexes seeking at different position in the file depending on the worker thread. Since we do not want to load the all file limiting the number of worker thread with a partition of the file and each returning the missing value I think would work, suggestions ?
If the numbers are not sorted then it is a all different story ! I would use the same technique but first I would use multiple Thread or process to sort the file (maybe merge sort since it would work well in parallel because of its divide and conquer methodology) and then apply the above method. just some thought...
Helpful Answer?
Yes | No
Inappropriate?
Aug 4, 2011
by Alex:
Just use a hash, where keys are numbers. Then iterate through the sorted list of keys and push the missing ones into another list.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 11, 2011
by Anonymous:
The number are from 100 - (1 billion -1). If we use a bitset then we would need 1 billion bits = 125 MB. Assuming it'll fit in given memory we can do a 1 pass on the file and in the end just print out the cleared(0) bits of bitset starting from index 99 (100th bit).
Helpful Answer?
Yes | No
Inappropriate?
Sep 14, 2011
by bigo:
As it is clear requirement that file should not be loaded/open for long time. I think reading file in chunk and as alex also mention, having hash-map is faster solution then just using plan bit-set. Run-time complexity to set individual bit in bit-set based on number read from file is MORE than hash, which gives near O(1) complexity, but yes space complexity with hash is HIGH (could be "125MB + 125*8 MB" or 16*125MB)).
Helpful Answer?
Yes | No
Inappropriate?
Sep 14, 2011
by bigO:
mistake: space complexity seems to be (32*125MB + 8*125MB). Pls correct me if you find problem or have any better solution
=================================
u have a thick client application i.e. swings. two users are working on the app. one of them wants to update name field where as the other one wants to update company name.until the users are trying to update different field , they should be allowed to do that . when both are trying to modify the same field, one of them should be notified and the updated value should appear.
version number pattern
===================
Find the largest 100 numbers out of a list of a trillion unsorted numbers
Use a heap to hold the 100 largest numbers so far. If the new number is larger than the heap top (the smallest number in the heap) pop it out and add the new number.
The worst case complexity is O(N * log(100)). Hence log(100) is a small constant (7) the complexity should be good enough.
=====================
Implement a stack that pops out the most frequently added item.
Answers & Comments (2)
Jul 10, 2011
by Anonymous:
You could have a combination of two heaps: one indexed by value, and the other indexed by frequency of addition. Or a hash table and a heap, respectively. It depends on the applications and the balance between memory and processing time resources.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by Noel C.:
An additional comment: Nodes in the hash table and the heap must be shared (to save memory, and for convenience). Which means nodes should have links not only to their children, but their parents as well, so that rotations on the heap can be performed by lookup in the hashtable.
==================
Write a function to perform incremental search
You can use a trie that keeps track of frequencies in each node. When the user begins typing, you've selected one branch of the trie. The trick comes in selecting the branches, or leaves, with the most common occurrences.
A simple way to do this would be to do a traversal of the tree based on frequency at each level of the tree. You could do this with a linear search, or you could generate a max-heap for children at each level of the tree on-the-fly.
================
Write a function to caculate the angle between hour and minute hand on a clock.
Answers & Comments (7)
Jul 7, 2011
by Interview Candidate:
Just make sure u take account of the angle of hour hand
Helpful Answer?
Yes | No
Inappropriate?
Jul 12, 2011
by Oz:
public class Clock {
/** * @param args */
public static void main(String[] args) { System.out.println(getAngle(2,11));
}
public static double getAngle(int hours, int mins) {
System.out.println(hours * 30.0 + 30.0*mins/60.0);
System.out.println(mins*360/60);
double angle = Math.abs((hours * 30 + 30.0*mins/60.0) - (mins*360.0/60.0));
return angle; }
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2011
by anonymous:
Just few thoughts on interview process:
- why the interviewer attacks that way at beginning?
- when u know the answer, i think it's sort of honesty to say you had read this question before; then the interviewer might ask different ques, or he might ask to see how do u code it
- finally, why do you said "Received and Declined Offer", when you failed 2nd phone screen. No offense, just ask for correction.
Helpful Answer?
Yes | No
Inappropriate?
Jul 13, 2011
by OP:
Quick answers
1. I have no idea why.
2. I didn't see the question before but I solved it too quickly and he accused me.
3. Oops, this needs to be corrected.
Helpful Answer?
Yes | No
Inappropriate?
Jul 14, 2011
by Hasan Diwan:
Oz,
Your code has some bugs... the corrected code is below:
public class Clock {
public static void main(String[] args) {
System.err.println(getAngle(Integer.parseInt(args[0]),Integer.parseInt(args[1])));
}
public static double getAngle(int hours, int mins) {
double angle = Math.abs((hours * (360.0/12.0)) - ((60 - mins) / 5.0 * (360.0/12.0)));
return angle % 360.0;
}
}
Helpful Answer?
Yes | No
Inappropriate?
0 of 2 people found this helpful
Oct 12, 2011
by bensegar:
Sorry Hasan,
But I still don't think your code is correct. For example, if the time was 3:15, the angle should be 0 rather than 180 [ the output your code suggests. Similarly, if the time was 3:45, the angle should be 180 rather than 0 [ the output your code suggests. Why? because the question is the angle between the hour and the minute hand. I will post my solution soon. Its alot more complicated than people think!
Helpful Answer?
Yes | No
Inappropriate?
Dec 15, 2011
by anonymous:
Think of it this way:
First, you need to take the hour and do a modulo 12 on it, because there aren't 24 hours on a clock.
Next, every minute, the minute hand moves by 6 degrees (360/60).
Now, the hour hand does a complete rotation in 12 hours, that would be 30 degrees per hour (360 degrees / 12 hours)
Of course, as the minute hand rotates beyond H:00, the hour hand keeps advancing, so we need to account for that. We know it takes 60 minutes for the hour hand to advance by 30 degrees, so the correction is (fraction of an hour) * 30 degrees.
So the angle between 12 o'clock and the position of the hour hand (Ha) is:
Hour = Hour % 12 -> handle values past noon
Ha = 30*Hour -> position of the hour hand without correction
Ha = Ha + (Minute / 60 * 30 degrees) -> correction for the position of the hour hand
And the angle between noon and the minute hand (Ma) is:
Ma = 360 degrees / 60 minutes * Minute
And so the angle between the two hands is:
Abs(Ha - Ma)
For instance, for 14h20:
Hour = 14 % 12 = 2
Ha = 30 * 2 = 60 (uncorrected)
Ha = Ha + (20 / 60 * 30) = 70°
Ma = 360 / 60 * 20 = 120°
Angle between the two = 50°
Whenever you have a problem like this one, try to draw it on the board, and pick easy values, for instance 6:30, which is obviously not 0°, but half of the angle that represents 5 minutes, and you'll end up figuring it out pretty quickly.
]]
==================
Given an unsorted array of integers, find first two numbers in the array that equal a given sum.
Answers & Comments (5)
1 of 1 people found this helpful
Jul 1, 2011
by Interview Candidate:
Gave a O(n^2) solution by comparing each number to every other number, was asked to improve it.
Build a binary tree out of the array, do a traversal of the tree, and use the fact SUM = A + B, where A is the node you are currently visiting. Do a binary search of B. Was asked to come up with a O(N) solution.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 6, 2011
by kaustubh:
Sort the array. O(nlogn)
take two pointer at head( index 0 ) and tail (index array.length-1)
while (head sum)
tail--
else
print head and tail
}
Helpful Answer?
Yes | No
Inappropriate?
7 of 7 people found this helpful
Jul 6, 2011
by René:
The question is ill-posed. What does 'the first two numbers" mean? Suppose that the numbers at indices 1 and 100 add up to the given sum, as well as the numbers at indices 2 and 5, as well as those at indices 3 and 4. Which one of these three pairs constitute "the first two numbers"?
Finding a valid pair can be done in linear time with hashing: (1) hash al the numbers, together with their index in the array, into a hashmap (2) for every insertion of a number n, do a lookup of (sum - n) to check if that value is in the hashmap too. If so, you have found your pair.
Helpful Answer?
Yes | No
Inappropriate?
1 of 2 people found this helpful
Jul 14, 2011
by Tom:
Here you go, an excuse for me to play a bit with Ruby and an excuse for you to learn it:
def find2sum(array,desired_sum)
the_hash=Hash.new
i=0
array.each do |elt|
complement = desired_sum-elt
lookup = the_hash[complement]
if (lookup == nil)
the_hash[elt]=i
else
#puts "soln found, complement=#{complement} at index=#{lookup}, with #{elt} at #{i}"
return [lookup,i]
end
i=i+1
end
#puts "soln not found!"
return[-1,-1]
end
puts find2sum([39,5,15,3,7,9,16,30,23],30)
Helpful Answer?
Yes | No
Inappropriate?
Aug 3, 2011
by bt:
Ok im on a tablet so i ll keep it short.
make an array up to sum/2.
Scan thru the list.
If u find int represented by array or its counter part, mark the the space.
Eg 2+5 equals 7
if 2 or 5 comes along put that in 2.
Now do that until u bump into 5 or other number before. U know?
its easy just think bout it.
'
=============================
different types of sorting
=========================
C++ versus Java. Reverse a singly lined list.
reverse(Node n1, Node n2) {
Node newHead;
if (n2.next != null) newHead=reverse(n2, n2.next);
else newHead = n2;
n2.next = n1;
}
Helpful Answer?
Yes | No
Inappropriate?
Oct 8, 2011
by D:
to J, good stuff. remember to return newHead
==================
How to add a counter to www.google.com to track the billionth user.
Answers & Comments (3)
Jun 25, 2011
by Interview Candidate:
The idea is to have a distributed local counters and a good way to combine the local counters into one global counter. Another key property is to combine the results of local counters asynchronously in order not to slow down the search time.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by Anonymous:
Each server should keep track of the total number of users, and perform "edits" to this number.
At a specified time interval, servers should synchronize their counter by transmitted their aggregated "edits" to the total number of users.
"Edits" are simply how much to add to the sum.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by Noel C.:
Each server should keep track of the total number of users, and perform "edits" to this number.
At a specified time interval, servers should synchronize their counter by transmitted their aggregated "edits" to the total number of users.
"Edits" are simply how much to add to the sum.
======================
You have a 64bit interger counter set to 0. How long it will take to overflow the counter given that you are incrementing it at 4Ghz speed.
Answers & Comments (6)
0 of 2 people found this helpful
Jun 28, 2011
by grad stud:
60 years
Helpful Answer?
Yes | No
Inappropriate?
2 of 3 people found this helpful
Jul 2, 2011
by Praveen:
If we were to keep it simple and not consider every increment to be a load, increment, store then we basically need 2^64 increments to make the long overflow.
4GHz means 4*(2^30) instructions per second.. which is 2^32
effectively it is (2^64)/(2^32) = 2^32 seconds.. or roughly 136years.
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 18, 2011
by Parag:
total increments before overflow (tibo) = 2^64
increment speed(is) = 1 second / (4*10^9) increments | 4Ghz = 1x10^9 Hz
total seconds (ts) = 2^64 increments * (1 second /(4*10^9) increments)
ts = 4.611 * 10^9 seconds
total years = ts/(60*60*24*52) = 146.2 years
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
Jul 18, 2011
by correction(s) to above:
total years = ts/(60*60*24*7*52) = 146.2 years
and 4ghz = 4*10^9 Hz
Helpful Answer?
Yes | No
Inappropriate?
Jul 22, 2011
by Anonymous:
Please read the question carefully, it says counter is incrementing at the rate of 4GHz.
i.e, 4GB per second. Not incrementing every second.
So after elapsing first second, counter is at 4GB. After elapsing 2nd second, it is 4 + 4 = 8GB.
64 bit integer is, 2^64 = 2^32 * 2^32. Which is roughly 4GB * 4GB = 16GB.
So per second counter incremented to 4GB, so for 16GB it takes 4 seconds.
Helpful Answer?
Yes | No
Inappropriate?
Sep 17, 2011
by donutello:
Anonymous: 4GB * 4GB != 16 GB. You're ignoring the units!
To be accurate, the answer is 4G * 4G = 16 G^2 = 16 * 2^30 * 2^30.
Helpful Answer?
Yes | No
Inappropriate?
=======================
Comparisons of trees and hash tables. What are the tradeoffs of using one versus another.
=======================
Quickly estimate 2^64 without using a pen/papar.
Answers & Comments (5)
0 of 1 people found this helpful
Jun 27, 2011
by justaguye:
Well, 2^8 is 256 and 2^16 is that squared, which should have 5 digits..
If I square it again, I should have double those digits, and again if I square it again..
So I'm looking for something in the neighborhood of 1x10^20, or approx
10,000,000,000,000,000,000.
Calculator says: 18,446,744,073,709,551,616--> I'm in the ballpark.
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Jun 29, 2011
by Kaustubh:
2^10=1024 ~10^3
2^64=(2^10)^6 * 2^4
=> (10^3)^6*16
=> 10^18*16
=> 1.6 * 10 ^ 19
= 16,000,000,000,000,000,000
Calculator says: 18,446,744,073,709,551,616
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 1, 2011
by Saurabh:
2 ^ 10 = 1.024 * (10^3)
2 ^ 60 = (1.024 ^ 6) * (10 ^ 18)
2 ^ 64 = (16 * (1.024 ^ 6) * (10 ^ 18) )
All, we need to solve is 1.024 ^ 6. using binomial expansion, ignoring the smaller terms we get : (1 + 0.024) ^ 6 = 1 + 6 * 0.024 = 1.144 = 1.15 (approx)
Hence the answer is : (16 * 1.15) * (10 ^ 18) = 18.4 * (10 ^ 18)
It is much closer to the actual answer and very fast to calculate.
Helpful Answer?
Yes | No
Inappropriate?
Aug 3, 2011
by bt:
Donno if this is to test witt and prepness..
I would say 18,446,.... so on
He ll ask how i get that..
Say "calculator"
The question was about without using pen/paper
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Aug 25, 2011
by m:
2^32 ~= 4 bil
2^64 = 4bil * 4 bil
= 16 bil bil
each bil 9 0's, so 16 with 18 0's.
========================
Serialize an array of integers in an arbitrary way. Imagine a 4x4 grid where the cells are visited in a snakelike pattern.
Answers & Comments (5)
Jun 23, 2011
by Anonymous:
Here's a simple solution in Java for snake traversal of a 2D-Array
public static void snakeTraverse(int arr[][]) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
int m = i % 2 == 0 ? j : arr[i].length - 1 - j;
// do smt with the element
System.out.printf("%d ", arr[i][m]);
}
}
}
Helpful Answer?
Yes | No
Inappropriate?
Jun 26, 2011
by qadro:
The question is what kind of "snake-like" traversal they meant.
I'd expect it to be the diagonal snake-like which is much harder.
Helpful Answer?
Yes | No
Inappropriate?
Jun 26, 2011
by Anonymous:
Indeed, the question was to do a traversal across the diagonals, not along the rows/cols of the grid.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Jul 9, 2011
by Kunal Punjabi [email protected] :
I love solving problems like this. The trick here is to think through the edge cases with each iteration and build an algorithm that is generic enough to solve the problem at hand. With a 4x4 grid you would need to traverse the grid in the following order (note that an alternate order is possible depending on how you start, ie to the right first and then diagonally downward or downward first and diagonally upward)
(x,y) indicate row,column coordinates of an element in the 4x4 grid.
iteration 1: 0,0
iteration 2: 0,1 1,0
iteration 3: 2,0 1,1 0,2
iteration 4: 0,3 1,2 2,1 3,0
iteration 5: 4,0 3,1 2,2 1,3 0,4
iteration 6: 1,4 2,3 3,2 4,1
iteration 7: 4,2 3,3 2,4
iteration 8: 3,4 4,3
iteration 9: 4,4
int snakeTraverse(int len, int * grid) {
int max = len-1;
int row = 0;
int col = 0;
while ((row < max) && (col < max)) {
if ((row == 0) || (row == max)) {
if (col < max) { col++; } else {row++;}
while (col >0) {
col--;
row++;
printf (âgrid row=%d, col=%d, value = %dâ, row, col, grid[row][col]);
}
} else if ((col == 0 || (col==max)) {
if (row < max) { row++; } else {col++;}
while (row >0) {
col++;
row--;
printf (âgrid row=%d, col=%d, value = %dâ, row, col, grid[row][col]);
}
} else {
// impossible
}
}
}
My solution here goes to the right first - if you want to start off by going to the bottom first and then diagonally upward, then all you have to do is flip the order of the two if statements.
Helpful Answer?
Yes | No
Inappropriate?
Jul 10, 2011
by MBS:
Here is a shorter, if not simpler, version of achieving the diagonal snake traversal as described by Punjabi above:
//Assuming an mxm array
bool toggle false;
int i,j,k,minI, maxI;
for (int k=0; k<2m+1; ++k)
{
minI = k1){
int mid = low + (high-low)/2;
if(arr[mid]>value)
result = findNearestValue3(value, arr, low, mid);
else if(arr[mid] arr[mid])
low = mid + 1;
else
return arr[mid];
}
int diffLow = abs(value - arr[low]);
int diffHigh = abs(value - arr[high]);
if (diffLow < diffHigh)
return arr[low];
// Else
return arr[high];
}}
=============================
Design the friend suggestion of facebook, write a code, complexity,...
=============================
reverse a sentence such that the ordering of words is reversed but the words aren't changed
===================================
bacteria multiply 2x a day, and on the 50th day, there are 100 bacteria, how many were here on the 48th day.
nswers & Comments (5)
1 of 1 people found this helpful
Aug 3, 2011
by bt:
100? Cuase 2 power 50 doesnt seem to be close to a100. Hat means even with the multiplication. Too many dies along the way. Is that what they were looking for? Or 25...
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Sep 19, 2011
by Aditya:
Let n be the number of days
let x be the number of bacteria on day 1 (i.e n=1)
number of bacteria on day 2 (i.e n =2) = 2*x
number of bacteria on day 3 (i.e n =3) = 2*(2*x) = 4*x = [2^(n-1)]*x
thus, we get a pattern, which tells us that the number of bacteria on any given day = [2^(n-1)]*x
now when n=50, # of bacteria = [2^(50-1)]*x = [2^(49)]*x = 100;
therefore x = 100/[2^(49)] ...... (lets call this eq. 1)
# of bacteria on day 48 = [2^(48-1)]*x = [2^(47)]*x
substituting x in from eq. 1, we get
# of bacteria on day 48 = [2^(48-1)]*x = [2^(47)]*{100/[2^(49)]} = 25
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Sep 19, 2011
by Aditya:
also, since we have been given the number 48, which is just 2 short of 50, the number of bacteria on day 49 is going to be half of day 50 (i.e 100/2 =50) and the number of bacteria on day 48 will be half of day 49 )i.e 50/2 = 25).
Caution: we could calculate it this way because we were given a number close to 50 (the day for which we know the number of bacteria). in other cases, this will be hard to calculate. i,e. lets say that we are asked to calculate the number of bacteria on day 1000)
Helpful Answer?
Yes | No
Inappropriate?
Sep 29, 2011
by Duh:
With these kinds of doubling questions always work backwards, inverse thinking ie think backwards.
Helpful Answer?
Yes | No
Inappropriate?
Oct 18, 2011
by Anonymous:
is dat even valid? because 25 on 48th doesnot seem possible. two questions arise: 1) how many did we start with if multiplying 2X gives us 25 on 48th day and 2) how did we reach a odd number? - and only assumption that can lead to 25 on 48th day is some died.which nullifies d problem as we dont know how many died at each stage
========================
You are given an function which converts a string like "I work at Google" to "Google at work I". Write all the test cases you can think of for testing such a function.
- Test for null string
- Test for single character string like "a"
- Test for simple 2 word string like "a b"
- Test for multiple char 2 word strings like "abcd efgh"
- Test for multiple word strings
- Test for variable space length strings. Add spaces at the beginning and end of string.
===================
You are given a random binary tree 5 / \ 4 9 / \ / \ 3 5 6 8 Write code to print it out in order level ie 5 4 9 3 5 6 8 The tree need not be balanced. Write all the datastructures for the tree and make sure that you print newlines after each level. Also write test cases to test your code
Answers & Comments (2)
0 of 1 people found this helpful
Jun 9, 2011
by Interview Candidate:
Solution is to do a BFS on the binary tree. Now in order to print newlines, the datastructure inserted in the BFS queue also needs to contain level information which must be correctly updated while doing an insert in the queue.
Helpful Answer?
Yes | No
Inappropriate?
Aug 7, 2011
by Emre:
Here's a Java implementation (skipping imports etc.):
public class Pair {
F first;
S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
public class Node {
public int value;
public Node left;
public Node right;
public Node() {
}
public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
public static void printTreeLevels(Node root) {
Queue> q = new LinkedList>();
q.add(new Pair(root, 1));
int level = 1;
while(!q.isEmpty()) {
Pair pair = q.remove();
Node node = pair.first;
if(pair.second > level) {
System.out.println("");
level = pair.second;
}
System.out.print(node.value + " ");
if(node.left != null)
q.add(new Pair(node.left,(pair.second+1)));
if(node.right != null)
q.add(new Pair(node.right,(pair.second+1)));
}
}
}
}
=========================================
Describe a technical problem that you solved.
=======================================
Write a function that will return the second longest string in a list of strings. You have to do a single pass on the list.
Answers & Comments (2)
Jun 13, 2011
by lkcfree:
public int find2ndLongest(String[] strAry) {
int max_1 = 0;
int max_2 = -1;
if (strAry == null || strAry.length == 0) {
System.err.println(" Array is NULL or length is zero!!");
return -99;
}
if (strAry.length == 1) {
System.err.println(" Array length is ONE. No Max 2!!");
return -99;
}
int i = 0;
while (i < strAry.length) {
int lastMax = max_1;
if (strAry[i].length() > strAry[max_1].length()) {
max_2 = max_1;
max_1 = i;
} else {
if (max_2 < 0 || strAry[max_2].length() < strAry[i].length())
max_2 = i;
}
i++;
} //end while
return max_2;
}
Helpful Answer?
Yes | No
Inappropriate?
Jun 27, 2011
by medicine23:
while I agree with lkcfree's approach, the question asks to return the second longest "string", not the length itself.
Helpful Answer?
Yes | N
=============================================
Please design a iterator class.
======================
Design Google news.
========================
Design an RPC protocol.
=======================
What guarantees does the synchronized keyword give when used on a method? When a thread calls the synchronized method, can another thread call a method that isn't synchronized on the same object?
The synchronized keyword guarantees that a thread that thread calling the method cannot be preempted by another thread, eg. the thread wont be interrupted when its inside the scope of the synchronized method.
Another thread can call a non synchronized method on the same object when another thread is inside the synchronized method.
================
A google recruiter cold-called me on 3 Feb 2011 (I guess they got my résumé from an old co-worker?) and I was kinda bored so I aksed her to send me more info about the job. The recruiter sounded eerily stoked on both the company and the project (kept describing it all as "exciting"). By the end of the next week we had scheduled a phone interview for 22 Feb. (I wasn't in any sorta hurry).
Then I rescheduled the phone interview for a week later, 1 Mar. Shared google doc, the interviewer pasted some code and aksed me to find bugs in it and repair them. Some other question I don't remember. The topics were like race conditions in multi-threaded systems or something. It was nothing shocking, and the interviewer seemed to have a more muted stoke about working for google.
Two days later, the ultra-stoked recruiter called back with a second recruiter to invite me for an in-person. The second recruiter sounded pretty hepped up on the brand-name too. I think the second was a more senior recruiter. We scheduled an interview for 2 weeks later, 17 Mar.
They put me up in a hotel in Mtn View. The hotel was perfectly fancy, and had lots of nerd-themed items in the desk in the room (think weird Rubik's Cubes, puzzles made of heavy wire, &c). Next morning I woke up and drove to the googleplex. It was pretty, with ample parking, and a kinda agrestic setting. Flowers, vegetables, nerds. I waited in building 43 and watched people come in and out. it was easy to tell the difference between the home team and the visitors -- the googlers were the ones who looked super-jazzed, and the others looked uneasy.
I mean, noticeably super-jazzed.
The senior recruiter came `round and took me to the first interview room. I'd been scheduled for three interviews, but he told me they had found a fourth interviewer and would I mind staying longer for more probing. (I said I wouldn't mind.) The first interviewer came in, aksed a question about like statefulness in distributed systems or something, I wrote a big long answer on the board. he was mellow, genial, and helpful. The interview question wasn't too hard, and afterwards (when prompted) he expressed satisfaction with the company. He left, and another helpful, genial, and mellow engineer came in and aksed me some more basic cs stuff, and a question about how to build the back-end of a particular google product. She also expressed contentment with google as a place of employment.
The guy who gave me the phone interview came and took me to lunch.
We went to yet another building for my next interviews. A frankly-kinda-stressed-out-seeming engineer aksed questions about code prettification: namely, how to prettify the Java code I wrote on the white board. She took me to the next interview where a young guy aksed me a question about c-language bit-twiddling, and aksed a question about dynamic programming. my undergraduate cs courses were like 18 years previous, and I drew a blank. after futzing around w/ it for a bit, time was called and I drove home.
I sorta figured that it would end there, so I wasn't suprised when they didn't call back. Two weeks later though, the senior recruiter called back to tell me they almost had all the interview reports, and that they just needed one guy's report before making a decision.
Three days later, around 5 Apr, both recruiters started calling me and emailing me. I ignored them for a while, then finally phoned them back. They said they wanted me to talk with a few potential teams there to see if we could find a match.
Over the next two weeks I spoke with six or seven folks, engineers and managers both. The tone of the calls went from testing my domain-awareness to openly soliciting my membership in their teams.
Eventually (over the course of about a week) the recruiter reported the progress of my hiring order from hiring committee to I guess a second hiring committee to some kind of executive committee to the compensation manager to the executive approval, then they phoned me to tell me the nitty-gritty of the job offer.
It was pretty good, so I accepted.
======================
What subclasses of Collection do you know
====================
print binary tree in level order
Its a standard BFS question. A simple solution in Java would look like the following:
public static void printLevelOrder(BTNode tree){
Queue queue = new LinkedList();
queue.add(tree);
while(queue.size()>0){
BTNode node = queue.remove();
System.out.print(node.value+â â);
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
}
=====================
Interviewer ask me to solve some permutation related problems. 1) Algorithm to get Index of a permutation when all permutations arranged in lexicographical order and its complexity
Answers & Comments (4)
0 of 1 people found this helpful
May 2, 2011
by ---:
This is equivalent to searching in sorted array (which means that the word 'permutation' is here just to mislead you), that is, binary search. Complexity is O(log n)
By the way, linear scan in an array of all permutations of n-character string is O(n!)
Helpful Answer?
Yes | No
Inappropriate?
0 of 1 people found this helpful
May 6, 2011
by Scott:
you're a little off here. Using your definition of n, there are n! strings in the sorted array. Finding a particular one using binary search takes O(log n!) time.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 31, 2011
by anon:
The permutations in lexigraphic order look like this
012345
... ( 5!-1 more permutations that start with 0 )
102345
... ( 5!-1 more permutations that start with 1 )
201345
... ( 5!-1 more permutations that start with 2 )
So if the permutation starts with a 2 its position is
2 * 5! + (offset within the list that starts with a 2)
I think this is a start of an efficient recursive method for determining
the position, but in the recursion you have to translate the remaining
digits properly...
Helpful Answer?
Yes | No
Inappropriate?
Jun 24, 2011
by H-can:
Here's my solution in Java, which takes log(N) time to 'calculate' the position. N being the length of the permutation string.
Using a binary search ignores the fact that the list is not sorted but also complete, so we can calculate the position without going through the list.
public static int getPermIndex(String[] perms, String needle) {
// perms[0] is ordered letters, take it as reference
int itemsBefore = 0;
for (int i = 0; i < needle.length(); i++) {
char c = needle.charAt(i);
// check each char, if its not in the 'correct' position
// find the number of permutations comes before needle
int diff = c - perms[0].charAt(i);
if(diff>0)
itemsBefore += diff * fact(needle.length() - (i + 1));
}
return itemsBefore;
}
public static int fact(int n) {
if (n == 0 || n == 1)
return 1;
return n * fact(n - 1);
}
=====================
Discuss and implementation of flattening a binary search tree into string representations.
=========================
Describe a method to sift through dozens of emails and rank them based on 'importance'.
==========================
Ref to the game, Boggle, given a 3x3 grid of letters represented as a char array, generate all possible word combinations. The legal character sequences are horizontally or vertically adjacent chars. So in [A, B, C; D, E, F; G, H, I], ABCFI is legal but DFH is illegal.
Answers & Comments (1)
1 of 1 people found this helpful
Apr 18, 2011
by Anonymous:
Here's my clumsy TE way of implementing this problem. As you can see I use array[curPosition.X, curPosition.Y] notation, which should've been vice versa, but it works just as well.
--call--
char[,] matrix = new char[,] {{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}};
Arrays.GridWords(matrix, 3);
--implementation--
// assumes two-dimensional array with size as a size
public static void GridWords(char[,] array, int size)
{
List words = new List();
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
_gridWords(array, new Position(i, j), String.Empty, size, ref words);
}
}
foreach (string str in words)
{
Console.WriteLine(str);
}
}
private static void _gridWords(char[,] array, Position pos, string word, int size, ref List words)
{
string newWord = String.Format("{0}{1}", word, array[pos.X, pos.Y]);
if (!words.Contains(newWord))
{
words.Add(newWord);
}
List possibleGos = _goodNeighbors(array, pos, word, size);
for (int i = 0; i < possibleGos.Count; i++)
{
_gridWords(array, possibleGos[i], newWord, size, ref words);
}
}
// assuming size is size in arr[1] notation
private static List _goodNeighbors(char[,] array, Position curPos, string word, int size)
{
List list = new List();
if (curPos.X - 1 >= 0 && !word.Contains(array[curPos.X - 1, curPos.Y]))
{
list.Add(new Position(curPos.X - 1, curPos.Y));
}
if (curPos.X + 1 < size && !word.Contains(array[curPos.X + 1, curPos.Y]))
{
list.Add(new Position(curPos.X + 1, curPos.Y));
}
if (curPos.Y - 1 >= 0 && !word.Contains(array[curPos.X, curPos.Y - 1]))
{
list.Add(new Position(curPos.X, curPos.Y - 1));
}
if (curPos.Y + 1 < size && !word.Contains(array[curPos.X, curPos.Y + 1]))
{
list.Add(new Position(curPos.X, curPos.Y + 1));
}
return list;
}
==========================
Write down the algorithm of a Inorder Tree Traversal.
After he finished that question, I told him I already know how to do that if he wants to ask a different question. But he wanted me to write it.
So I told him, what are the requirements? Do we have unlimited CPU, Memory, Disk storage. The reason why I told him that is because there are Recursive Algorithms and Iterative algorithms.
So I wrote him an recursive algorithm in couple of minutes. Then he told me to write down an iterative algorithm. I told him sure I could use a stack like how they teach you in school, but it still doesn't make any difference than recursive,we still using a stack to put all the function calls.
So I told him to do a real iterative algorithm, we need to change the data structure a bit, where each node knows their parent. By knowing the parent, you can walk up the tree instead of maintaining a stack. That makes it really efficient.
===========================
Given two binary search trees, write function which tells if two such trees are the same â (i.e. same info in the nodes, same branching to left and right at every node).
Answers & Comments (6)
Mar 12, 2011
by Interview Candidate:
Recursive implementation was presented. Was asked to do non-recursive version (question was not about better solution, say, w/constant memory) â I proposed to change recursive algorithm to non-recursive with a user-defined stack (formal transformation rather boring but doable, FORTRAN people do it). Demonstrated that but code was messy with gotos, etc. Asked about complexity â both recursive and non-recursive versions required linear stack in worst case of pathological one-sided trees.
Helpful Answer?
Yes | No
Inappropriate?
Mar 26, 2011
by Java Dev:
// Something like this:
public boolean treesEqual(NodePair roots) {
Stack stack = new Stack();
stack.push(roots);
while(!stack.isEmpty()) {
NodePair nodes = stack.pop();
Node left = nodes.left();
Node right = nodes.right();
if(!nodesEqual(left, right)) return false;
if(left != null && right != null) {
stack.push(new NodePair(left.left(), right.left()));
stack.push(new NodePair(left.right(), right.right()));
}
}
return true;
}
Helpful Answer?
Yes | No
Inappropriate?
Apr 10, 2011
by Brad:
Another solution can be is, first check that the lengths and the roots are same for both the BST's and if they are, then do Inorder traversal to check if both are same. If all three conditions (same root, height and inorder then same BST's). If either root or height dont match then dont do inorder and return it as false.
Helpful Answer?
Yes | No
Inappropriate?
May 1, 2011
by Lucy:
Think of both trees as a heap representation (without heap properties), where the index of the root is 1, and index of a left child is (2 x index of its parent), and index of a right child is (1+ index of left child). Then traverse one tree in BFS fashion, at each node, do a BS on the second tree. If found, compare their indices.
The index can be calculated on the fly during traversing and BS, so you don't really need to copy the tree to an array or something.
This is just a theory in my head. I haven't really written code to prove it works.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 4, 2011
by Anonymous:
1) Pre order traversal both trees into strings then compare the strings.
Helpful Answer?
Yes | No
Inappropriate?
Dec 18, 2011
by Anonymous:
The code by Java Dev will fail if one tree is bigger than the other and they are identical for all the elements in the small tree.
================
Given two large files with 64-bit integers produce file with integers which are present in both files and estimate O(?) complexity of your algorithm.
Answers & Comments (3)
Mar 12, 2011
by Interview Candidate:
Proposed solution of splitting both files in n chunks (k integers in each) and solving n^2 subproblems while incrementally updating the result by merging sorted files of partial results (we will need to sort each chunk once). After algorithm was finalized, we checked the complexity and it was something cubic by n and k. Too bad. Navigated me to the solution to sort both files and find intersection by merging, this was better. As an afterthought I still think that when files do not have large overlap my solution might be winning as sorting original large files is not required (k should be selected so that each chunk could be sorted in memory, how about n=k=sqrt(file-size)?:).
Helpful Answer?
Yes | No
Inappropriate?
Apr 28, 2011
by Millin:
You can use bitmap sorting in O(n).
Create a bitmap of size 2^64, scan over the file and mark all numbers on the bitmap, then dump out the bitmap.
Helpful Answer?
Yes | No
Inappropriate?
Dec 18, 2011
by Anonymous:
Put one file into a hash table (Unordered_set in c++) and for each element in the other file check whether it is in the table. Lookup time is constant so complexity is linear.
Helpful Answer?
===============
Check whether the string is symmetric, how to test your result
Answers & Comments (6)
Jan 14, 2011
by NehaGupta:
#include
#include
using namespace std;
bool isSymmetric(string str)
{
int len = str.length();
for(int i=0;i> str;
cout << isSymmetric(str);
return 0;
}
Helpful Answer?
Yes | No
Inappropriate?
Jan 15, 2011
by Anonymous:
i is in scope of for, so u need to define i earlier to access it later!
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Jan 17, 2011
by Anonymous:
actually yo do not need to break from the algorithm, just return false when you find they are different, then return true after the iteration.
Helpful Answer?
Yes | No
Inappropriate?
Jan 27, 2011
by Anonymous:
The code is close to correct but will never return true
Helpful Answer?
Yes | No
Inappropriate?
Mar 30, 2011
by Jo:
#include
#include
using namespace std;
bool isSymmetric(string str)
{
int len = str.length();
int i = 0;
int j = len -1;
do
{
if (str[i] == str[j])
{
i++;
j--;
}
else
{
return false;
}
}
while(i> str;
cout < getTheNextLargerElement(BSTNode node, int x)
{
if(node == null)
return null;
BSTNode returned;
if(node.info > x)
{
returned = getTheNextLargerElement(node.left, x);
if(returned == null)
{
return node;
}
return returned;
}
return getTheNextLargerElement(node.right,x);
}
==================
Count bi-grams in a huge collection of documents grouped by source web site.
Use MapReduce, with the Key Values for Map being common bigrams and Values being each pair of letters in the website.
======================
* Write iterator class encapsulating in-order traversal of a binary tree. What is a time complexity? What is a worst case?
* You have a collection of html documents grouped by a source web site . You need to count frequencies of bi-grams across all documents and present it in a sorted order (may be return top N frequent bi-grams). How would you approach it? How to filter out non-significant bi-grams? How to distribute and merge? What data structures to use to keep counters?
* OOP. Write classes representing expression tree for a simple calculator. You care only about constants and basic binary operators. Write function evaluating expressions.
* N clients - M servers. Each server can handle limited number of queries/sec. How to improve availability and performance ?
* Write code to shift a string with rotation [a, b, c << 2 = 2 c, a, b]
* How to count frequencies of characters in a string. What if the string is too huge? When is it reasonable to distribute across machines? How to find the most frequent character in the distributed scenario with a minimum data exchange between machines?
* You are given a huge stream of geo coordinates. Unordered. Return list of objects in a specified radius from some point X.
=====================
Function for int2str
public static String int2str(int x) {
if (x == 0) return "0";
StringBuilder res = new StringBuilder();
while (x > 0) {
res.insert(0, (char)('0' + x % 10));
x /= 10;
}
return res.toString();
}
=====================
Design the battle ship game
=======================
Was asked to implement a Linked List insertion.
=======================
Was asked how I would implement division without using division or mod operators. The answer should return in the form quotient r remainder.
Answers & Comments (8)
Feb 9, 2011
by Interview Candidate:
Answer 1: Use subtraction and keep a count of how many times subtracted. When the remainder is smaller than the divisor, count is your answer, and whatever is left is the remainder.
Was then asked the complexity in terms of binary. After that, was asked to come up with a solution with better complexity.
Answer 2: Multiply the divisor by two until it is larger than the dividend. Go back one, subtract that out, multiply again. This solution will have a much better complexity.
Helpful Answer?
Yes | No
Inappropriate?
Feb 12, 2011
by NehaGupta:
I could not get second solution. Though its really interesting ....
e.g. 39/3
1. multiply 3 with 2 until it gets bigger 3->6->12->24->48 (using <<1)
2. Go back one 24 =>8
3. Sub that out 39-24 = 14
4. Go to 1
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Feb 13, 2011
by Anonym:
1. multiply 3 with 2 until it gets bigger than 29: 6,12,24,48
2. Go back one: 24 =>8
3. Sub that out: 39-24 = 15
1. multiply 3 with 2 until it gets bigger than 15: 6,12,24
2. Go back one: 12 =>4
3. Sub that out: 15-12 = 3
1. multiply 3 with 2 until it gets bigger than 3: 6
2. Go back one: 3=>1
3. Sub that out: 3-3 = 0
Answer: 8+4+1 = 13
Helpful Answer?
Yes | No
Inappropriate?
Feb 16, 2011
by Beau:
I think you're very close, but perhaps the interviewer was suggesting to think of the quotient in terms of being a binary number.
// QuickDivide, implemented in Java
public static String QuickDivide(int num, int denom)
{
int quotBits = 1; // start with a single bit quotient
int quot = 0;
// get number of quotient bits
while (Math.pow(2,quotBits) * denom < num)
{
quotBits++;
}
for (int bitExp = quotBits - 1; bitExp >= 0; bitExp--)
{
if (num >= Math.pow(2, bitExp)* denom)
{
// add to quotient and subtract from numerator
quot += Math.pow(2,bitExp);
num -= Math.pow(2, bitExp) * denom;
}
}
// numerator is holding remainder
return String.format("%1$d R %2$d", quot, num);
}
Helpful Answer?
Yes | No
Inappropriate?
Feb 18, 2011
by pit kelev:
// gets leftmost bit position
public native static int __builtin_clz(int n);
/**
* Divide x by y.
* @return {result, reminder}
*/
public static int[] div(int x, int y) {
int py = __builtin_clz(y);
int res = 0;
while(x > 0) {
int px = __builtin_clz(x) - py;
x -= y << px;
if (x < 0) {
x += y;
px--;
}
res += 1 << px;
}
return new int[] {res, x};
}
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Feb 22, 2011
by Pale:
Besides the returning format, and according the algorithm above, I would write in C the following function:
void div(int N, int D) {
int Q = 0;
int x = N;
int it = 1;
while (x >= D) {
if ( x < (D << it) ) {
x -= (D << (it-1));
Q += (1 << (it-1));
it = 0;
}
it++;
}
cout << "Quotient: " << Q << " Remainder: " << x << endl;
}
Helpful Answer?
Yes | No
Inappropriate?
Apr 24, 2011
by MrB:
public class Division
{
public static void main(String[] args)
{
int num = 23, denom = 7;
System.out.println(Divide(num, denom));
}
public static String Divide(int num, int denom)
{
int quotBits = 1; // start with a single bit quotient
int quot = 0;
// get number of quotient bits
while ((denom << quotBits) < num)
quotBits++;
for (int bitExp = quotBits - 1; bitExp >= 0; bitExp--)
{
if (num >= (denom< array[i+windowSize-1]){
minimum = array[i+windowSize-1];
}
System.out.println( minimum );
}
}
This should do it in O(n) time and o(1) space
Helpful Ans)))]}])})))})))))))))))
============================
))))""")))}))})))})))})}""""))))}))})})}}))}))})})")))}))})}))})))')))})")})]))}))}))})))))))})]})]]]]]]])))))))))))})}))})}}]])}}))})]])})}))))))))))))))))))})))}))})))))))}]))))}]))))}]))))}]))}])]])})))}))]"}}")}]))})))})})}]))'''}'''}'''}}]]])]'))})))))]')})]})'))))))))')))))))}))}))))`))"))"]])}}]])})"")})"")})}))
======================================
Given a tree and leaf node, write the code to make the leaf node as root of tree.
========================
Find all (english word) substrings of a given string. (every = every, ever, very)
Answers & Comments (3)
Feb 22, 2011
by Interview Candidate:
The real emphasis was on how to make it efficient.
Helpful Answer?
Yes | No
Inappropriate?
Feb 23, 2011
by NehaGupta:
Get A english dictionary using Trie and then look for each substring in that if exists.
Creating a trie is preprocessing.
Actually it will take o(n2) time after dictionary is ready for reference.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Feb 26, 2011
by Anonymous:
http://en.wikipedia.org/wiki/Directed_acyclic_word_graph
Use this instead. Uses less memory and can be more efficient.
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this question â Join Now (It's Free) or Sign In
You might also be interested in: Interview Questions, Software Engineer Interview Questions, Google Interview
Employees' Choice Winner: 2009, 2010, 2011, 2012
Google Overview (GOOG)
Edit
Website www.google.com
HQ Mountain View, CA
Industry
Internet Search & Navigation Services
Size
5000+ Employees, $23B+ Revenue
Competitors
Microsoft, Apple, Facebook
Featured Jobs
Software Engineer
Cadence Designs â San Jose, CA
From Cadence Designs â 12 days ago
Software Engineer
Texas Instruments â United States
From Texas Instruments â 24 days ago
Software Engineer
Norvax â Chicago, IL
From Norvax â 26 days ago
Software Engineer
Autodesk
From Autodesk â 21 days ago
Also try jobs in Istanbul:
TheLadders, Inc (122 jobs)
Interviews by Company
Microsoft Interview
Apple Interview
Accenture Interview
Booz Allen Hamilton Interview
Bank of America Interview
Salaries by Company
CNET Networks Salaries
IAC Salaries
NexTag Salaries
WebMD Health Salaries
About Us | F
==================================
Design a class to serialize / deserialze a graph.
adjacency list or adjacency matrix
=====================================
Design a class to process a matrix, and it needs to be able to return the average for the elements of arbitrary sub-rectangle inside that matrix, in constant time.
prefix sum
================================
Create a function which returns the angle of the clock's hour and minute hands.
First the problem is purposely obscure as it does not say whether the angle is accute or obtuse, so be sure to ask for this detail. Also, make sure you take into account the hour angle in relation to the minutes, as the hour is not always exactly on the hour marker.
=======================
Write code for Fibonacci algorithm (iterative or recursive) and explain what's the performance.
Recursive:
void fib(int k)
{
if(k==0)
return 0;
if(k==1)
return 1;
return fib(k-1)+fib(k-2);
}
Iterative:
void fib(int k)
{
if(k==0)
return 0;
if(k==1)
return 1;
int pre2Term =0;
int preTerm =1;
int retVal = 0;
for(int i=2 ; i<=k;i++)
{
retVal += preTerm + pre2Term;
pre2Term = preTerm;
preTerm = retVal;
}
return retVal;
}
Test:
fibTest()
{
int testInt = 3;
print(fib(testInt));
}
Iterative version of course has better performance because it doesn't need multiple function calls and program stacks to save variables.
Helpful Answer?
Yes | No
Inappropriate?
Apr 17, 2011
by SlzP:
When using recursive method, one way to improve performance is to store the computed values in a global array.
ex: To calculate Fib(5), we calculate Fib(4) + Fib(3)
Now Fib(4) again calculates Fib(3) & Fib(2) which is repeating the calculations
For large values of n, this leads to too many recursive calls. So, as and when we calculate Fib(k) we can store the value in a global array and reuse it to improve performance.
Helpful Answer?
Yes | No
Inappropriate?
}}}}}}}
========================
Given a set of shapes in 2D space, and a coordinate pair, write a routine that returns true if any of the shapes overlap the coordinate pair.
Answers & Comments (3)
Nov 29, 2010
by Arnab:
Assumption: The 2D shapes are rectangles. For any other types, the solution will become more involved.
The proposed solution involves using 2 bit vectors, one to keep track of X coordinates and the other to keep track of Y coordinates. Make a first pass through the shapes and determine the largest and smallest X coordinate and same for Y coordinate. Initialize 2 bit vectors of size (Xmax - Xmin + 1) bits and (Ymax - Ymin + 1) bits to 0. Make a second pass through the shapes, filling the bit vectors with 1 at the locations of the Y segments and X segments of all the shapes.
Now given a coordinate, just AND the y coordinate with the Y bit vector and the X coordinate with the X bit vector. If both operations return non zero results, the coordinate pair is contained within one of the shapes. Otherwise, it is not present inside the shapes.
Helpful Answer?
Yes | No
Inappropriate?
Nov 29, 2010
by Arnab:
The above solution uses O(n) time and O(Ymax - Ymin + Xmax - Xmin) space to build the hash table.
O(1) for any subsequent lookup.
Helpful Answer?
Yes | No
Inappropriate?
Nov 30, 2010
by lamont:
Good effort, Arnab, but I think the bit vector algorithm can give false positives in certain configurations of 2 or more rectangles. Consider point x and rectangles ## in this diagram:
^
| ##
| ## x
| ##
| ###
| ###
|--------------------->
The point is in the x-shadow of one rectangle and the y-shadow of the other, but lies within neither.
Here is a standard algorithm to determine if point (x, y) lies within a polygon with npol vertices (xp[i], yp[i]):
int pnpoly(int npol, float *xp, float *yp, float x, float y)
{
int i, j;
bool inside = false;
for (i = 0, j = npol-1; i < npol; j = i++) {
if ((((yp[i]<=y) && (y arr2.length ? arr1 : arr2;
int[] small = arr1.length > arr2.length ? arr2 : arr1;
for (int i = 0; i < small.length; i++) {
int n = binarySearch(big, small[i]);
if (n > 0) {
while ( n < big.length && big[n] == small[i]) {
System.out.printf("%d ", big[n]);
n++; i++;
}
break;
}
}
}
public static int binarySearch(int[] arr, int value){
int start=0, end=arr.length-1;
int mid = 0;
while(start<=end){
mid = start + (end - start)/2;
if(arr[mid]==value) return mid;
if(arr[mid]value) end = mid-1;
}
return -1;
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 23, 2011
by Vagrant:
Don't forget about the case of duplicate values.
A= 1 3 3
B= 2 3 3
You don't want to output 3 twice.
Helpful Answer?
Yes | No
Inappropriate?
Members c
====================
Answers & Comments (4)
6 of 6 people found this helpful
Mar 26, 2011
by baskin:
public static void printIntersectionOfSortedArrays(int []a, int []b)
{
int i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] == b[j]) {
System.out.println(a[i] + " ");
i++; j++; // INC BOTH
}
else if (a[i] < b[j]) {
i++;
}
else {
j++;
}
}
}
if one array is really larger than the other array:
iterate over smaller ans binary search in larger.
Helpful Answer?
Yes | No
Inappropriate?
May 11, 2011
by Anonymous:
Create a hash table.
hash[50] = 0;
Set hash[array1[i]] =1 for all elements in array 1.
loop through array2.
if hash[array2[i]] == 1, then true; // the element intersects...
this will work even if array 2 is longer than array 1.
Helpful Answer?
Yes | No
Inappropriate?
Jun 24, 2011
by H-can:
O(n log N)
where n size of smaller array
N size of bigger array
public static void printIntersection(int[] arr1, int[] arr2) {
int[] big = arr1.length > arr2.length ? arr1 : arr2;
int[] small = arr1.length > arr2.length ? arr2 : arr1;
for (int i = 0; i < small.length; i++) {
int n = binarySearch(big, small[i]);
if (n > 0) {
while ( n < big.length && big[n] == small[i]) {
System.out.printf("%d ", big[n]);
n++; i++;
}
break;
}
}
}
public static int binarySearch(int[] arr, int value){
int start=0, end=arr.length-1;
int mid = 0;
while(start<=end){
mid = start + (end - start)/2;
if(arr[mid]==value) return mid;
if(arr[mid]value) end = mid-1;
}
return -1;
}
Helpful Answer?
Yes | No
Inappropriate?
Jul 23, 2011
by Vagrant:
Don't forget about the case of duplicate values.
A= 1 3 3
B= 2 3 3
You don't want to output 3 twice.
Helpful Answer?
Yes | No
Inappropriate?
Members c
=======================
print out the powset of a set. use any programming language you want.
Answers & Comments (3)
Mar 24, 2011
by Interview Candidate:
not very sure
Helpful Answer?
Yes | No
Inappropriate?
Apr 12, 2011
by anon:
either recursively (not the best solution cause of stack):
if A = {1.2.3.4.5}, then the powerset of A is the the powerset(A[:-1]) (meaning the powerset of A without the 5 element) plus the sets of powerset(A[:-1]) appending the 5 element to each of them plus the set {5}
or with bits. All the length(A)-bit numbers where 0 at the ith position means element A[i] doesn't belong to the set and 1 means it does
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Apr 12, 2011
by X.X.:
If the set has n elements, each subset can be associated with a number k, 0 <= k < 2^n. Write k in binary representation. If i-th bit is on, the i-th element of the set is in subset k. Else i-th element is not there.
2^n will overflow for n = 64 for 64-bit integers. If desired to go beyond that, use a sequence of n numbers with each each number either 0 or 1 to emulate the n-bit integer k.
To go from the bit sequence for k to the bit sequence for k + 1 emulate how addition is done, by adding to a digit, and carrying over to the higher position digit if necessary.
Say start with the empty set, and stop when the full set is reached. That way it is not even necessary to compute 2^n which again could overflow.
Helpful Answer?
Yes | No
Inappropriate?
Members can answer or comment on this question â Join Now (It's Free) or Sign In
You might also be interested in: Interview Questions, Software Engineer Interview Questions, Google Interview
Employees' Choice Winner: 2009, 2010, 2011, 2012
Google Overview (GOOG)
Edit
Website www.google.com
HQ Mountain View, CA
Industry
Internet Search & Navigation Services
Size
5000+ Employees, $23B+ Revenue
Competitors
Microsoft, Apple, Facebook
Featured Jobs
Software Engineer
Cadence Designs â San Jose, CA
From Cadence Designs â 12 days ago
Software Engineer
Texas Instruments â United States
From Texas Instruments â 24 days ago
Software Engineer
Norvax â Chicago, IL
From Norvax â 26 days ago
Software Engineer
Autodesk
From Autodesk â 21 days ago
Also try jobs in Istanbul:
TheLadders, Inc (122 jobs)
Interviews by Company
Microsoft Interview
Apple Interview
Accenture Interview
Booz Allen Hamilton Interview
Bank of America Interview
Salaries by Company
CNET Networks Salaries
IAC Salaries
NexTag Salaries
WebMD Health Salaries
A
==============================
Q1) How to skim through 10,000 lines of code to find out any obvious mistakes?
Open the code in a IDE with static analysis tool, it will report problems right there ... etc. Kept telling about Java docs and naming conventions ... etc. Did not bother to mention about "cyclomatic complexity" and all that good stuff.
================================
Q2) compare quick sort and merge sort in space?
Quick sort is done "In space" so O(1), merge sort would take place in O(n).
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Apr 3, 2011
by Anonymous:
quicksort -> o(logn) (for stack space in case of recursive solution)
merge sort -> o(n)
==========================
Q3) While processing quick sort would take O(logn) space constraint, can you explain.
I was about to write a pseudo code so that I can derive the big O analysis on the space consumed. But not allowed to continue. Typing on the Google doc might have been an issue here. Not well connected with the conversation. You end up typing something, interviewer would be talking(asking) some thing different. Difficult to get all in same page.
Helpful Answer?
Yes | No
Inappropriate?
Dec 2, 2011
by mike:
Quicksort works in-place. It doesn't actually explicitly need more memory (besides constant memoery). The O(log N) space is due to the Log N recursive calls
==================
Q4) How to calculate Hamming distance between two integers, write code.
Answers & Comments (2)
Mar 23, 2011
by Interview Candidate:
i was looking for any Integer to Byte conversion ... etc ... etc [thinking that modulo 2 approach would be so kiddish). Questions started going towards fundamental understanding of java int ... etc ... etc. Didn't fly well.
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
Apr 3, 2011
by Anonymous:
xor the 2 numbers and count the number of 1s in the result. The number of 1s can be counted in different ways as explained in below link.
http://gurmeet.net/puzzles/fast-bit-counting-routines/#
=======================
Given a list L of n numbers. Write a function to return true if the sum of any two numbers of L equals to k; false otherwise.
Answers & Comments (3)
0 of 1 people found this helpful
Apr 3, 2011
by Anonymous:
assume all are positive numbers. O(n) to go through list and separate all numbers less than k. Let us say there are m numbers that are less than or equal to k.
There are m(m-1)/2 combinations of additions possible. A simple solution will be using 2 for loops(outer loop to select the first number and inner loop to select the 2nd number)
for (i=0; i O(n) time in all
3. If found return true else after iterating thru L return false.
Method 2: (no extra space)
1. Sort all elements => O(n log n) time
2. For every element "m" binary search for (k-m) => O(n log n) time for all elements in the worst case
3. return true when found else at end of array return false
Helpful Answer?
Yes | No
Inappropriate?
Jul 23, 2011
by Vagrant:
For method 2 (no extra space) there is no need to do a binary search for each element. After you sort the array, start adding the numbers from both ends, then move the ends inward. Move the larger end inward is the sum is larger than k. Move the small end inwards of the sum is less than k.
)]
==========================
Find the number of connected components in a Graph.
Depth search. When this is finished, a component is found. Go to a vertex not visited so far. Repeat depth search.
============================
questions on the running time of quicksort and selection sort
================================
In one of the questions in the interview they asked me to build a tree iterator for a binary tree
=================================
Given a list of strings return the substring representing the longest common prefix
b/w 2 strings -> the brute force method (comapre one by one until they are not equal).
divide and conquer the original problem by finding longest common prefix of every 2 strings, then lcp of the found lcps, and so on....
Helpful Answer?
Yes | No
Inappropriate?
1 of 1 people found this helpful
May 14, 2011
by Phishi:
Consider inserting the strings into a "trie" and keep track of the longest prefix.
================================
Describe Hashmap with details.
=====================
Write code for depth first search in a binary tree (iterative or recursive) and explain what's the performance.
=========================
Given a set of shapes in 2D space, and a coordinate pair, write a routine that returns true if any of the shapes overlap the coordinate pair.
Answers & Comments (3)
Nov 29, 2010
by Arnab:
Assumption: The 2D shapes are rectangles. For any other types, the solution will become more involved.
The proposed solution involves using 2 bit vectors, one to keep track of X coordinates and the other to keep track of Y coordinates. Make a first pass through the shapes and determine the largest and smallest X coordinate and same for Y coordinate. Initialize 2 bit vectors of size (Xmax - Xmin + 1) bits and (Ymax - Ymin + 1) bits to 0. Make a second pass through the shapes, filling the bit vectors with 1 at the locations of the Y segments and X segments of all the shapes.
Now given a coordinate, just AND the y coordinate with the Y bit vector and the X coordinate with the X bit vector. If both operations return non zero results, the coordinate pair is contained within one of the shapes. Otherwise, it is not present inside the shapes.
Helpful Answer?
Yes | No
Inappropriate?
Nov 29, 2010
by Arnab:
The above solution uses O(n) time and O(Ymax - Ymin + Xmax - Xmin) space to build the hash table.
O(1) for any subsequent lookup.
Helpful Answer?
Yes | No
Inappropriate?
Nov 30, 2010
by lamont:
Good effort, Arnab, but I think the bit vector algorithm can give false positives in certain configurations of 2 or more rectangles. Consider point x and rectangles ## in this diagram:
^
| ##
| ## x
| ##
| ###
| ###
|--------------------->
The point is in the x-shadow of one rectangle and the y-shadow of the other, but lies within neither.
Here is a standard algorithm to determine if point (x, y) lies within a polygon with npol vertices (xp[i], yp[i]):
int pnpoly(int npol, float *xp, float *yp, float x, float y)
{
int i, j;
bool inside = false;
for (i = 0, j = npol-1; i < npol; j = i++) {
if ((((yp[i]<=y) && (y x
end
return false
end
(Figured that checking up to 100 was good enough..)
Helpful Answer?
Yes | No
Inappropriate?
Sep 21, 2010
by Anonymous:
In C:
void findexponent(int x, int y)
{
int product=1; int i=0;
while (product <= x)
{
product *= y;
i++;
}
product /= y;
if (i==0 || product != x)
printf("No exponent");
else if (product == x)
printf("%d", i-1);
}
Helpful Answer?
Yes | No
Inappropriate?
2 of 2 people found this helpful
Oct 5, 2010
by Bartosz Milewski:
bool isPower(int x, int y)
{
int pow = 1;
while (x <= pow)
pow *= y;
return x == pow;
}
Notice that isPower(1, anything) is true because anything to the power of zero is one.
Helpful Answer?
Yes | No
Inappropriate?
4 of 4 people found this helpful
Oct 6, 2010
by pflau:
Just check if ln(x) / ln(y) is an integer.
Helpful Answer?
Yes | No
Inappropriate?
Nov 30, 2010
by lamont:
Bartosz' solution is a good start (once you flip the condition from x<=pow to x>pow). However, it fails to recognize two boundary conditions:
1. y = 0
2. Values of x and y that cause pow to overflow (y^i < x <= MAXINT < y^(i+1) for some value of i)
Both of these calls will enter an infinite loop:
isPower(2, 0);
isPower(2000000000, 2);
Below is one attempt to handle these boundary conditions.
bool isPower(int x, int y)
{
if (y == 0) return (x == 1); // zero^zero = one
int pow = 1;
while (x > pow) {
int p2 = pow * y;
if (p2 < pow) // would overflow?
break;
pow = p2;
}
return (x == pow);
}}}}}}}}