Skip to content

Commit 57efc15

Browse files
committed
Problem 165: Product except self
1 parent d917d34 commit 57efc15

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,5 +234,6 @@ Include contains single header implementation of data structures and some algori
234234
| Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.| [merge_trees.cpp](leet_code_problems/merge_trees.cpp)|
235235
| Write a function that takes a string as input and reverse only the vowels of a string.|[reverse_vowels.cpp](leet_code_problems/reverse_vowels.cpp)|
236236
| Given a string, sort it in decreasing order based on the frequency of characters.For example: <ul><li>Input: cccbbbbaa Output: bbbcccaa</li></ul>| [sortCharByFrequency.cpp](leet_code_problems/sortCharByFrequency.cpp)|
237+
|Product of Array Except Self. Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].| [product_except_self.cpp](leet_code_problems/product_except_self.cpp)|
237238

238239

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* Given an array of n integers where n > 1, nums, return an array output
3+
* such that output[i] is equal to the product of all the elements of nums except nums[i].
4+
* Example: [1, 2, 3, 4] ==> [24, 12, 8, 6]
5+
*
6+
* Try to use constant space. (excluding result array)
7+
*/
8+
9+
#include <iostream>
10+
#include <vector>
11+
12+
std::vector<int> product_except_self(const std::vector<int>& nums)
13+
{
14+
int product_from_beginning = 1;
15+
int product_from_end = 1;
16+
unsigned int n = nums.size();
17+
std::vector<int> result(n, 1);
18+
for (unsigned int i = 0; i < n; ++i) {
19+
result[i] *= product_from_beginning;
20+
product_from_beginning *= nums[i];
21+
result[n-1-i] *= product_from_end;
22+
product_from_end *= nums[n-1-i];
23+
}
24+
return result;
25+
}
26+
void print_vector(const std::vector<int>& vec)
27+
{
28+
for (auto n : vec) {
29+
std::cout << n << " ";
30+
}
31+
std::cout << std::endl;
32+
}
33+
34+
int main()
35+
{
36+
std::vector<int> vec{1, 2, 3, 4};
37+
std::cout << "Input Vector: ";
38+
print_vector(vec);
39+
std::vector<int> result = product_except_self(vec);
40+
std::cout << "Output Vector: ";
41+
print_vector(result);
42+
}
43+

0 commit comments

Comments
 (0)