diff --git a/cs/product-of-array-except-self.cs b/cs/product-of-array-except-self.cs new file mode 100644 index 0000000..39fe6cc --- /dev/null +++ b/cs/product-of-array-except-self.cs @@ -0,0 +1,28 @@ +public class Solution { + private int Get(int[] products, int idx) { + if (idx < 0 || idx >= products.Length) { + return 1; + } + return products[idx]; + } + + public int[] ProductExceptSelf(int[] nums) { + var left = new int[nums.Length]; + var right = new int[nums.Length]; + + for (var i = 0; i < nums.Length; ++i) { + left[i] = nums[i] * Get(left, i - 1); + + int j = nums.Length - i - 1; + right[j] = nums[j] * Get(right, j + 1); + } + + var result = new int[nums.Length]; + + for (var i = 0; i < nums.Length; ++i) { + result[i] = Get(left, i - 1) * Get(right, i + 1); + } + + return result; + } +}