Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Arrays & Hashing

Product of Array Except Self

MEDIUM✓ CHIP-TIMEDLC #238 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Compute, for every index, the product of all other values in the array — without ever dividing and without recomputing the whole product from scratch each time.

An array of integers arrives, and for every index the task is to report the product of all the other values in the array — everyone except that one position.

Division is off the table as a shortcut, since a zero anywhere in the array would break a divide-based approach; the product has to be assembled without ever dividing.

The output is its own array, the same length as the input, where each slot holds the product of everything except the value that started in that same slot.

  • arrays hold at least two elements
  • values may be negative, zero, or positive, including more than one zero
  • the running products always fit in a standard signed integer range
  • division is disallowed as a solving technique
EX 01
nums = [1, 2, 3, 4]
→ [24, 12, 8, 6]
EX 02
nums = [-1, 2, 0, -3]
→ [0, 0, 6, 0]
a single zero zeroes out every index but its own
EX 03
nums = [0, 0]
→ [0, 0]
two zeros zero out everything

The hintstake only what you need

HINT 1 THE NUDGE

Dividing the total product by nums[i] would give the answer in one pass, but a zero anywhere in the array breaks division. What structure avoids division entirely?

HINT 2 THE STRUCTURE

The product excluding index i splits cleanly into two halves: everything to its left times everything to its right. Both halves can be built as running totals.

HINT 3 ONE STEP FROM THE ANSWER

Fill the output with running prefix products left to right, then sweep right to left multiplying in a running suffix product — no division, and the second pass reuses the output array as its own storage.

Coach's boardthe pattern, step by step

PREFIX MEETS SUFFIXPATTERN · PREFIX × SUFFIX PASSESnums = [1, 2, 3, 4]
1
2
3
4
STEP 1

nums = [1, 2, 3, 4]. A left-to-right pass fills each slot with the running product of everything to its left.

STEP 1 / 10 · ← → WORK TOO

The splitstwo paces, two languages

grind/product-of-array-except-self.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = [1] * n
        prefix = 1
        for i in range(n):
            result[i] = prefix
            prefix *= nums[i]
        suffix = 1
        for i in range(n - 1, -1, -1):
            result[i] *= suffix
            suffix *= nums[i]
        return result
TIME O(N)SPACE O(1) EXTRAPYTHON · RACE PACE · 13 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED