Write an API that generates fancy sequences using the append
, addAll
, and mulall operations.
Implement the Fancy
class:
Fancy()
Initializes the object with an empty sequence.void append(val)
Appends an integer val to the end of the sequence.void addAll(inc)
Increments all existing values in the sequence by an integerinc
.void multAll(m)
Multiplies all existing values in the sequence by an integerm
.int getIndex(idx)
Gets the current value at the indexidx
(0-indexed) of the sequence modulo109 + 7
. If the index is greater or equal than the length of the sequence, return-1
.
Example:
Input
["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"]
[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]
Output
[null, null, null, null, null, 10, null, null, null, 26, 34, 20]
Explanation
Fancy fancy = new Fancy();
fancy.append(2); // fancy sequence: [2]
fancy.addAll(3); // fancy sequence: [2+3] -> [5]
fancy.append(7); // fancy sequence: [5, 7]
fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]
fancy.getIndex(0); // return 10
fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]
fancy.append(10); // fancy sequence: [13, 17, 10]
fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]
fancy.getIndex(0); // return 26
fancy.getIndex(1); // return 34
fancy.getIndex(2); // return 20
Approach:
C++
#include <bits/stdc++.h>using namespace std;int mod = 1000000007;unsigned long modPow(unsigned long x, int y){unsigned long tot = 1, p = x;for (; y; y >>= 1){if (y & 1)tot = (tot * p) % mod;p = (p * p) % mod;}return tot;}class Fancy{public:unsigned long seq[100001];unsigned int length = 0;unsigned long increment = 0;unsigned long mult = 1;Fancy(){}void append(int val){seq[length++] = (((mod + val - increment) % mod) *modPow(mult, mod - 2)) % mod;}void addAll(int inc){increment = (increment + inc % mod) % mod;}void multAll(int m){mult = (mult * m % mod) % mod;increment = (increment * m % mod) % mod;}int getIndex(int idx){if (idx >= length){return -1;}else{return ((seq[idx] * mult) % mod + increment) % mod;}}};int main(){Fancy fancy;fancy.append(2);fancy.addAll(3);fancy.append(7);fancy.multAll(2);cout << fancy.getIndex(0) << ", ";fancy.addAll(3);fancy.append(10);fancy.multAll(2);cout << fancy.getIndex(0) << ", ";cout << fancy.getIndex(1) << ", ";cout << fancy.getIndex(2);return 0;}
No comments:
Post a Comment