Applied AI Engineer (LLM) coding learning path Level 2 This level · 31 of 31

Product of Array Except Self

Medium Single pass Prefix sum

Problem

Return an array where each position holds the product of all other elements, without using division and in linear time.

Original: LeetCode 238: Product of Array Except Self.

Examples

Example 1

Input`nums = [1, 2, 3, 4]`
Output`[24, 12, 8, 6]`

Example 2

Input`nums = [-1, 1, 0, -3, 3]`
Output`[0, 0, 9, 0, 0]`

Example 3

Input`nums = [2, 3]`
Output`[3, 2]`

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 238: Product of Array Except Selfleetcode.com
  2. JLS 17, 15.17.1: Multiplication operatordocs.oracle.com
Previous
Next