-
Notifications
You must be signed in to change notification settings - Fork 0
/
product_of_array_except_self.rs
50 lines (40 loc) · 1.29 KB
/
product_of_array_except_self.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#![allow(dead_code)]
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
let mut output = vec![1; nums.len()];
let mut left = 1;
let mut right = 1;
for i in 0..nums.len() {
output[i] *= left;
left *= nums[i];
output[nums.len() - 1 - i] *= right;
right *= nums[nums.len() - 1 - i];
}
output
}
/*
Algorithm - Two Pass
- Create an output array of the same size as the input array
- Iterate through the input array from left to right
- At each index, multiply the current element with the previous element
- Store the result in the output array
- Iterate through the input array from right to left
- At each index, multiply the current element with the previous element
- Store the result in the output array
- Return the output array
Time: O(n)
Space: O(1), excluding the output array
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_product_except_self() {
assert_eq!(product_except_self(vec![1, 2, 3, 4]), vec![24, 12, 8, 6]);
assert_eq!(
product_except_self(vec![-1, 1, 0, -3, 3]),
vec![0, 0, 9, 0, 0]
);
assert_eq!(product_except_self(vec![1, 2]), vec![2, 1]);
assert_eq!(product_except_self(vec![1]), vec![1]);
}
}