Problem
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 integervalto 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 indexidx(0-indexed) of the sequence modulo109 + 7. If the index is greater or equal than the length of the sequence, return-1.
Examples
Example 1:
| |
Solution
Method 1 - Using List
The problem involves creating and maintaining a sequence with operations (append, addAll, and multAll) that modify the entire sequence efficiently. Directly applying the operations on all elements every time would result in a poor time complexity when the sequence becomes large. To optimise this process:
Key Observations
- Tracking Operations:
- Instead of modifying every element for each operation, maintain values
addandmultthat track the cumulative additions and multiplications applied to all elements.
- Instead of modifying every element for each operation, maintain values
- Delayed Evaluation:
- When
getIndex(idx)is called, compute the value at the specific index lazily by applying the stored operations.
- When
- Modulo (
10^9 + 7):- Since operations may result in large numbers, ensure all calculations are done modulo
10^9 + 7.
- Since operations may result in large numbers, ensure all calculations are done modulo
Approach
- Use a list
seqto store the appended values. - Maintain two variables:
addfor cumulative addition.multfor cumulative multiplication (starting with 1).
- Implement the methods as follows:
append(val): Append thevaladjusted for the currentmultandadd.addAll(inc): Increment theaddvariable.multAll(m): Updatemult, and adjust theaddbased on the multiplication.getIndex(idx): Retrieve the value atidxusing the stored operations, modulo10^9 + 7.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(1)for each operation - 🧺 Space complexity:
O(n)wherenis the number of appended elements in the sequence.