Start learning free

LESSON 240 OF 442 · PARTIAL SUMS #1

Product of Array Except Self in Scala

Practice O(n)

Given an array of integers nums, return an array answer of the same length such that answer[i] is the product of all the elements of nums except nums[i].

Solve it without using division.

 

Example 1:

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

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Explanation: Every product that includes the 0 is 0. Only answer[2] leaves the 0 out: (-1) * 1 * (-3) * 3 = 9.

Example 3:

Input: nums = [2,3]
Output: [3,2]
Explanation: With two elements, each answer is the other element.

 

Constraints:

  • 2 <= nums.length <= 105
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums, and every answer[i], fits in a 32-bit integer.

Note:

Your algorithm should run in O(n) time and use O(1) extra space: the returned array doesn't count.

STEP 1 OF 9
    Ctrl + Enter to check

    Product Of Array Except Self in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free