Facebook | Phone Screen | Product of Array Except Self

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2019-08-19Added By Anonymous
Source: Link

Company: Meta
Role: e3, e4
Interview Stage: Phone Screen
Location: London, UK
Year: unknown

Original Post Content:

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[0];
  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 infinity.
But it was rejected. Might be I took long time.

Comments