🪙
Leetcode
  • Content
  • Algorithms
    • Linear Search
    • Binary Search
    • Counting Sort
    • Merge Sort
    • Insertion Sort
    • Selection Sort
  • Array and String
    • Introduction to Array
      • Introduction to Array
      • Introduction to Dynamic Array
      • Find Pivot Index
      • Largest Number At Least Twice of Others
      • Plus One
    • Introduction to 2D Array
      • Introduction to 2D Array
      • Diagonal Traverse
      • Spiral Matrix
      • Pascal's Triangle
    • Introduction to String
      • Introduction to String
      • Immutable String - Problems & Solutions
      • Add binary
      • Implement strStr()
      • Longest Common Prefix
    • Two-Pointer Technique
      • Two-pointer Technique - Scenario I
      • Reverse String
      • Array Partition I
      • Two Sum II - Input array is sorted
      • Two-pointer Technique - Scenario II
      • Remove Element
      • Max Consecutive Ones
      • Minimum Size Subarray Sum
    • Conclusion
      • Array-related Techniques
      • Rotate Array
      • Pascal's Triangle II
      • Reverse Words in a String
      • Reverse Words in a String III
      • Remove Duplicates from Sorted Array
      • Move Zeroes
  • Linked List
    • Singly Linked List
      • Introduction - Singly Linked List
      • Add Operation - Singly Linked List
      • Delete Operation - Singly Linked List
      • Design Linked List
    • Two Pointer Technique
      • Two-Pointer in Linked List
      • Linked List Cycle
      • Linked List Cycle II
      • Intersection of Two Linked Lists
      • Remove Nth Node From End of List
      • Summary - Two-Pointer in Linked List
  • Problems
    • 1. Two Sum
    • 2. Add Two Numbers
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 11. Container With Most Water
    • 12. Integer to Roman
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 15. 3Sum
    • 21. Merge Two Sorted Lists
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Find the Index of the First Occurrence in a String
    • 34. Find First and Last Position of Element in Sorted Array
    • 35. Search Insert Position
    • 43. Multiply Strings
    • 49. Group Anagrams
    • 50. Pow(x, n)
    • 54. Spiral Matrix
    • 58. Length of Last Word
    • 66. Plus One
    • 67. Add Binary
    • 69. Sqrt(x)
    • 73. Set Matrix Zeroes
    • 75. Sort Colors
    • 88. Merge Sorted Array
    • 104. Maximum Depth of Binary Tree
    • 121. Best Time to Buy and Sell Stock
    • 122. Best Time to Buy and Sell Stock II
    • 136. Single Number
    • 146. LRU Cache
    • 189. Rotate Array
    • 206. Reverse Linked List
    • 217. Contains Duplicate
    • 219. Cotains Duplicate II
    • 226. Invert Binary Tree
    • 238. Product of Array Except Self
    • 242. Valid Anagram
    • 268. Missing Number
    • 283. Move Zeroes
    • 350. Intersection of Two Arrays II
    • 383. Ransom Note
    • 389. Find the Difference
    • 412. Fizz Buzz
    • 414. Third Maximum Number
    • 445. Add Two Numbers II
    • 448. Find All Numbers Disappeared in an Array
    • 459. Repeated Substring Pattern
    • 485. Max Consecutive Ones
    • 509. Fibonacci Number
    • 637. Average of Levels in Binary Tree
    • 657. Robot Return to Origin
    • 682. Baseball Game
    • 704. Binary Search
    • 705. Design HashSet
    • 709. To Lower Case
    • 724. Find Pivot Index
    • 876. Middle of the Linked List
    • 896. Monotonic Array
    • 860. Lemonade Change
    • 905. Sort Array By Parity
    • 916. Word Subsets
    • 941. Valid Mountain Array
    • 976. Largest Perimeter Triangle
    • 977. Squares of a Sorted Array
    • 1041. Robot Bounded In Circle
    • 1051. Height Checker
    • 1089. Duplicate Zeros
    • 1232. Check If It Is a Straight Line
    • 1275. Find Winner on a Tic Tac Toe Game
    • 1295. Find Numbers with Even Number of Digits
    • 1299. Replace Elements with Greatest Element on Right Side
    • 1342. Number of Steps to Reduce a Number to Zero
    • 1346. Check If N and Its Double Exist
    • 1476. Subrectangle Queries
    • 1480. Running Sum of 1d Array
    • 1491. Average Salary Excluding the Minimum and Maximum Salary
    • 1502. Can Make Arithmetic Progression From Sequence
    • 1523. Count Odd Numbers in an Interval Range
    • 1572. Matrix Diagonal Sum
    • 1672. Richest Customer Wealth
    • 1768. Merge Strings Alternately
    • 1752. Check if Array Is Sorted and Rotated
    • 1769. Minimum Number of Operations to Move All Balls to Each Box
    • 1790. Check if One String Swap Can Make Strings Equal
    • 1800. Maximum Ascending Subarray Sum
    • 1822. Sign of the Product of an Array
    • 1930. Unique Length-3 Palindromic Subsequences
    • 1991. Find the Middle Index in Array
    • 2185. Counting Words With a Given Prefix
    • 2235. Add Two Integers
    • 2236. Root Equals Sum of Children
    • 2270. Number of Ways to Split Array
    • 2381. Shifting Letters II
    • 2559. Count Vowel Strings in Ranges
    • 2610. Convert an Array Into a 2D Array With Conditions
    • 2657. Find the Prefix Common Array of Two Arrays
    • 3042. Count Prefix and Suffix Pairs I
    • 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
    • 3151. Special Array I
    • 3223. Minimum Length of String After Operations
