Fancy Sequence solution and explanation
9 more videos on this problem
Fancy Sequence | Made Super Simple | Intuitive | Detailed | Leetcode 1622 | codestorywithMIKcodestorywithMIK · 42:57 · 9K views
LeetCode 1622. Fancy SequenceHappy Coding · 30:19 · 1K views
1622. Fancy Sequence | Leetcode Daily - PythonLeetcode Daily · 8:21 · 713 views
1622. Fancy Sequence (Leetcode Hard)Programming Live with Larry · 1:16:30 · 484 views
Daily Leetcode #2175: Mar 15, 2026 - 1622. Fancy SequenceProgramming Live with Larry · 27:54 · 434 views
Fancy Sequence | LeetCode 1622 - Pythonimpoldev · 12:56 · 399 views
leetcode 1622 | Fancy Sequence | Affine Transformation | Leetcode POTD | DSA | HardCode With Vick · 26:00 · 313 views
LeetCode 1622 | Fancy Sequence | Why Google Asks This! | LeetCode POTD 1415Shubham Bansal · 33:22 · 289 views
LeetCode 1622 Fancy Sequence | Hard DSA Problem Explained | Data Structure DesignAlgoDiary · 23:09 · 199 views
The Affine Transformation Pattern | LeetCode 1622 Visual ExplanationCode Crusaders · 6:31 · 194 views
The 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.
Example 1:
Input ["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"] [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]] Output [null, null, null, null, null, 10, null, null, null, 26, 34, 20] Explanation Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: [2] fancy.addAll(3); // fancy sequence: [2+3] -> [5] fancy.append(7); // fancy sequence: [5, 7] fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17] fancy.append(10); // fancy sequence: [13, 17, 10] fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20
Constraints:
1 <= val, inc, m <= 1000 <= idx <= 105- At most
105calls total will be made toappend,addAll,multAll, andgetIndex.
Approach overview
Problem Overview: You design a sequence that supports four operations: append(val), addAll(inc), multAll(m), and getIndex(i). Each modification affects every element already in the sequence. The challenge is handling up to 10^5 operations efficiently while applying additions and multiplications under modulo 1e9+7.
Approach 1: Direct Simulation (O(n) per update, O(1) query)
The simplest idea stores the sequence in an array and directly applies addAll or multAll by iterating through every element. Each operation modifies the entire list using a loop. While getIndex becomes a constant-time lookup, update operations cost O(n) time. With up to 10^5 operations, this approach quickly becomes too slow and exceeds time limits. Space complexity is O(n) for storing the sequence.
Approach 2: Lazy Global Transformation (Affine Function) (O(1) per operation)
Every operation applied to the sequence can be modeled as an affine transformation: x → a * x + b. Instead of updating each element, maintain global multipliers a and b. When you append a value, store it in a normalized form that cancels the current transformation using modular inverse. Later, when retrieving with getIndex, reconstruct the real value by applying the current transformation. All operations run in O(1) time with O(n) space. This technique relies on modular arithmetic and inverse computation, a common trick in math-heavy design problems.
Approach 3: Operations Tracking with Differential Storage (O(1) amortized)
Another design tracks the sequence values along with cumulative operations applied after insertion. Instead of modifying stored elements, maintain operation history such as total multipliers and additions. Each element remembers the operation state at the time it was appended. When retrieving an index, compute the difference between the stored state and the current state to derive the final value. This avoids repeated updates and keeps operations constant time. The technique works well for problems involving chained transformations and falls under advanced design patterns.
Approach 4: Segment Tree with Lazy Propagation (O(log n))
A more general solution uses a segment tree with lazy propagation. Each node stores values for a range and defers updates using lazy tags representing multiplication and addition. When addAll or multAll is called, the update propagates lazily across the tree. Queries push pending updates down the path before reading the value. Time complexity becomes O(log n) per operation with O(n) space. This approach is more flexible but heavier than the affine transformation trick.
Recommended for interviews: The affine transformation approach with lazy global parameters is the expected optimal solution. It achieves O(1) operations while handling both multiplication and addition efficiently. Discussing the brute-force simulation first shows understanding of the problem constraints, while the optimized math-based design demonstrates strong algorithmic thinking.
Approach 1: Lazy Propagation Using Differential Storage
Overview: The main idea is to avoid updating every element directly for each operation. Instead, maintain a cumulative add and mult factor that gets applied on retrieval.
Explanation: By maintaining separate variables for the total add and mult operations performed on the sequence, we can apply them whenever a specific index is requested, rather than updating every element in the sequence each time an operation is made.
class Fancy:
MOD = 10**9 + 7
def __init__(self):
self.seq = []
self.add = 0
self.mult = 1
def append(self, val: int) -> None:
# Inverse of current mult factor on append
val = (val - self.add) * pow(self.mult, self.MOD-2, self.MOD) % self.MOD
self.seq.append(val)
def addAll(self, inc: int) -> None:
self.add = (self.add + inc) % self.MOD
def multAll(self, m: int) -> None:
self.mult = self.mult * m % self.MOD
self.add = self.add * m % self.MOD
def getIndex(self, idx: int) -> int:
if idx >= len(self.seq):
return -1
return (self.seq[idx] * self.mult + self.add) % self.MODThe append operation appends a transformed value to the sequence by reversing the current operations effect using modular arithmetic inverses. addAll and multAll update cumulative add and mult factors respectively. getIndex applies stored operations to retrieve the correct value.
Time complexity for append is O(1) with efficient modular inverse calculation. Other operations are O(1).
Space complexity is O(n) for maintaining the sequence.
Approach 2: Efficient Use of Lazy Evaluation and Modular Arithmetic
Overview: Use mathematical properties of addition and multiplication with modular arithmetic for maintaining sequence properties efficiently without updating the sequence on every operation.
Explanation: We can keep track of transformations applied to the entire sequence using lazy evaluations. When retrieving an element by index, compute its final value by applying all saved transformations.
class Fancy {
constructor() {
this.MOD = 10 ** 9 + 7;
this.seq = [];
this.add = 0;
this.mult = 1;
}
append(val) {
val = ((val - this.add) * this.modInverse(this.mult)) % this.MOD;
this.seq.push((val + this.MOD) % this.MOD);
}
addAll(inc) {
this.add = (this.add + inc) % this.MOD;
}
multAll(m) {
this.mult = (this.mult * m) % this.MOD;
this.add = (this.add * m) % this.MOD;
}
getIndex(idx) {
if (idx >= this.seq.length) return -1;
return (this.seq[idx] * this.mult + this.add) % this.MOD;
}
modInverse(x) {
return this.modularExp(x, this.MOD - 2);
}
modularExp(base, exp) {
let result = 1;
while (exp > 0) {
if (exp % 2 !== 0) result = (result * base) % this.MOD;
base = (base * base) % this.MOD;
exp = Math.floor(exp / 2);
}
return result;
}
}Similar to the Python approach, JavaScript implementation utilizes a lazy evaluation mechanism and mathematical inverses to apply effects during retrieval rather than upon each operation. Inverse calculations are handled via modular exponentiation for efficiency.
Time complexity for each operation remains O(1), leveraging fast modular arithmetic.
Space complexity is O(n) as it maintains the sequence.
Approach 3: Efficient Operations Tracking
This approach optimizes by tracking the cumulative effects of the operations using incremental values and coefficients. Instead of applying operations directly on the sequence, we maintain an additive increment totalAdd and a multiplicative factor totalMult.
class Fancy:
def __init__(self):
self.sequence = []
self.totalAdd = 0
self.totalMult = 1
self.mod = 10**9 + 7
def append(self, val):
# Reverse the current operations to store the original value
val = (val - self.totalAdd * pow(self.totalMult, -1, self.mod)) % self.mod
val = val * pow(self.totalMult, -1, self.mod) % self.mod
self.sequence.append(val)
def addAll(self, inc):
self.totalAdd = (self.totalAdd + inc) % self.mod
def multAll(self, m):
self.totalMult = self.totalMult * m % self.mod
self.totalAdd = self.totalAdd * m % self.mod
def getIndex(self, idx):
if idx >= len(self.sequence):
return -1
return (self.sequence[idx] * self.totalMult + self.totalAdd) % self.mod#include <vector>
using namespace std;
class Fancy {
public:
vector<long long> seq;
long long totalAdd, totalMult;
const int MOD = 1e9 + 7;
Fancy() : totalAdd(0), totalMult(1) {}
void append(int val) {
val = (val - totalAdd + MOD) % MOD;
val = val * modInverse(totalMult, MOD) % MOD;
seq.push_back(val);
}
void addAll(int inc) {
totalAdd = (totalAdd + inc) % MOD;
}
void multAll(int m) {
totalMult = totalMult * m % MOD;
totalAdd = totalAdd * m % MOD;
}
int getIndex(int idx) {
if (idx >= seq.size()) return -1;
long long result = (seq[idx] * totalMult + totalAdd) % MOD;
return (int)result;
}
private:
long long modInverse(long long a, long long m) {
long long m0 = m, t, q;
long long x0 = 0, x1 = 1;
if (m == 1) return 0;
while (a > 1) {
q = a / m;
t = m;
m = a % m, a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0) x1 += m0;
return x1;
}
};The Python solution uses a modulo operation to efficiently manage the applied transformations.
append: Inserts the value by reversing current transformations.addAll: Updates the ongoing cumulative addition effect.multAll: Updates cumulative multiplication effect and adjusts previous additive impact.getIndex: Retrieves an adjusted value by applying stored transformations.
Time Complexity: O(1) per operation.
Space Complexity: O(n), where n is the number of values appended.
Approach 4: Delayed Application with Lazy Propagation
In this strategy, we store the sequence as-is and apply cumulative transformations only when necessary. This involves calculating the effects just-in-time when accessing elements, thereby delaying computation and optimizing space allocation and access costs.
import java.util.*;
class Fancy {
List<Long> sequence = new ArrayList<>();
long totalAdd = 0;
long totalMult = 1;
final int MOD = 1_000_000_007;
public Fancy() {}
public void append(int val) {
sequence.add(val - totalAdd * modInverse(totalMult, MOD) % MOD);
}
public void addAll(int inc) {
totalAdd = (totalAdd + inc) % MOD;
}
public void multAll(int m) {
totalMult = totalMult * m % MOD;
totalAdd = totalAdd * m % MOD;
}
public int getIndex(int idx) {
if (idx >= sequence.size()) return -1;
long val = sequence.get(idx);
return (int)((val * totalMult + totalAdd) % MOD);
}
private long modInverse(long a, long m) {
long m0 = m, t, q;
long x0 = 0, x1 = 1;
if (m == 1) return 0;
while (a > 1) {
q = a / m;
t = m;
m = a % m; a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0) x1 += m0;
return x1;
}
}using System;
using System.Collections.Generic;
public class Fancy {
private List<long> sequence = new List<long>();
private long totalAdd = 0;
private long totalMult = 1;
private const int MOD = 1000000007;
public Fancy() { }
public void Append(int val) {
sequence.Add((val - totalAdd + MOD) % MOD * ModInverse(totalMult, MOD) % MOD);
}
public void AddAll(int inc) {
totalAdd = (totalAdd + inc) % MOD;
}
public void MultAll(int m) {
totalMult = (totalMult * m) % MOD;
totalAdd = (totalAdd * m) % MOD;
}
public int GetIndex(int idx) {
if (idx >= sequence.Count) return -1;
long result = (sequence[idx] * totalMult + totalAdd) % MOD;
return (int)result;
}
private long ModInverse(long a, long mod) {
long m0 = mod, t, q;
long x0 = 0, x1 = 1;
if (mod == 1) return 0;
while (a > 1) {
q = a / mod;
t = mod;
mod = a % mod;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
return x1 < 0 ? x1 + m0 : x1;
}
}The Java implementation uses a list to maintain the sequence as originally appended. The operations modify a cumulative set of transformation variables.
appendcaptures values adjusted by existing transformation effects reversed using a modular inverse.addAllincrements a global additive transformation.multAllscales bothtotalAddandtotalMult.getIndexlazily calculates the required result for the index given the cumulative operations.
Time Complexity: O(1) per operation.
Space Complexity: O(n), where n is the number of values appended.
Approach 5: Default Approach
const MOD = 1000000007n;
class Node {
left: Node | null = null;
right: Node | null = null;
l: number;
r: number;
mid: number;
v = 0n;
add = 0n;
mul = 1n;
constructor(l: number, r: number) {
this.l = l;
this.r = r;
this.mid = (l + r) >> 1;
}
}
class SegmentTree {
root: Node;
constructor() {
this.root = new Node(1, 100001);
}
modifyAdd(l: number, r: number, inc: bigint, node: Node = this.root): void {
if (l > r) return;
if (node.l >= l && node.r <= r) {
node.v = (node.v + BigInt(node.r - node.l + 1) * inc) % MOD;
node.add = (node.add + inc) % MOD;
return;
}
this.pushdown(node);
if (l <= node.mid) this.modifyAdd(l, r, inc, node.left!);
if (r > node.mid) this.modifyAdd(l, r, inc, node.right!);
this.pushup(node);
}
modifyMul(l: number, r: number, m: bigint, node: Node = this.root): void {
if (l > r) return;
if (node.l >= l && node.r <= r) {
node.v = (node.v * m) % MOD;
node.add = (node.add * m) % MOD;
node.mul = (node.mul * m) % MOD;
return;
}
this.pushdown(node);
if (l <= node.mid) this.modifyMul(l, r, m, node.left!);
if (r > node.mid) this.modifyMul(l, r, m, node.right!);
this.pushup(node);
}
query(l: number, r: number, node: Node = this.root): bigint {
if (l > r) return 0n;
if (node.l >= l && node.r <= r) return node.v;
this.pushdown(node);
let v = 0n;
if (l <= node.mid) v = (v + this.query(l, r, node.left!)) % MOD;
if (r > node.mid) v = (v + this.query(l, r, node.right!)) % MOD;
return v;
}
pushup(node: Node): void {
node.v = (node.left!.v + node.right!.v) % MOD;
}
pushdown(node: Node): void {
if (!node.left) node.left = new Node(node.l, node.mid);
if (!node.right) node.right = new Node(node.mid + 1, node.r);
if (node.add !== 0n || node.mul !== 1n) {
const add = node.add;
const mul = node.mul;
const left = node.left!;
const right = node.right!;
left.v = (left.v * mul + BigInt(left.r - left.l + 1) * add) % MOD;
right.v = (right.v * mul + BigInt(right.r - right.l + 1) * add) % MOD;
left.add = (left.add * mul + add) % MOD;
right.add = (right.add * mul + add) % MOD;
left.mul = (left.mul * mul) % MOD;
right.mul = (right.mul * mul) % MOD;
node.add = 0n;
node.mul = 1n;
}
}
}
class Fancy {
n = 0;
tree = new SegmentTree();
append(val: number): void {
this.n++;
this.tree.modifyAdd(this.n, this.n, BigInt(val));
}
addAll(inc: number): void {
this.tree.modifyAdd(1, this.n, BigInt(inc));
}
multAll(m: number): void {
this.tree.modifyMul(1, this.n, BigInt(m));
}
getIndex(idx: number): number {
if (idx >= this.n) return -1;
return Number(this.tree.query(idx + 1, idx + 1));
}
}
/**
* Your Fancy object will be instantiated and called as such:
* var obj = new Fancy()
* obj.append(val)
* obj.addAll(inc)
* obj.multAll(m)
* var param_4 = obj.getIndex(idx)
*/const MOD int64 = 1e9 + 7
type Node struct {
left *Node
right *Node
l int
r int
mid int
v int64
add int64
mul int64
}
func newNode(l, r int) *Node {
return &Node{
l: l,
r: r,
mid: (l + r) >> 1,
mul: 1,
}
}
type SegmentTree struct {
root *Node
}
func newSegmentTree() *SegmentTree {
return &SegmentTree{
root: newNode(1, 100001),
}
}
func (t *SegmentTree) modifyAdd(l, r int, inc int64) {
t.modifyAddNode(l, r, inc, t.root)
}
func (t *SegmentTree) modifyAddNode(l, r int, inc int64, node *Node) {
if l > r {
return
}
if node.l >= l && node.r <= r {
node.v = (node.v + int64(node.r-node.l+1)*inc) % MOD
node.add = (node.add + inc) % MOD
return
}
t.pushdown(node)
if l <= node.mid {
t.modifyAddNode(l, r, inc, node.left)
}
if r > node.mid {
t.modifyAddNode(l, r, inc, node.right)
}
t.pushup(node)
}
func (t *SegmentTree) modifyMul(l, r int, m int64) {
t.modifyMulNode(l, r, m, t.root)
}
func (t *SegmentTree) modifyMulNode(l, r int, m int64, node *Node) {
if l > r {
return
}
if node.l >= l && node.r <= r {
node.v = node.v * m % MOD
node.add = node.add * m % MOD
node.mul = node.mul * m % MOD
return
}
t.pushdown(node)
if l <= node.mid {
t.modifyMulNode(l, r, m, node.left)
}
if r > node.mid {
t.modifyMulNode(l, r, m, node.right)
}
t.pushup(node)
}
func (t *SegmentTree) query(l, r int) int {
return int(t.queryNode(l, r, t.root))
}
func (t *SegmentTree) queryNode(l, r int, node *Node) int64 {
if l > r {
return 0
}
if node.l >= l && node.r <= r {
return node.v
}
t.pushdown(node)
var v int64
if l <= node.mid {
v = (v + t.queryNode(l, r, node.left)) % MOD
}
if r > node.mid {
v = (v + t.queryNode(l, r, node.right)) % MOD
}
return v
}
func (t *SegmentTree) pushup(node *Node) {
node.v = (node.left.v + node.right.v) % MOD
}
func (t *SegmentTree) pushdown(node *Node) {
if node.left == nil {
node.left = newNode(node.l, node.mid)
}
if node.right == nil {
node.right = newNode(node.mid+1, node.r)
}
if node.add != 0 || node.mul != 1 {
add := node.add
mul := node.mul
left := node.left
right := node.right
left.v = (left.v*mul + int64(left.r-left.l+1)*add) % MOD
right.v = (right.v*mul + int64(right.r-right.l+1)*add) % MOD
left.add = (left.add*mul + add) % MOD
right.add = (right.add*mul + add) % MOD
left.mul = left.mul * mul % MOD
right.mul = right.mul * mul % MOD
node.add = 0
node.mul = 1
}
}
type Fancy struct {
n int
tree *SegmentTree
}
func Constructor() Fancy {
return Fancy{
tree: newSegmentTree(),
}
}
func (f *Fancy) Append(val int) {
f.n++
f.tree.modifyAdd(f.n, f.n, int64(val))
}
func (f *Fancy) AddAll(inc int) {
f.tree.modifyAdd(1, f.n, int64(inc))
}
func (f *Fancy) MultAll(m int) {
f.tree.modifyMul(1, f.n, int64(m))
}
func (f *Fancy) GetIndex(idx int) int {
if idx >= f.n {
return -1
}
return f.tree.query(idx+1, idx+1)
}Complexity comparison
| Approach | Complexity |
|---|---|
| Lazy Propagation Using Differential Storage | Time complexity for |
| Efficient Use of Lazy Evaluation and Modular Arithmetic | Time complexity for each operation remains O(1), leveraging fast modular arithmetic. |
| Efficient Operations Tracking | Time Complexity: O(1) per operation. Space Complexity: O(n), where n is the number of values appended. |
| Delayed Application with Lazy Propagation | Time Complexity: O(1) per operation. Space Complexity: O(n), where n is the number of values appended. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Direct Simulation | O(n) per update | O(n) | Small constraints or quick prototype to verify logic |
| Lazy Global Affine Transformation | O(1) per operation | O(n) | Optimal solution when operations affect all elements uniformly |
| Operations Tracking / Differential Storage | O(1) amortized | O(n) | Useful when tracking cumulative transformations over time |
| Segment Tree with Lazy Propagation | O(log n) | O(n) | General-purpose range update problems requiring flexible queries |
Frequently asked questions
Is Fancy Sequence easy or hard?
Fancy Sequence is classified as a Hard problem because it requires recognizing that repeated add and multiply operations form an affine transformation. Implementing the lazy math correctly with modular inverses and maintaining correct values during append operations can be tricky.
Fancy Sequence Python/Java solution
Python solutions typically implement the affine transformation technique with modular inverse using pow(x, MOD-2, MOD). Java, C++, and JavaScript implementations follow the same logic with long integers and modular arithmetic to prevent overflow while maintaining O(1) operations.
How to solve Fancy Sequence in O(1)?
Maintain two global variables representing multiplication and addition factors applied to the entire sequence. When appending a value, store its normalized version by reversing the current transformation using modular inverse. During getIndex, reconstruct the real value with (stored_value * mul + add) mod 1e9+7. This keeps all operations constant time.
What is the best approach for Fancy Sequence?
The optimal approach models all operations as an affine transformation x -> a*x + b applied lazily to the sequence. Instead of updating every element, maintain global multiplier and addition values and store appended numbers in normalized form using modular inverse. This allows append, addAll, multAll, and getIndex to run in O(1) time with O(n) space.
Is Fancy Sequence asked at Google/Amazon/Meta?
Fancy Sequence represents the type of design-plus-math problem commonly asked in top tech interviews including Google, Meta, and Amazon. It tests understanding of lazy updates, modular arithmetic, and data structure design under heavy operation constraints.
What data structure is used in Fancy Sequence?
The optimal solution primarily uses an array combined with lazy global transformation variables. Alternative implementations can use a segment tree with lazy propagation to support range updates, though the affine transformation trick is more efficient.
What is the time complexity of Fancy Sequence?
Using the optimal lazy affine transformation approach, every operation runs in O(1) time. The sequence stores values in normalized form and applies the global transformation during retrieval. Space complexity is O(n) for storing the appended elements.
