Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active October 31, 2017 13:32
Show Gist options
  • Save shailrshah/df0abdd821f062a159785357ff5b63a9 to your computer and use it in GitHub Desktop.
Save shailrshah/df0abdd821f062a159785357ff5b63a9 to your computer and use it in GitHub Desktop.
You have an array of integers, and for each index you want to find the product of every integer except the integer at that index.
// 1 2 3 4 nums
// 1 2 6 24 forward
// 24 24 12 4 backward
// 24 12 8 6 final nums
public int[] productExceptSelf(int[] nums) {
return getProductExceptSelf(nums, buildForward(nums), buildBackward(nums));
}
private static int[] buildForward(int[] nums) {
int[] forward = new int[nums.length];
forward[0] = nums[0];
for(int i = 1; i < nums.length; i++)
forward[i] = forward[i-1] * nums[i];
return forward;
}
private static int[] buildBackward(int[] nums) {
int[] backward = new int[nums.length];
backward[nums.length-1] = nums[nums.length-1];
for(int i = nums.length-2; i >= 0; i--)
backward[i] = backward[i+1] * nums[i];
return backward;
}
private static int[] getProductExceptSelf(int[] nums, int[] forward, int[] backward) {
nums[0] = backward[1];
nums[nums.length-1] = forward[nums.length-2];
for(int i = 1; i < nums.length-1; i++)
nums[i] = forward[i-1] * backward[i+1];
return nums;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment