| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.ProductOfArrayExceptSelf; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ProductOfArrayExceptSelfPrefixSum : IProductOfArrayExceptSelf |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int[] ProductExceptSelf(int[] nums) |
| | 2 | 24 | | { |
| | 2 | 25 | | var n = nums.Length; |
| | | 26 | | |
| | 2 | 27 | | Span<int> prefix = stackalloc int[n + 1]; |
| | | 28 | | |
| | 2 | 29 | | prefix[0] = 1; |
| | | 30 | | |
| | 22 | 31 | | for (var i = 1; i <= n; i++) |
| | 9 | 32 | | { |
| | 9 | 33 | | prefix[i] = prefix[i - 1] * nums[i - 1]; |
| | 9 | 34 | | } |
| | | 35 | | |
| | 2 | 36 | | Span<int> suffix = stackalloc int[n + 1]; |
| | | 37 | | |
| | 2 | 38 | | suffix[n] = 1; |
| | | 39 | | |
| | 22 | 40 | | for (var i = n - 1; i >= 0; i--) |
| | 9 | 41 | | { |
| | 9 | 42 | | suffix[i] = suffix[i + 1] * nums[i]; |
| | 9 | 43 | | } |
| | | 44 | | |
| | 22 | 45 | | for (var i = 0; i < n; i++) |
| | 9 | 46 | | { |
| | 9 | 47 | | nums[i] = prefix[i] * suffix[i + 1]; |
| | 9 | 48 | | } |
| | | 49 | | |
| | 2 | 50 | | return nums; |
| | 2 | 51 | | } |
| | | 52 | | } |