Real O(1) space, O(n) time solution


  • -1
    S

    Simply for the product of all (except for zero) and divide each element.

    public class Solution {
        public int[] ProductExceptSelf(int[] nums) {
            long p = 1;
            int z = 0;
            foreach(int n in nums) {
                if (n == 0) {
                    if (++z > 1) {p = 0; break;}
                }
                else p *= n;
            }
            var ans = new int[nums.Length];
            for(int i = 0; i < nums.Length; i++) {
                ans[i] = nums[i] == 0 ? (int)p : (z == 1 ? 0 : (int)(p / nums[i]));
            }
    
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.