MEDIUM NC#6 Blind #4 Arrays & Hashing

238. Product of Array Except Self

๐Ÿ“– Problem

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Compute prefix products from left to right
  • โ†’ Compute suffix products from right to left
  • โ†’ Result[i] = prefix[i] * suffix[i]
  • โ†’ Can do in two passes without extra space for prefix/suffix arrays
  • โ†’ Time: O(n), Space: O(1) excluding result array

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขCompute prefix products from left to right
  • โ€ขCompute suffix products from right to left
  • โ€ขResult[i] = prefix[i] * suffix[i]

Common Pitfalls

  • โ€ขCan do in two passes without extra space for prefix/suffix arrays
  • โ€ขTime: O(n), Space: O(1) excluding result array

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
productExceptSelf([1,2,3,4]);
Expected:
[24, 12, 8, 6]
Test Case 2
Not run
Input:
productExceptSelf([-1,1,0,-3,3]);
Expected:
[0, 0, 9, 0, 0]
Test Case 3
Not run
Input:
productExceptSelf([1,0]);
Expected:
[0, 1]

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit