Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #238: Product of Array Except Self

In this guide, we solve Leetcode #238 Product of Array Except Self in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Prefix Sum

Intuition

Range queries become simple once we precompute cumulative sums.

We can transform subarray conditions into prefix comparisons.

Approach

Compute prefix sums and use a map to find matching prefixes.

This avoids nested loops while keeping the logic clear.

Steps:

  • Compute prefix sums.
  • Use a map to find valid ranges.
  • Update the answer.

Example

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

Python Solution

class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) ans = [0] * n left = right = 1 for i, x in enumerate(nums): ans[i] = left left *= x for i in range(n - 1, -1, -1): ans[i] *= right right *= nums[i] return ans

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the array nums\textit{nums}nums. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy