Google Interview Question for Software Engineer in Tests


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
17
of 23 vote

You can do it in 2N traversals. That is O(n). First find the product of N numbers and store it in a variable. Then, in the second traversal, traverse the array and divide by the element in each index and print the value.

- Kiran Kumar August 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think the same. Just do not forget to check the three cases with the count of the elements equal to 0 (at least do not devide by 0 check):
1.) cnt = 0 --> just the case you have mentioned
2.) cnt = 1 --> all the elements are 0 except the element == 0
3.) cnt > 1 --> all the elements are 0

- GKalchev August 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Few more checks
1. Integer/long overflow
2. multiplication of N-1 can give different results from multiplication of N and division of number at N.

I believe this is what interviewer want to ask the guy so this question :)

- R August 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hi Raj,
did not get your second point...
How it give different results? Can you give an example?

- Sanjay August 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

One example I can think of would be there is a 0 and overflow occurred

- Anonymous August 15, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You totally forgot the case of zeros and non-uniqueness of elements. I gave a solution - please correct me if I am doing any mistake. Thank you very much :)

- Dilbert Einstein September 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If there are any elements in the array that have a value = 0,
the entire output array will be zero except the elements that are zero.

for example
[2,3,0,4]

Output array
[3*0*4, 2*0*4, 2*3*4, 2*3*0]

- Anonymous March 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

I think question will be more interesting if we do the same without using division operator.
Ok, this also can be done in 2N element traversal. Just giving the possibility of questions to be asked!!

- Psycho August 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

how?

- mbriskar May 23, 2015 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

Assumption: All integers are unique (I explained for non-unique case below with some more assumptions)

If a zero exists:
product of non-zero values - just one value as output.
If no zeros:
take the product of all values in one iteration.
do second iteration - for each current value, o/p = product/current_value;
this will give n values of output.

If values are NOT unique:

if one zero: output=product of rest
if more than one zero: output=0 (just one output)
if no zeros: same as non-unique case (note that there will be repetition of values - assuming no deduping required.)

- Dilbert Einstein September 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

the code in java

package practicepackage;

public class SpecialMultiplication{

public static void main(String[] args)
{
	int[] numbers={1,2,3,4};
	int value=1;
	for(int i=0;i<numbers.length;i++)
	{
		value*=numbers[i];
	}
	for(int j=0;j<numbers.length;j++)
	{
		numbers[j]= value/numbers[j];
	}
	for(int k=0;k<numbers.length;k++)
	{
		System.out.println(numbers[k]);
	}
}

}

- codingAddicted August 10, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This case is a specific scenario. As mentioned above, what if one of the elements in the array is 0. This program will break down. Always check for corner conditions, divide by zero errors, etc!

- SSB December 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

#include<stdio.h>

int main(){
int array[] = { 4 , 0 , 7 , 6 , 8 , 0 , 8 , 78, 79, 2};
int len = 10;
long int product;
int i = 0;
int count = 0;

for(i = 0 ; i < len ; i++){
    if(array[i]==0){
        count++;
        continue;
    }
    product *= array[i];
}

for(i = 0 ; i < len ; i++){
    if(array[i])
        printf("%ld\t", (product/array[i]) );
    else{
        if(count = 1)    // IF THERE IS ONE 0 IN THE ARRAY
           printf("%ld", product );
        if(count > 1)    // HANDLES MULTIPLE 0s CASE
            printf("%d" , 0);
    }
}
}

- shantanudesai2009 August 11, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

product need to be initialized to 1

- kingpotter1990 October 07, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 3 vote

def multiply(alist):
	flist = [1] * len(alist)
	blist = [1] * len(alist)
	for i in range(1, len(alist)):
		flist[i] = alist[i - 1] * flist[i - 1]
	for i in range(len(alist) - 2, -1, -1):
		blist[i] = alist[i + 1] * blist[i + 1]
		
	return [x * y for x, y in zip(flist, blist)]

- gnahzy August 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is the ideal way to address the problem. There is no need for division or check for zeroes. And this follows classic dynamic programming.

And, if you prefer, there is a way to achieve this using only one output array.

- Prash September 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This solution is a good one, but it cost extra O(n) space. Is there any solution for O(1) extra space?

- little-eyes September 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

this is like calculating the product of all numbers in array except current element

void productArray(int arr[], int n)
{
int i, temp = 1;

/* Allocate memory for the product array */
int *prod = (int *)malloc(sizeof(int)*n);

/* Initialize the product array as 1 */
memset(prod, 1, n);

/* In this loop, temp variable contains product of
elements on left side excluding arr[i] */
for(i=0; i<n; i++)
{
prod[i] = temp;
temp *= arr[i];
}

/* Initialize temp to 1 for product on right side */
temp = 1;

/* In this loop, temp variable contains product of
elements on right side excluding arr[i] */
for(i= n-1; i>=0; i--)
{
prod[i] *= temp;
temp *= arr[i];
}

/* print the constructed prod array */
for (i=0; i<n; i++)
printf("%d ", prod[i]);

return;
}
Time Complexity: O(n)
Space Complexity: O(n)
Auxiliary Space: O(1)

- DG September 24, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
using namespace std;
#define N 8

int main(){
int A[]= {2, 3, 5, 40, 10, 16, 100, 9};
int i;
long long int pro=1;

for(i= 0; i< N; i++){
pro*= A[i];
}
for(i= 0; i<= N; i++)
cout<<pro/A[i]<<" ";
return 0;
}

- Abhijeet Rokade August 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does not work in case there is a zero in the array

- Anonymous August 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Let m=Multiplication of all numbers
output(i) =m/i;

- musfiqur August 25, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Construct two auxiliary arrays as follows :
A[0] = input[0]
A[i] = A[i-1]*input[i]
B[n-1] = input[n-1]
b[i] = b[i+1]*input[i]
Then, output[i]=a[i-1]*b[i+1]

- Qtpie August 26, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class GenerateProduct{
public static void generateProduct(int[] input){
long product = 1;
int count = 0;
int len = input.length;

for(int i : input){
if(i == 0){
count++;

if(count == 2){
for(int j = 0; j< len; ++j){
System.out.println(0);
}
return;
}

continue;
}
product *= i;
}


for(int i : input)
{
if(count == 1){
if(i == 0){
System.out.println(product);
continue;
}
else{
System.out.println(0);
continue;
}
}
else
System.out.println(product/i);
}

}
}

- Hans August 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class GenerateProduct{
    public static void generateProduct(int[] input){
    	long product = 1;
    	int count = 0;
    	int len = input.length;
	
    	for(int i : input){
    		if(i == 0){
    			count++;
		
    			if(count == 2){
    				for(int j = 0; j< len; ++j){
    					System.out.println(0);
    				}
    				return;
    			}
		
    			continue;
    		}
    		product *= i;
    	}

	
    	for(int i : input)
    	{
    		if(count == 1){
    			if(i == 0){
    				System.out.println(product);
    				continue;
    			}
    			else{
    				System.out.println(0);
    				continue;
    			}
    		}
    		else
    			System.out.println(product/i);
    	}

    }
}

- Hans August 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Arr {
    public static void prodOther(int[] a) {
        int p = 1;
        for (int entry : a) {
            if (entry != 0) {
                p *= entry;
            }
        }
        for (int i = 0; i < a.length; ++i) {
            a[i] = a[i] == 0 ? 0 : p / a[i];
        }
    }

    public static void main(String[] args) {
        int[] a = {2, 3, 4};
        prodOther(a);
        for (int e : a) {
            System.out.println(e);
        }
    }
}

- Anonymous September 28, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static long generateProduct(int[] arr){
long product = 1;
int zeros;
for(int a : arr){
if(a == 0){
zeros ++;
if(zeros > 1){
return 0;
}
}else{
product *= a;
}
}
return product;
}
public static void main(String args[]){
int[] arr = new int[] {1,2,3,4};
long product = generateProduct();
for(int a : arr){
System.out.println(product/a);
}
}

- Badal Shah November 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Python:

def missing_product(ints):
    product = reduce(lambda x,y: x*y, ints)
    return [product / i for i in ints]

- X May 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int[] calculateSpecialZero(int[] array) {
        int total = 1;
        boolean zeroSeen = false;
        for(int i = 0; i < array.length; i++) {
            if(array[i] == 0) {
                zeroSeen = true; // do not record it in out total
            } else {
                total *= array[i];
            }
        }
        // now we have total we can replace array values
        for(int j = 0; j < array.length; j++) {
            if(zeroSeen) {
                if(array[j] == 0) {
                    array[j] = total;
                } else {
                    array[j] = 0;
                }
            } else {
                array[j] = total / array[j];
            }
        }
        return array;
    } // O(N) with only O(1) space

- awallace July 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is C++ solution...

#include<iostream>
using namespace std;

void printProduct(int* arr, int n){
	if (n <= 0)
		return;

	int product = 1;
	int zero = 0;
	for (int i = 0; i < n; ++i){
		if (!arr[i])
			zero++;
		else
			product *= arr[i];
	}

	if (zero>1){
		for (int i=0; i < n; ++i)
			cout << 0 << " ";
	}
	else if (zero == 1){
		for (int i = 0; i < n; ++i)
			if(!arr[i])
				cout << product << " ";
			else
				cout << 0 << " ";
	}
	else{
		for (int i = 0; i < n; ++i)
			cout << product/arr[i] << " ";
	}
	cout << endl;
}

int main(){
	int arr[5] = { 5, 1, 0, 3, 0};
	printProduct(arr, 5);
	return 0;
}

- AndyC April 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def genRand(num):
    b = 1
    result = []
    for i in range(len(num)):
        for j in range(len(num)):
            if j != i:
                b *= num[j]
        result.append(b)
        b = 1
    return result

- mora December 10, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

def get_ans(array):
	result=[1]*len(array)
	for i in range(len(array)-2,-1,-1):
		result[i]=result[i+1]*array[i+1]
	left=1
	for j in range(0,len(array)):
		result[j] *=left
		left *=array[j]
	print(result)

- Sikandar April 06, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def get_ans(array):                                          
    result=[1]*len(array)                                    
    for i in range(len(array)-2,-1,-1):                      
        result[i]=result[i+1]*array[i+1]                     
                                                             
    left=1                                                   
    for j in range(0,len(array)):                            
        result[j] *=left;                                    
        left *= array[j]                                     
                                                             
    print(result)                                            
                                                             
arra=[10, 4, 1, 6, 2]                                        
                                                             
get_ans(arra)

- Sikandar April 06, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def get_ans(array):  
		result=[1]*len(array)                
		for i in range(len(array)-2,-1,-1):  
    			result[i]=result[i+1]*array[i+1] 
                                     
		left=1                               
		for j in range(0,len(array)):        
    			result[j] *=left;                
    			left *= array[j]                 
                                     
		print(result)

- sikandar April 06, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 votes

Are you google employee? Since it was asked in Google, can you provide your thinking that what would you be looking in this question and what would be accurate solution?

- Andy2000 August 27, 2012 | 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