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 integerval
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 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
add
andmult
that 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
seq
to store the appended values. - Maintain two variables:
add
for cumulative addition.mult
for cumulative multiplication (starting with 1).
- Implement the methods as follows:
append(val)
: Append theval
adjusted for the currentmult
andadd
.addAll(inc)
: Increment theadd
variable.multAll(m)
: Updatemult
, and adjust theadd
based on the multiplication.getIndex(idx)
: Retrieve the value atidx
using the stored operations, modulo10^9 + 7
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
for each operation - 🧺 Space complexity:
O(n)
wheren
is the number of appended elements in the sequence.