|
| 1 | +/** |
| 2 | + * 1622. Fancy Sequence |
| 3 | + * https://leetcode.com/problems/fancy-sequence/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Write an API that generates fancy sequences using the append, addAll, and multAll operations. |
| 7 | + * |
| 8 | + * Implement the Fancy class: |
| 9 | + * - Fancy() Initializes the object with an empty sequence. |
| 10 | + * - void append(val) Appends an integer val to the end of the sequence. |
| 11 | + * - void addAll(inc) Increments all existing values in the sequence by an integer inc. |
| 12 | + * - void multAll(m) Multiplies all existing values in the sequence by an integer m. |
| 13 | + * - int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo |
| 14 | + * 109 + 7. If the index is greater or equal than the length of the sequence, return -1. |
| 15 | + */ |
| 16 | + |
| 17 | +var Fancy = function() { |
| 18 | + this.sequence = []; |
| 19 | + this.additive = 0n; |
| 20 | + this.multiplicative = 1n; |
| 21 | + this.MOD = 1000000007n; |
| 22 | +}; |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number} val |
| 26 | + * @return {void} |
| 27 | + */ |
| 28 | +Fancy.prototype.append = function(val) { |
| 29 | + const valBig = BigInt(val); |
| 30 | + const inverse = this.modInverse(this.multiplicative); |
| 31 | + const adjustedVal = ((valBig - this.additive + this.MOD) * inverse) % this.MOD; |
| 32 | + this.sequence.push(adjustedVal); |
| 33 | +}; |
| 34 | + |
| 35 | +/** |
| 36 | + * @param {number} inc |
| 37 | + * @return {void} |
| 38 | + */ |
| 39 | +Fancy.prototype.addAll = function(inc) { |
| 40 | + this.additive = (this.additive + BigInt(inc)) % this.MOD; |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * @param {number} m |
| 45 | + * @return {void} |
| 46 | + */ |
| 47 | +Fancy.prototype.multAll = function(m) { |
| 48 | + const mBig = BigInt(m); |
| 49 | + this.additive = (this.additive * mBig) % this.MOD; |
| 50 | + this.multiplicative = (this.multiplicative * mBig) % this.MOD; |
| 51 | +}; |
| 52 | + |
| 53 | +/** |
| 54 | + * @param {number} idx |
| 55 | + * @return {number} |
| 56 | + */ |
| 57 | +Fancy.prototype.getIndex = function(idx) { |
| 58 | + if (idx >= this.sequence.length) return -1; |
| 59 | + return Number((this.sequence[idx] * this.multiplicative + this.additive) % this.MOD); |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * @param {number} a |
| 64 | + * @return {number} |
| 65 | + */ |
| 66 | +Fancy.prototype.modInverse = function(a) { |
| 67 | + let m = this.MOD; |
| 68 | + const m0 = m; |
| 69 | + let x = 1n; |
| 70 | + let y = 0n; |
| 71 | + |
| 72 | + a = a % m; |
| 73 | + while (a > 1n) { |
| 74 | + const q = a / m; |
| 75 | + [a, m] = [m, a % m]; |
| 76 | + [x, y] = [y, x - q * y]; |
| 77 | + } |
| 78 | + |
| 79 | + return x < 0n ? x + m0 : x; |
| 80 | +}; |
0 commit comments