[LeetCode] Fancy Sequence

1622. Fancy Sequence

Write an API that generates fancy sequences using the append, addAll, and multAll 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 integer inc.
  • void multAll(m) Multiplies all existing values in the sequence by an integer m.
  • int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.
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
class Fancy {
long m = 1, p = 0, mod = 1e9 + 7;
vector<array<long,3>> A;

long modPow(long n, long x) {
if(x == 1) return n;
long res = modPow(n, x>>1);
res = (res * res) % mod;
if(x & 1) res = (res * n) % mod;
return res;
}
public:
Fancy() {

}

void append(int val) {
A.push_back({val, m, p});
}

void addAll(int inc) {
p = (p + inc) % mod;
}

void multAll(int mul) {
m = (m * mul) % mod;
p = (p * mul) % mod;
}

int getIndex(int idx) {
if(A.size() <= idx) return -1;
auto [n, multi, plus] = A[idx];
auto eval = m * modPow(multi, mod - 2) % mod;
return (eval * (mod + n - plus) % mod + p) % mod;
}
};

/**
* Your Fancy object will be instantiated and called as such:
* Fancy* obj = new Fancy();
* obj->append(val);
* obj->addAll(inc);
* obj->multAll(m);
* int param_4 = obj->getIndex(idx);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/30/PS/LeetCode/fancy-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.