Skills101
← All coding problems

Product of Array Except Self

mediumArrays & Hashing+20 XPTime limit 2s

For every position i, print the product of all the other numbers in the array (everything except a[i]).

Input:

  • line 1: n
  • line 2: n integers

Output: n numbers on one line — answer[i] = product of all a[k] with k ≠ i.

Constraints: 2 ≤ n ≤ 10⁵, −30 ≤ a[i] ≤ 30. Every product fits in a 64-bit integer (long / long long).

Rules: don't use division (zeros make it fail anyway). Aim for O(n): a product of everything to the left of i times everything to the right of i.

Sample input 1

4
1 2 3 4

Sample output 1

24 12 8 6

Sample input 2

5
-1 1 0 -3 3

Sample output 2

0 0 9 0 0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.