codekofi
← All problems

Problem 10

Medium

1 · Worked examples

0 / 4

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 4 outputs correctly.

The accepted solution

1vector<int> solution(const vector<int>& nums) {
2
3 int n = nums.size();
4 vector<int> ans(n, 1);
5
6 int running = 1;
7
8 for (int i = 0; i < n; i++) {
9 ans[i] = running;
10 running = running * nums[i];
11 }
12
13 running = 1;
14
15 for (int i = n - 1; i >= 0; i--) {
16 ans[i] = ans[i] * running;
17 running = running * nums[i];
18 }
19
20 return ans;
21}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.