Product of Array Except Self

medium Arrays

Problem

Read an array. For every position i print the product of all elements except a[i]. Do not use division. All results fit in 32 bits.

Constraints

  • 2 <= n <= 10^5
  • Every product fits in a 32-bit integer

Examples

Input

4
1 2 3 4

Output

24 12 8 6

Solutions

Best approachTime O(n)Space O(1) extra

Product except self = (product on the left) * (product on the right). Two passes build both without division, so zeros are no problem.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The products.
 * Approach: Left products, then right products.
 * Time    : O(n)
 * Space   : O(1) extra
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        int n = a.length;
        int[] result = new int[n];

        // Step 1: result[i] = product of all elements to the LEFT of i.
        result[0] = 1;
        for (int i = 1; i < n; i++) {
            result[i] = result[i - 1] * a[i - 1];
        }

        // Step 2: Walk from the right and multiply with the product of all elements to the RIGHT of i.
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            result[i] = result[i] * right;
            right = right * a[i];
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. How can you get the left product of every position in one pass?