238. Product of Array Except Self

Contents

238. Product of Array Except Self#

#Medium #Array #Prefix Sum

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]

Think#

๋‚˜๋ˆ—์…ˆ์ด ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์ง€๋งŒ, ๋‚˜๋ˆ—์…ˆ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ?

์™ผ์ชฝ ๊ณฑ์…ˆ๊ณผ ์˜ค๋ฅธ์ชฝ ๊ณฑ์…ˆ์„ ๋”ฐ๋กœ ๊ณ„์‚ฐํ•˜์—ฌ ๋‘ ๊ฐ’์„ ๊ณฑํ•˜๋ฉด ๋œ๋‹ค. ๋ˆ„์ ๊ณฑ(prefix product)๊ณผ ๋ˆ„์ ๊ณฑ(suffix product)๋ฅผ ๋”ฐ๋กœ ๊ณ„์‚ฐํ•˜์—ฌ ๋‘ ๊ฐ’์„ ๊ณฑํ•˜๋ฉด ๋œ๋‹ค. ํŠนํžˆ O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์š”๊ตฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— for๋ฌธ์„ ๋‘ ๋ฒˆ ๋Œ๋ฆด ๊ฒฝ์šฐ์—๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐ˜๋“œ์‹œ ๋‚˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๊ทธ๋ ‡๊ธฐ์— ํ•œ ๋ฒˆ์ด ๋„˜์–ด๊ฐ€๋Š” ๊ฒน์น˜๋Š” ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋œ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ์ €์žฅ์˜ ๊ฐœ๋…์„ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค. p

from utils import *

def process_line(line, line_count, func):
    import traceback
    try:
        inp, oup = line.strip().split()
        inp = list(map(int, inp.split(",")))
        oup = list(map(int, oup.split(",")))

        result = func(inp)
        if result != oup:
            raise ValueError(f"WRONG : {line}")
        logger.info(f"{line_count} : {inp} --- {oup} {oup == result}")
        return line_count + 1

    except Exception:
        logger.error(traceback.format_exc())
        logger.info(f"FINISHED WITH ERROR IN {line_count}")
        return line_count


class Solution:
    from typing import List
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        answer = [1] * n
        
        for i in range(1, n):
            answer[i] = answer[i - 1] * nums[i - 1]
        
        right = 1
        for i in range(n - 1, -1, -1):
            answer[i] *= right
            right *= nums[i]
        
        return answer
problem_num = 238
logger = get_logger("DEBUG")
solution_instance = Solution()
sol(problem_num, solution_instance.productExceptSelf, logger, process_line)
[2024/12/24 11:39:35 INFO] 1 : [1, 2, 3, 4] --- [24, 12, 8, 6] True
[2024/12/24 11:39:35 INFO] 2 : [-1, 1, 0, -3, 3] --- [0, 0, 9, 0, 0] True
[2024/12/24 11:39:35 INFO] EOF