◀ THE GRIND — ARRAYS & HASHING

Product of Array Except Self

MEDIUM✓ CHIP-TIMEDLC #238 — FULL STATEMENT ↗

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.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

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 HINTS — TAKE 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 BOARD — THE 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 SPLITS — TWO PACES, TWO LANGUAGES
grind/product-of-array-except-self.pyRACE 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-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED