{"id":"6b093ddfbd4755deb67ee08f","slug":"product-except-self","title":"Product of all except self","summary":"For every position compute the product of the other elements – without division and in linear time. Prefix and suffix products, plus zeros.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["arrays","prefix-sums","prefix-products"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** result[i] = product of all elements except nums[i]; no division, O(n). */\nfunction productExceptSelf(nums: number[]): number[] {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":8,"tests":"// 0 and -0 are treated as equal (0 * -3 === -0 in JavaScript)\nconst norm = (values) => values.map((x) => (x === 0 ? 0 : x));\n\ntest('basic example', () => {\n  expect(norm(productExceptSelf([1, 2, 3, 4]))).toEqual([24, 12, 8, 6]);\n});\n\ntest('one zero', () => {\n  expect(norm(productExceptSelf([-1, 1, 0, -3, 3]))).toEqual([0, 0, 9, 0, 0]);\n  expect(norm(productExceptSelf([2, 0, -3, 4]))).toEqual([0, -24, 0, 0]);\n});\n\ntest('two zeros', () => {\n  expect(norm(productExceptSelf([0, 4, 0]))).toEqual([0, 0, 0]);\n});\n\ntest('negative numbers', () => {\n  expect(norm(productExceptSelf([-2, -3, 4]))).toEqual([-12, -8, 6]);\n});\n\ntest('single element and empty array', () => {\n  expect(productExceptSelf([5])).toEqual([1]);\n  expect(productExceptSelf([])).toEqual([]);\n});\n\ntest('two elements swap', () => {\n  expect(norm(productExceptSelf([7, -9]))).toEqual([-9, 7]);\n});\n\ntest('the input is not modified', () => {\n  const input = [3, 1, 2];\n  productExceptSelf(input);\n  expect(input).toEqual([3, 1, 2]);\n});\n\ntest('performance: 100 000 elements', () => {\n  const n = 100000;\n  const nums = Array.from({ length: n }, (_, i) => (i % 2 === 0 ? 1 : -1));\n  nums[500] = 2;\n  nums[99999] = 3;\n  const got = productExceptSelf(nums);\n  // product of everything: 50 000 factors of -1 (one replaced by 3) and one 2 → sign +1 · 2 · 3 · (-1)^49 999\n  const total = -6;\n  expect(got).toHaveLength(n);\n  expect(got[0]).toBe(total / nums[0]);\n  expect(got[500]).toBe(total / 2);\n  expect(got[99999]).toBe(total / 3);\n  expect(got[12345]).toBe(total / nums[12345]);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * result[i] = product of all elements except nums[i]; no division, O(n).\n * @param {number[]} nums\n * @returns {number[]}\n */\nfunction productExceptSelf(nums) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":8,"tests":"// 0 and -0 are treated as equal (0 * -3 === -0 in JavaScript)\nconst norm = (values) => values.map((x) => (x === 0 ? 0 : x));\n\ntest('basic example', () => {\n  expect(norm(productExceptSelf([1, 2, 3, 4]))).toEqual([24, 12, 8, 6]);\n});\n\ntest('one zero', () => {\n  expect(norm(productExceptSelf([-1, 1, 0, -3, 3]))).toEqual([0, 0, 9, 0, 0]);\n  expect(norm(productExceptSelf([2, 0, -3, 4]))).toEqual([0, -24, 0, 0]);\n});\n\ntest('two zeros', () => {\n  expect(norm(productExceptSelf([0, 4, 0]))).toEqual([0, 0, 0]);\n});\n\ntest('negative numbers', () => {\n  expect(norm(productExceptSelf([-2, -3, 4]))).toEqual([-12, -8, 6]);\n});\n\ntest('single element and empty array', () => {\n  expect(productExceptSelf([5])).toEqual([1]);\n  expect(productExceptSelf([])).toEqual([]);\n});\n\ntest('two elements swap', () => {\n  expect(norm(productExceptSelf([7, -9]))).toEqual([-9, 7]);\n});\n\ntest('the input is not modified', () => {\n  const input = [3, 1, 2];\n  productExceptSelf(input);\n  expect(input).toEqual([3, 1, 2]);\n});\n\ntest('performance: 100 000 elements', () => {\n  const n = 100000;\n  const nums = Array.from({ length: n }, (_, i) => (i % 2 === 0 ? 1 : -1));\n  nums[500] = 2;\n  nums[99999] = 3;\n  const got = productExceptSelf(nums);\n  // product of everything: 50 000 factors of -1 (one replaced by 3) and one 2 → sign +1 · 2 · 3 · (-1)^49 999\n  const total = -6;\n  expect(got).toHaveLength(n);\n  expect(got[0]).toBe(total / nums[0]);\n  expect(got[500]).toBe(total / 2);\n  expect(got[99999]).toBe(total / 3);\n  expect(got[12345]).toBe(total / nums[12345]);\n});\n"},{"lang":"python","runner":"browser","starter":"def product_except_self(nums: list[int]) -> list[int]:\n    \"\"\"result[i] = product of all elements except nums[i]; no division, O(n).\"\"\"\n    raise NotImplementedError\n","testCount":8,"tests":"def check(nums, expected):\n    got = product_except_self(nums)\n    assert got == expected, f\"product_except_self({nums[:8]}): expected {expected[:8]}, got {got[:8]}\"\n\n\ndef test_basic_example():\n    check([1, 2, 3, 4], [24, 12, 8, 6])\n\n\ndef test_one_zero():\n    check([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0])\n    check([2, 0, -3, 4], [0, -24, 0, 0])\n\n\ndef test_two_zeros():\n    check([0, 4, 0], [0, 0, 0])\n\n\ndef test_negative_numbers():\n    check([-2, -3, 4], [-12, -8, 6])\n\n\ndef test_single_element_and_empty():\n    check([5], [1])\n    check([], [])\n\n\ndef test_two_elements_swap():\n    check([7, -9], [-9, 7])\n\n\ndef test_input_is_not_modified():\n    data = [3, 1, 2]\n    product_except_self(data)\n    assert data == [3, 1, 2], f\"input changed: {data}\"\n\n\ndef test_performance_100k():\n    n = 100_000\n    nums = [1 if i % 2 == 0 else -1 for i in range(n)]\n    nums[500] = 2\n    nums[99_999] = 3\n    got = product_except_self(nums)\n    total = -6\n    assert len(got) == n, f\"expected {n} values, got {len(got)}\"\n    for i in (0, 500, 12_345, 99_999):\n        assert got[i] == total // nums[i], f\"result[{i}]: expected {total // nums[i]}, got {got[i]}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>result[i] = product of all elements except nums[i]; no division, O(n).</summary>\n    public static int[] ProductExceptSelf(int[] nums)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"class Solution {\n    /** result[i] = product of all elements except nums[i]; no division, O(n). */\n    static int[] productExceptSelf(int[] nums) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// ProductExceptSelf returns result[i] = product of all elements except nums[i]; no division, O(n).\nfunc ProductExceptSelf(nums []int) []int {\n\tpanic(\"not implemented\")\n}\n","testCount":8}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.195Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"In a pricing model each of "},{"type":"text","text":"n","marks":[{"type":"code"}]},{"type":"text","text":" factors (discounts, rates, multipliers) affects the final price. An analyst wants to know the outcome "},{"type":"text","text":"without","marks":[{"type":"bold"}]},{"type":"text","text":" each factor – for every one of them. Dividing the total product is out: factors can be zero."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"For an integer array "},{"type":"text","text":"nums","marks":[{"type":"code"}]},{"type":"text","text":" return an array "},{"type":"text","text":"result","marks":[{"type":"code"}]},{"type":"text","text":" where "},{"type":"text","text":"result[i]","marks":[{"type":"code"}]},{"type":"text","text":" is the product of all elements "},{"type":"text","text":"except","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"nums[i]","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"No division","marks":[{"type":"bold"}]},{"type":"text","text":", "},{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" time."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The input array must not be modified."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"For a single element the result is "},{"type":"text","text":"[1]","marks":[{"type":"code"}]},{"type":"text","text":" (the empty product), for an empty array – an empty array."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Signatures: "},{"type":"text","text":"productExceptSelf(nums)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"product_except_self(nums)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.ProductExceptSelf","marks":[{"type":"code"}]},{"type":"text","text":" (C#), "},{"type":"text","text":"Solution.productExceptSelf","marks":[{"type":"code"}]},{"type":"text","text":" (Java), "},{"type":"text","text":"ProductExceptSelf","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]},{"type":"heading","attrs":{"level":2,"id":"examples"},"content":[{"type":"text","text":"Examples"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nums","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[1, 2, 3, 4]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[24, 12, 8, 6]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[-1, 1, 0, -3, 3]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[0, 0, 9, 0, 0]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[0, 4, 0]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[0, 0, 0]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[5]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[1]","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"0 ≤ n ≤ 100,000","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"-30 ≤ nums[i] ≤ 30","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The product of every prefix and suffix fits in a 32-bit "},{"type":"text","text":"int","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" time, "},{"type":"text","text":"O(1)","marks":[{"type":"bold"}]},{"type":"text","text":" extra memory besides the result array."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/product-of-array-except-self/","title":"LeetCode 238 – Product of Array Except Self","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:55.197Z","updatedAt":"2026-11-27T08:22:55.197Z"}