Product of Array Except Self

Edit

Difficulty: MEDIUM

Categories: ๋ฐฐ์—ด/๋ฌธ์ž์—ด

Source: https://leetcode.com/problems/product-of-array-except-self/


Solutions

Add Solution
JAVA 2026-09-30 12:00 Edit
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];
        answer[0] = 1;
        for (int i = 1; i < n; i++) {
            answer[i] = answer[i - 1] * nums[i - 1];
        }
        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            answer[i] *= right;
            right *= nums[i];
        }
        return answer;
    }
}
Notes:

[์ž๋™ ํ’€์ด ยท gpt-4.1-mini] ๊ฐ ์ธ๋ฑ์Šค์—์„œ ์™ผ์ชฝ์— ์žˆ๋Š” ๋ชจ๋“  ์ˆ˜์˜ ๊ณฑ๊ณผ ์˜ค๋ฅธ์ชฝ์— ์žˆ๋Š” ๋ชจ๋“  ์ˆ˜์˜ ๊ณฑ์„ ๊ณฑํ•˜๋ฉด ํ•ด๋‹น ์ธ๋ฑ์Šค๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  ์ˆ˜์˜ ๊ณฑ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์™ผ์ชฝ ๊ณฑ ๋ฐฐ์—ด๊ณผ ์˜ค๋ฅธ์ชฝ ๊ณฑ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด ํ•œ ๋ฒˆ์— ๊ณ„์‚ฐํ•˜๊ฑฐ๋‚˜, ๊ฒฐ๊ณผ ๋ฐฐ์—ด์„ ์ด์šฉํ•ด ๊ณต๊ฐ„์„ ์ ˆ์•ฝํ•˜๋ฉฐ ๋‘ ๋ฒˆ ์ˆœํšŒํ•œ๋‹ค. ์‹œ๊ฐ„ O(n) ยท ๊ณต๊ฐ„ O(1) (์ถœ๋ ฅ ๋ฐฐ์—ด ์ œ์™ธ) ์ฃผ์˜: 0์ด ์—ฌ๋Ÿฌ ๊ฐœ์ผ ๋•Œ ๊ฒฐ๊ณผ๊ฐ€ ๋ชจ๋‘ 0์ด ๋˜๋Š” ์ ๊ณผ, ๋‚˜๋ˆ„๊ธฐ ์—ฐ์‚ฐ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค๋Š” ์ ์„ ์ฃผ์˜ํ•ด์•ผ ํ•œ๋‹ค.