Saturday, May 7, 2022

LeetCode Medium: Product of Array Except Self

 Problem Name: Product of Array Except Self

Problem Descriptionhttps://leetcode.com/problems/product-of-array-except-self/

Problem Approach used: It's an easy problem to solve, just keep in mind your Indeterminate Numbers lesson of High School to solve it.

Time Complexity:  O(n) worst-case time complexity and O(1) auxiliary space complexity.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
    public int[] productExceptSelf(int[] nums) {
        long prodArr = 1;
        long non0ProdArr = 1;
        int countZeroes = 0;
        for (int i=0; i<nums.length; i++) {
            if (nums[i] == 0)
                countZeroes++;
            if (nums[i] != 0)
                non0ProdArr *= nums[i];
            prodArr *= nums[i];
        }
        int[] answer = new int[nums.length];
        if (countZeroes > 1) {
            Arrays.fill(answer, 0);
            return answer;
        }
        
        for (int i=0; i<nums.length; i++) {
            if (nums[i] == 0 && countZeroes == 1) {
                    countZeroes--;
                    answer[i] = (int)non0ProdArr;
            } else {
                answer[i] = (int)(prodArr / (long)nums[i]);
            }
        }
        
        return answer;
    }
}


Until Next time, Keep coding and have fun!


Love! ❤️ 
#Lets #Code

Follow us on :

https://twitter.com/ThinkAlgorithms


No comments:

Post a Comment

Featured Post

interviewBit Medium: Palindrome Partitioning II

Problem Name:  Palindrome Partitioning II Problem Description : https://www.interviewbit.com/problems/palindrome-partitioning-ii/ Problem Ap...