From b634dfae36d0ad05e7190ff63c4e4227928887f6 Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Sun, 15 Oct 2023 09:49:43 -0700 Subject: [PATCH] day 16: 238-product-of-array-except-self --- 238-product-of-array-except-self/driver.cpp | 10 ++++++ 238-product-of-array-except-self/soln.cpp | 35 +++++++++++++++++++++ 238-product-of-array-except-self/soln.hpp | 7 +++++ 3 files changed, 52 insertions(+) create mode 100644 238-product-of-array-except-self/driver.cpp create mode 100644 238-product-of-array-except-self/soln.cpp create mode 100644 238-product-of-array-except-self/soln.hpp diff --git a/238-product-of-array-except-self/driver.cpp b/238-product-of-array-except-self/driver.cpp new file mode 100644 index 0000000..7fce4c1 --- /dev/null +++ b/238-product-of-array-except-self/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + vector nums{1, 2, 3, 4}; + vector answer{24, 12, 8, 6}; + Solution soln; + cout << "Found products correctly? " << soln.test(nums, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/238-product-of-array-except-self/soln.cpp b/238-product-of-array-except-self/soln.cpp new file mode 100644 index 0000000..27610be --- /dev/null +++ b/238-product-of-array-except-self/soln.cpp @@ -0,0 +1,35 @@ +#include "soln.hpp" + +vector Solution::productExceptSelf(vector &nums) +{ + int n = nums.size(); + vector pres(n); + vector sufs(n); + vector result(n); + // calculate prefixes starting from second + int cur = 1; + for (int i = 1; i < n; i++) + { + pres[i] = cur * nums[i - 1]; + cur = pres[i]; + } + // calculate suffixes starting from second last + cur = 1; + for (int j = n - 2; j >= 0; j--) + { + sufs[j] = cur * nums[j + 1]; + cur = sufs[j]; + } + + result[0] = sufs[0]; + result[n - 1] = pres[n - 1]; + for (int i = 1; i < n - 1; i++) + { + result[i] = pres[i] * sufs[i]; + } + return result; +} + +bool Solution::test(vector& nums, vector& answer) { + return productExceptSelf(nums) == answer; +} \ No newline at end of file diff --git a/238-product-of-array-except-self/soln.hpp b/238-product-of-array-except-self/soln.hpp new file mode 100644 index 0000000..5ac33cc --- /dev/null +++ b/238-product-of-array-except-self/soln.hpp @@ -0,0 +1,7 @@ +#include +using namespace std; +class Solution { +public: + vector productExceptSelf(vector& nums); + bool test(vector& nums, vector& answer); +}; \ No newline at end of file