Fancy Sequence - Problem

Design and implement a Fancy class that supports dynamic sequence operations:

  • Fancy() - Initializes the object with an empty sequence
  • append(val) - Appends an integer val to the end of the sequence
  • addAll(inc) - Increments all existing values in the sequence by integer inc
  • multAll(m) - Multiplies all existing values in the sequence by integer m
  • getIndex(idx) - Gets the current value at index idx (0-indexed) modulo 109 + 7. Returns -1 if the index is greater than or equal to the sequence length

All operations must handle large numbers and return results modulo 109 + 7.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["Fancy", "append", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"], values = [null, 2, 3, 7, 2, 0, 1, 2]
Output: [10, 14, -1]
💡 Note: append(2): [2], addAll(3): [5], append(7): [5,7], multAll(2): [10,14]. getIndex(0)=10, getIndex(1)=14, getIndex(2)=-1 (out of bounds)
Example 2 — Multiple Multiplications
$ Input: operations = ["Fancy", "append", "multAll", "getIndex", "multAll", "getIndex"], values = [null, 5, 2, 0, 3, 0]
Output: [10, 30]
💡 Note: append(5): [5], multAll(2): [10], getIndex(0)=10, multAll(3): [30], getIndex(0)=30
Example 3 — Empty Sequence
$ Input: operations = ["Fancy", "getIndex"], values = [null, 0]
Output: [-1]
💡 Note: getIndex(0) on empty sequence returns -1

Constraints

  • 1 ≤ val, inc, m ≤ 100
  • 0 ≤ idx ≤ 100
  • At most 105 calls total to append, addAll, multAll, and getIndex
  • All values modulo 109 + 7

Visualization

Tap to expand
Fancy Sequence: Dynamic OperationsOperations:append(2)addAll(3)append(7)multAll(2)Sequence State:1014Transformation:(2+3)×2 = 107×2 = 14Result: getIndex(0)=10, getIndex(1)=14
Understanding the Visualization
1
Input
Operations: append(2), addAll(3), append(7), multAll(2)
2
Process
Track transformations lazily without updating elements
3
Output
getIndex returns transformed values: [10, 14]
Key Takeaway
🎯 Key Insight: Instead of updating all elements individually, track cumulative transformations and apply them lazily during retrieval
Asked in
Google 15 Facebook 12 Amazon 8
15.4K Views
Medium Frequency
~35 min Avg. Time
278 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen