Google Interview Question for Software Development Managers


Country: United States




Comment hidden because of low score. Click to expand.
7
of 7 vote

This problem is basically [matchine Nuts and bolts].

Solution to this problem is with help of quicksort.
1. pick any object A randomly, then compare it all B to find the exact match for it. This pivot in quicksort.
2. While searching for match divide B into two part with respect to pivot so this will make
all small object (of type B) than pivot on left side and all large object (of type B ) on right.. same as quicksort.
3. So at this point we find exact match for B as well as we aligend B. Now we can do the same thing on array of object A . Then repeat the process for on both halves.

Complexity will be (n lg n)

Note:-
We are doing this way we cant directly compare two A type of objects.

Ref:-
[http] www wisdom weizmann ac il/~naor/PUZZLES/nuts_solution.html

- Tester October 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think you are right, if we don't want to use space.

- lxh199124 October 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

How do you partition the first array from which you have selected randomly?.

EDIT: I got the solution. We can use the other array element to partition the first array.

- lodhi.harshil October 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This would assume that the compare function will also mention whether A is greater or lesser than B
If it was just a bool (like is_equal) it wouldnt work.
Or do we always assume "compare" implies it will give back smaller, equal and greater than ?

- AJK November 02, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

quicksort is O(n^2)

- nerdw/abs November 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This method is correct.
For the step1 and step2, do you mean going through B only for 1 time, you finish the both finding pivot and partitioning the array? If so, how do you do this? Can you provide the code? Thanks!

- allen.lipeng47 December 27, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 6 vote

You can use a hashTable to solve this problem.

Push all the 'A' object's with size as their keys. Then for each 'B' object, check if size of the object exists in HashTable.
RunTime : (Number of A objects + Number of B objects)
Memory: (Number of A objects)

- saran87 October 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

The function can only compare two objects, not look objects up by size. All you have are some A[] and B[] and some function bool compare(A a, B b).

- Anonymous October 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

To the 'anonymous' poster above, when he uses the sizes as the KEY in the hashtable, that creates the size lookup that he is referencing. Given that these are distinct elements (no duplicates) you could store <size, location> pairs of one of the arrays, then lookup and move elements in O(n) run time. The space complexity is O(n). This is a good workable solution. (I would recommend that the original poster mention the final sorting step to close the loop however.)

- masterjaso October 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What if size of the object A is much greater than limit of maximum number of elements in a hashtable? This solution may not work in that case. Moreover, if there are very less number of elements in the arrays, A[] and B[], and sizes of each element is huge, then you would end up wasting a lot of memory.
Correct me if I am wrong. Thanks :)

- Harsha November 10, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

(continuation to the above comment...)

Lets say that you are given both the arrays and a compare function (which has already been implemented) and nothing else, then I think your solution may not work(because you are not allowed to use any function other than compare).
Thanks.

- Harsha November 10, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

quick sort...

it's typical google question "nuts and bolts matching problem"

- Anonymous October 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import random

def compare_question(As, Bs):
    def f(A,B):
        # A is an int, B a string
        return cmp(A, len(B))

    if len(As) == 1:
        return [(As[0],Bs[0])]
    elif not As:
        return []

    pivot_B = Bs.pop(random.choice(range(len(Bs))))

    small_As, big_As = [], []
    for j in range(len(As)):
        A = As[j]
        if f(A, pivot_B) < 0:
            small_As.append(A)
        elif f(A, pivot_B) > 0:
            big_As.append(A)
        else:
            pivot_A_index = j

    pivot_A = As.pop(pivot_A_index)
    result = [(pivot_A,pivot_B)]

    small_Bs, big_Bs = [], []
    for B in Bs:
        if f(pivot_A, B) > 0:
            small_Bs.append(B)
        else: # has to be < now
            big_Bs.append(B)

    result += compare_question(small_As, small_Bs)
    result += compare_question(big_As, big_Bs)

    return result

print compare_question([1, 2, 4, 5, 6],
                       ["55555", "666666", "22", "1", "4444"])

- me November 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nice and concise solution! The only problem is memory consumption, since we create a lot of arrays. But in-place solution would be harder to read.

- damluar July 21, 2015 | Flag
Comment hidden because of low score. Click to expand.
-1
of 3 vote

I will preface my answer with the fact that the above answer utilizing a Hashtable runs faster than my answer by virtue of running in O(n) time instead of O(n log n). That being said, my answer has the potential to run in O(1) space complexity instead of O(n) space which is required of the Hashtable. Demonstrating both answers will show your interviewer your complete mastery.

This question is basically taking two randomly sorted arrays containing the same elements and asking that we match both arrays so that A[i] == B[i]. We know this from the fact that:

1. Both arrays are the same size
2. Both arrays contain the same 'object' type
3. The description 'Any object A is of the same size as exactly one object B'
4. The description 'All A's have different sizes, and all B's have different sizes'

So with a firm understanding that we have 2 unsorted lists of identical objects, the solution starts to materialize in the form of sorting. If we sort both lists, then all objects will satisfy the condition A[i] == B[i]. This means that we can get a run time complexity of O(n log n), and depending on the sort algorithm you can get O(1) space complexity by doing the sort in-place.

Quick code example in Java:

public void alignArrays(Object[] A, Object[] B){
		if(A.length != B.length) { return; }  //fail fast
		
		Arrays.sort(A);
		Arrays.sort(B);
	}

Note that we could have also made this a boolean return function and added a single for loop to ensure accuracy, but this type of error checking will increase our run time by O(2n) each call. We are given the assumption in the question that size, unique, and matching objects are guaranteed, but explaining your understanding of this concept can help further cement your understanding of the problem.

- masterjaso October 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This seems to not really be the problem statement. If you already know the arrays match, then why would you sort the second array -- you already know it'll match the first!

So then the problem is "sort an array", which doesn't seem like what would be asked.

- Anonymous October 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

But the problem statement does not indicate that either group of objects are sorted, merely that they contain matching distinct elements at a 1:1 ratio. If it provided one sorted and one non-sorted then yes we could simply sort one of the arrays and be finished. However, this is not the case based on the question. We therefore need to attack it with the information provided.

- masterjaso October 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Its mentioned that there are 2 distinct object types : A and B
They may not be similar.

And you cannot sort A alone, as you cannot compare 2 elements of A

- AJK November 02, 2014 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More