diff --git a/product-of-array-except-self/.gitignore b/product-of-array-except-self/.gitignore new file mode 100644 index 0000000..389159a --- /dev/null +++ b/product-of-array-except-self/.gitignore @@ -0,0 +1,20 @@ +# Created by https://www.toptal.com/developers/gitignore/api/rust +# Edit at https://www.toptal.com/developers/gitignore?templates=rust + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +# End of https://www.toptal.com/developers/gitignore/api/rust diff --git a/product-of-array-except-self/Cargo.toml b/product-of-array-except-self/Cargo.toml new file mode 100644 index 0000000..d482d53 --- /dev/null +++ b/product-of-array-except-self/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "product-of-array-except-self" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/product-of-array-except-self/src/main.rs b/product-of-array-except-self/src/main.rs new file mode 100644 index 0000000..c3db099 --- /dev/null +++ b/product-of-array-except-self/src/main.rs @@ -0,0 +1,34 @@ +struct Solution {} + +impl Solution { + pub fn product_except_self(nums: Vec) -> Vec { + let mut result = vec![1; nums.len()]; + let mut left = 1; + let mut right = 1; + + println!("{:?}", result); + for i in 0..nums.len() { + // Moving left to right: multiple each number by the preceding number + result[i] *= left; + left *= nums[i]; + + // Moving right to left, multiple each number by the following number + result[nums.len() - 1 - i] *= right; + right *= nums[nums.len() - 1 - i]; + } + + result + } +} + +fn main() { + assert_eq!( + Solution::product_except_self(vec![1, 2, 3, 4]), + vec![24, 12, 8, 6] + ); + + assert_eq!( + Solution::product_except_self(vec![-1, 1, 0, -3, 3]), + vec![0, 0, 9, 0, 0] + ) +}