DEV Community

Bernice Waweru
Bernice Waweru

Posted on

1

Product of Array Except Self

Instructions

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].

Attempt here

Example

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

Approach

The first idea you are likely to come up with is to find the product of all the elements in the array and divide the product by nums[i] to get the product at a given i.
However, the questions requires that we do not use the division operator.

Another approach would be to maintain a prefix that stores the product of elements before array[i] and a postfix that stores the product of elements occuring after array[i].

Implementation

def productExceptSelf(self, nums: List[int]) -> List[int]:

        result = [1] * (len(nums))
        prefix = 1
        postfix = 1

        for i in range(len(nums)):
            result[i] = prefix
            prefix *= nums[i]        
        for i in range(len(nums) - 1, -1, -1):
            result[i] *= postfix
            postfix *= nums[i]
        return result
Enter fullscreen mode Exit fullscreen mode

When calculating the postfix we iterate through the array with -1 step. A negative step value in a range() function generates the sequence of numbers in reverse order.

This solution uses O(1) space complexity and O(n) time complexity.

Video Solution
Happy learning !!!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay