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