Fancy Sequence - Problem
Design and implement a Fancy Sequence data structure that supports dynamic operations on a sequence of integers. This sequence allows you to efficiently append new values, apply bulk transformations (add or multiply all elements), and query values at specific indices.
The challenge is to handle potentially millions of operations efficiently while maintaining the correct sequence state. All values should be returned modulo 109 + 7 to prevent integer overflow.
Operations to implement:
append(val)- Add integervalto the end of the sequenceaddAll(inc)- Addincto every existing element in the sequencemultAll(m)- Multiply every existing element in the sequence bymgetIndex(idx)- Return the current value at indexidx(0-indexed), or -1 if index is out of bounds
Key insight: Naive approaches will time out on large inputs due to the bulk operations affecting all elements.
Input & Output
example_1.py โ Basic Operations
$
Input:
fancy = Fancy()
fancy.append(2)
fancy.addAll(3)
fancy.append(7)
fancy.multAll(2)
print(fancy.getIndex(0))
print(fancy.getIndex(1))
โบ
Output:
10
14
๐ก Note:
First append 2, then add 3 to all (making it 5), append 7, then multiply all by 2. Index 0: (2+3)*2 = 10, Index 1: 7*2 = 14
example_2.py โ Out of bounds
$
Input:
fancy = Fancy()
fancy.append(2)
print(fancy.getIndex(0))
print(fancy.getIndex(1))
โบ
Output:
2
-1
๐ก Note:
Index 1 is out of bounds since we only have one element, so return -1
example_3.py โ Multiple transformations
$
Input:
fancy = Fancy()
fancy.append(0)
fancy.addAll(5)
fancy.multAll(3)
fancy.append(10)
fancy.multAll(2)
print(fancy.getIndex(0))
print(fancy.getIndex(1))
โบ
Output:
30
20
๐ก Note:
Index 0: ((0+5)*3)*2 = 30. Index 1: 10*2 = 20 (only affected by final multAll)
Constraints
- 1 โค val, inc, m โค 100
- 0 โค idx โค 105
-
At most 105 calls will be made to
append,addAll,multAll, andgetIndex - All values must be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Record Original Values
Store each number with a timestamp of when it joined the sequence
2
Track Global Transformations
Instead of applying operations immediately, record them as global transformation factors
3
Apply on Demand
When getIndex is called, calculate the final value by applying all transformations that occurred after the element was added
4
Use Modular Arithmetic
Handle large numbers and division using modular inverse to ensure correctness
Key Takeaway
๐ฏ Key Insight: By deferring the application of transformations until they're actually needed, we convert expensive O(n) bulk operations into O(1) bookkeeping, making the data structure highly efficient for large sequences with frequent transformations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code