Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

238. Product of Array Except Self #3

Merged
merged 1 commit into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/solutions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod s_198_house_robbers;
mod s_19_remove_nth_node_from_end_of_list;
mod s_206_reverse_linked_list;
mod s_22_generate_parentheses;
mod s_238_product_of_array_except_self;
mod s_3_longest_substring_without_repeating_characters;
mod s_417_pacific_atlantic_water_flow;
mod s_424_longest_repeating_character_replacement;
Expand Down
40 changes: 40 additions & 0 deletions src/solutions/s_238_product_of_array_except_self.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
struct Solution {}

impl Solution {
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
let mut forward_products = vec![1; nums.len()];
let mut backward_products = vec![1; nums.len()];
for i in 1..nums.len() {
forward_products[i] = forward_products[i - 1] * nums[i - 1];
let offset = nums.len() - 1 - i;
backward_products[offset] = backward_products[offset + 1] * nums[offset + 1];
}

let mut res = vec![];
for i in 0..forward_products.len() {
res.push(forward_products[i] * backward_products[i])
}
return res;
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_only_positive_integer() {
let input = vec![1, 2, 3, 4];
let expected = vec![24, 12, 8, 6];
let res = Solution::product_except_self(input);
assert_eq!(res, expected);
}

#[test]
fn test_zero_and_negative() {
let input = vec![-1, 1, 0, -3, 3];
let expected = vec![0, 0, 9, 0, 0];
let res = Solution::product_except_self(input);
assert_eq!(res, expected);
}
}