Tuesday 5 March 2024

Problem statement: https://leetcode.com/problems/product-of-array-except-self/description/

Solution:

in O(1) space , if ans array is not considered as extra space


class Solution {

    public int[] productExceptSelf(int[] nums) {

        int n = nums.length;

        int[] ans = new int[n];

        

        ans[0] = 1;

        for (int i = 1; i < n; i++) {

            ans[i] = ans[i - 1] * nums[i - 1];

        }

        

        int right = 1; 

        for (int i = n - 1; i >= 0; i--) {

            ans[i] *= right;

            right *= nums[i];

        }

        

        return ans;

    }

}


No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...