Prepin
Log in

Change each element of the array to the product of all the other elements, without utilizing the division operator.

Approach / Explanation

This question presents you with an array of numbers, and your objective is to substitute each element with the product of all other elements in the array, without utilizing the division ( / ) operator. The array may include positive, negative, or zero values. You must perform this task in-place, meaning you should alter the original array rather than generating a new one. To tackle this issue, think about the cumulative product of all elements that precede and follow the current element in the array. You can create two separate arrays or lists to hold these products. After that, compute the product of the respective elements in the two lists, which will yield the product of all elements except the one currently being considered.

Suggested Answer

Consider an array [1,2,3,4]. We will start by creating two new lists/arrays, referred to as prefix_product and suffix_product, both initialized to 1. The length of prefix_product and suffix_product will be equal to the length of the input_array. To fill the prefix_product, traverse the input_array from left to right (i.e., from index 0 to n-1), where each element in prefix_product represents the product of all preceding elements in the input_array. For example, the prefix_product will be [1, 1, 2, 6]. To fill the suffix_product, traverse the input_array from right to left (i.e., from index n-1 to 0), where each element in suffix_product represents the product of all elements that follow the current element in the input_array. For instance, the suffix_product will be [24, 12, 4, 1]. Finally, to obtain the output, for each index in the input_array, multiply the corresponding elements from prefix_product and suffix_product. The resulting array will be [24, 12, 8, 6].

Alternative Answer

Let's examine another example. Given the input [-1, 1, -2, 2]. Following the previously outlined steps, we first generate the prefix_product as [1, -1, -1, 2] and the suffix_product as [-4, 4, -2, 1]. Next, we multiply the corresponding elements of prefix_product and suffix_product to obtain our final result of [-4, 4, -2, 2]. It’s important to note that this solution remains valid even when the array includes zeros. If there is a single zero, all other elements will turn into 0 after the operation, except for the zero itself, which will represent the product of all other numbers except it. If there are multiple zeros, all elements will result in zero following the operation.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.