Facebook | Phone Screen | Product of Array Except Self

Location: London, UK

It was 45 minutes interview. Interviewer asked one question (but I think he was to ask another one): https://leetcode.com/problems/product-of-array-except-self

I give the solution in 2 min for Naive and Optimised. Code it in 35 min.

My solution
public int[] findProduct(int[] nums) {
	if(nums == null || nums.length == 0) return new int[];
	int[] ans = new int[nums.length];
	int product = 1;
	int index = -1;
	int numOfZeros = 0;
	for(int i=0; i<nums.length; i++) {
		if(numOfZeros > 1) return ans;
		if(nums[i] == 0) {
			numOfZeros++;
			index = i;
			continue;
		}
		product *= nums[i];
	}
	if(numOfZeros == 1) {
		ans[index] = product;
		return ans;
	}
	
	for(int i=0; i<nums.length; i++) {
		ans[i] = product / nums[i];
	}
	return ans;
}

Only handle use case with zero not with inifinity.
But it was rejected. Might be I took long time.

Comments (5)