Powered by GitBook
On this page
  • Example 1
  • Example 2
  • Constraints
  • Solution
  • Optimal Solution
  • Approach Analysis
  • Visualization of Both Approaches
  • Complexity Analysis
  • Why Solution Works
  • When to Use
  • Common Patterns & Applications
  • Interview Tips

Was this helpful?

Edit on GitHub
  1. Problems

238. Product of Array Except Self

🟧 Medium

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.

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]

Constraints

  • 2 <= nums.length <= 10^5

  • -30 <= nums[i] <= 30

  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Solution

My Solution

func productExceptSelf(nums []int) []int {
  res := make([]int, len(nums))

    left := 1
    for i ,num := range nums {
        res[i]=left
        left *= num
    }
    
    right := 1
    for i:=len(nums)-1; i>=0; i-- {
        res[i]*=right
        right*=nums[i]
    }

  return res
}

Optimal Solution

The optimal solution uses prefix and suffix products without using division:

func productExceptSelf(nums []int) []int {
    n := len(nums)
    result := make([]int, n)
    
    // Initialize result array with 1s
    result[0] = 1
    
    // Calculate prefix products
    for i := 1; i < n; i++ {
        result[i] = result[i-1] * nums[i-1]
    }
    
    // Calculate suffix products and combine with prefix
    suffix := 1
    for i := n-1; i >= 0; i-- {
        result[i] *= suffix
        suffix *= nums[i]
    }
    
    return result
}

Approach Analysis

The solution uses two key techniques:

  1. Prefix Products:

    • Calculate products of all elements to the left

    • Store intermediate results in output array

    • Build up products from left to right

  2. Suffix Products:

    • Calculate products of all elements to the right

    • Combine with prefix products

    • Use single variable to save space

Visualization of Both Approaches

Input: [1,2,3,4]

Step 1: Calculate Prefix Products
Initial: [1, _, _, _]
After 1: [1, 1, _, _]
After 2: [1, 1, 2, _]
After 3: [1, 1, 2, 6]

Step 2: Calculate Suffix Products
suffix = 1
[1, 1, 2, 6] * [24, 12, 4, 1]
= [24, 12, 8, 6]

Detailed Steps:
i=3: result[3] = 6 * 1 = 6,    suffix = 4
i=2: result[2] = 2 * 4 = 8,    suffix = 12
i=1: result[1] = 1 * 12 = 12,  suffix = 24
i=0: result[0] = 1 * 24 = 24,  suffix = 24

Final Result: [24, 12, 8, 6]

Complexity Analysis

Time Complexity:

  • O(n) - two passes through the array

  • First pass: prefix products

  • Second pass: suffix products

  • No nested loops

Space Complexity:

  • O(1) - excluding output array

  • Only one extra variable (suffix)

  • Output array not counted as extra space

Optimizations:

  • No division operation used

  • Reuse output array for prefix products

  • Single variable for suffix products

  • No extra arrays needed

Why Solution Works

  1. Prefix-Suffix Combination:

    • Each position gets products from both sides

    • Left products stored in result array

    • Right products multiplied during second pass

    • Avoids division operation

  2. Space Optimization:

    • Reuses output array for intermediate results

    • Needs only one extra variable

    • Maintains O(1) extra space

    • Efficient memory usage

  3. Two-Pass Approach:

    • First pass builds left products

    • Second pass combines with right products

    • Each element gets complete product

    • Handles zeros naturally

When to Use

This approach is ideal when:

  1. Division operation is not allowed

  2. O(1) extra space required

  3. Need products of all elements except self

  4. Array elements can be positive/negative/zero

Common applications:

  • Array transformation problems

  • Product calculations without division

  • Space-constrained environments

  • Interview problems

Common Patterns & Applications

  1. Prefix-Suffix Pattern:

    • Build products from both directions

    • Combine intermediate results

    • Use output array for storage

    • O(1) extra space

  2. Two-Pass Array:

    • Forward pass for prefix

    • Backward pass for suffix

    • Combine results in-place

    • Space-efficient solution

  3. Array Manipulation:

    • In-place modifications

    • Running products

    • Direction-based processing

    • Space optimization

Interview Tips

  1. Initial Clarification:

    • Confirm if division is allowed

    • Ask about space constraints

    • Clarify handling of zeros

    • Discuss integer overflow

  2. Solution Walkthrough:

    • Start with brute force approach

    • Explain space optimization

    • Show how to avoid division

    • Demonstrate two-pass technique

  3. Code Implementation Strategy:

    • Initialize result array

    • Implement prefix products

    • Add suffix products

    • Handle edge cases

  4. Optimization Discussion:

    • Why division is problematic

    • How to save space

    • Handling large numbers

    • Performance considerations

  5. Common Pitfalls to Avoid:

    • Using division

    • Creating extra arrays

    • Missing edge cases

    • Integer overflow

  6. Follow-up Questions:

    • Q: "How to handle integer overflow?" A: Use long/big integers or modulo arithmetic

    • Q: "Can we optimize for arrays with zeros?" A: Count zeros and handle special cases

    • Q: "How to parallelize this solution?" A: Split array and combine partial products

    • Q: "What if array is very large?" A: Consider chunking and parallel processing

  7. Edge Cases to Test:

    • Array with zeros

    • Array with negative numbers

    • Array with ones

    • Minimum length array (2)

    • Maximum length array

  8. Code Quality Points:

    • Clear variable names

    • Efficient array initialization

    • Clean loop logic

    • Proper comments

  9. Alternative Approaches:

    • Using logarithms (not recommended)

    • Division-based (if allowed)

    • Recursive solution

    • Parallel processing

  10. Performance Analysis:

    • Best case: O(n)

    • Worst case: O(n)

    • Memory: O(1)

    • CPU cache friendly

Previous226. Invert Binary TreeNext242. Valid Anagram

Last updated 5 months ago

Was this helpful?

Leetcode:

link
result