cp-snippets
Arrays
DifferenceArray
Helper class for range updates using difference array technique.
Source code in cp_snippets/arrays.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
get_array()
Reconstructs and returns the modified array.
Source code in cp_snippets/arrays.py
100 101 102 103 104 105 106 107 108 109 110 | |
update(l, r, val)
Adds val to arr[l...r] (inclusive).
Source code in cp_snippets/arrays.py
89 90 91 92 93 94 95 96 97 98 | |
binary_search(arr, target, *, key=None)
Binary search in a sorted array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Sequence[T]
|
Sorted sequence. |
required |
target
|
T
|
Value to search. |
required |
key
|
Optional[Callable[[T], T]]
|
Optional transform applied to elements before comparison. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Index of |
Source code in cp_snippets/arrays.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
get_prefix_sum(arr)
Computes the prefix sum array P where P[i] is the sum of arr[0...i-1]. P[0] = 0.
Source code in cp_snippets/arrays.py
55 56 57 58 59 60 61 62 63 64 | |
lower_bound(arr, target)
Returns the first index i such that arr[i] >= target in a sorted array.
Source code in cp_snippets/arrays.py
46 47 48 | |
max_subarray_sum(arr)
Finds the maximum subarray sum using Kadane's Algorithm. Returns 0 if the array is empty. For arrays with all negative numbers, returns the max single element.
Source code in cp_snippets/arrays.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
prefix_sum_2d(grid)
Builds 2D prefix sums.
Returns ps of shape (n+1) x (m+1) where:
ps[i][j] = sum of grid[0..i-1][0..j-1]
Source code in cp_snippets/arrays.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
query_range_sum(prefix_sum, l, r)
Returns the sum of arr[l...r] (inclusive) using the prefix sum array.
Source code in cp_snippets/arrays.py
67 68 69 70 71 | |
query_range_sum_2d(ps, r1, c1, r2, c2)
Rectangle sum query on a 2D prefix sum array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ps
|
List[List[int]]
|
2D prefix sum array from |
required |
r1, c1
|
Top-left (inclusive). |
required | |
r2, c2
|
Bottom-right (inclusive). |
required |
Source code in cp_snippets/arrays.py
132 133 134 135 136 137 138 139 140 | |
sliding_window_max(arr, k)
Calculates the maximum of every window of size k using a deque.
Source code in cp_snippets/arrays.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
sliding_window_sum(arr, k)
Calculates the sum of every window of size k.
Source code in cp_snippets/arrays.py
143 144 145 146 147 148 149 150 151 152 153 154 155 | |
two_sum_sorted(arr, target)
Finds two indices (i, j) in a sorted array such that arr[i] + arr[j] == target. Returns (i, j) 0-indexed if found, otherwise None.
Source code in cp_snippets/arrays.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
upper_bound(arr, target)
Returns the first index i such that arr[i] > target in a sorted array.
Source code in cp_snippets/arrays.py
51 52 53 | |
Bit Utils
check_bit(n, i)
Checks if the ith bit of n is set.
Source code in cp_snippets/bit_utils.py
16 17 18 | |
clear_bit(n, i)
Sets the ith bit of n to 0.
Source code in cp_snippets/bit_utils.py
6 7 8 | |
count_set_bits(n)
Counts the number of set bits (1s) in the binary representation of n.
Note: Requires Python 3.10+ for int.bit_count().
Source code in cp_snippets/bit_utils.py
21 22 23 24 25 26 27 28 29 | |
is_power_of_two(n)
Checks if n is a power of two.
Source code in cp_snippets/bit_utils.py
37 38 39 | |
lowest_set_bit(n)
Returns the value of the lowest set bit in n (e.g., for 12 (1100), returns 4 (0100)).
Source code in cp_snippets/bit_utils.py
32 33 34 | |
set_bit(n, i)
Sets the ith bit of n to 1.
Source code in cp_snippets/bit_utils.py
1 2 3 | |
toggle_bit(n, i)
Toggles the ith bit of n.
Source code in cp_snippets/bit_utils.py
11 12 13 | |
DP
knapsack_01(weights, values, capacity)
0/1 knapsack maximum value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Sequence[int]
|
item weights |
required |
values
|
Sequence[int]
|
item values |
required |
capacity
|
int
|
knapsack capacity |
required |
Returns:
| Type | Description |
|---|---|
int
|
Maximum attainable value. |
Complexity
O(n * capacity) time, O(capacity) memory.
Source code in cp_snippets/dp.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
lis_length(arr)
Length of the Longest Increasing Subsequence (strict) in O(n log n).
Source code in cp_snippets/dp.py
7 8 9 10 11 12 13 14 15 16 | |
Graphs
UnionFind
Disjoint Set Union (Union-Find) with path compression + union by size.
Source code in cp_snippets/graphs.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
bfs_dist(n, adj, src)
Shortest distances from src in an unweighted graph.
Returns a list dist where dist[v] is the number of edges in the shortest
path from src to v, or -1 if unreachable.
Source code in cp_snippets/graphs.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
bfs_path(n, adj, src, dst)
Returns one shortest path (as a list of vertices) from src to dst in an unweighted graph.
Source code in cp_snippets/graphs.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
connected_components(n, adj)
Connected components in an undirected graph.
Source code in cp_snippets/graphs.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
dfs_iterative(adj, start)
Iterative DFS that returns the visitation order.
Source code in cp_snippets/graphs.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
dijkstra(n, adj, src)
Dijkstra shortest paths for non-negative edge weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of vertices. |
required |
adj
|
Sequence[Sequence[Tuple[int, int]]]
|
Adjacency list where adj[u] contains (v, w). |
required |
src
|
int
|
Source vertex. |
required |
Returns:
| Type | Description |
|---|---|
List[int]
|
(dist, parent) |
List[int]
|
dist[v] is the shortest distance from src to v (or a large number if unreachable). |
Tuple[List[int], List[int]]
|
parent[v] is previous vertex on a shortest path (or -1 if unreachable, src's parent is src). |
Source code in cp_snippets/graphs.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
reconstruct_path(parent, src, dst)
Reconstruct a path from src to dst given a parent array.
The convention is that parent[src] == src, and parent[v] == -1 means unreachable.
Source code in cp_snippets/graphs.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
topological_sort_kahn(n, adj)
Topological sort of a directed graph.
Returns:
| Type | Description |
|---|---|
Optional[List[int]]
|
A topological order list of length n, or None if a cycle exists. |
Source code in cp_snippets/graphs.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
Math
euler_totient(n, spf)
Computes Euler's Totient function phi(n) using SPF. phi(n) = count of integers <= n coprime to n.
Source code in cp_snippets/math_utils.py
116 117 118 119 120 121 122 123 124 125 126 127 | |
gcd(a, b)
Computes the Greatest Common Divisor of a and b.
Source code in cp_snippets/math_utils.py
1 2 3 4 5 | |
init_nCr(N, mod)
Precomputes factorials and inverse factorials up to N for nCr calculations. Returns: (fact, invfact) lists.
Source code in cp_snippets/math_utils.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
lcm(a, b)
Computes the Least Common Multiple of a and b.
Source code in cp_snippets/math_utils.py
8 9 10 11 12 | |
mod_add(a, b, mod)
Computes (a + b) % mod.
Source code in cp_snippets/math_utils.py
15 16 17 | |
mod_inv(a, mod)
Computes modular inverse of a modulo mod using Fermat's Little Theorem. Assumes mod is prime.
Source code in cp_snippets/math_utils.py
37 38 39 40 41 42 | |
mod_mul(a, b, mod)
Computes (a * b) % mod.
Source code in cp_snippets/math_utils.py
20 21 22 | |
mod_pow(a, b, mod)
Computes (a^b) % mod using binary exponentiation.
Source code in cp_snippets/math_utils.py
25 26 27 28 29 30 31 32 33 34 | |
nCr(n, r, fact, invfact, mod)
Computes nCr % mod using precomputed factorials. Returns 0 if r < 0 or r > n.
Source code in cp_snippets/math_utils.py
63 64 65 66 67 68 69 70 | |
prime_factorize(x, spf)
Returns prime factorization of x using precomputed SPF array. Returns: Dictionary {prime_factor: exponent}.
Source code in cp_snippets/math_utils.py
103 104 105 106 107 108 109 110 111 112 113 | |
sieve(n)
Sieve of Eratosthenes to find primes up to n. Returns: is_prime boolean list where is_prime[i] is True if i is prime.
Source code in cp_snippets/math_utils.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
spf_sieve(n)
Computes Smallest Prime Factor (SPF) for each number up to n. Useful for fast prime factorization.
Source code in cp_snippets/math_utils.py
89 90 91 92 93 94 95 96 97 98 99 100 | |
IO
char_matrix(n)
Reads n lines of strings and converts them into a list of list of characters.
Source code in cp_snippets/io.py
38 39 40 | |
fast_reader()
Returns an iterator that yields tokens from stdin one by one.
Source code in cp_snippets/io.py
58 59 60 | |
int_input()
Reads a single integer from standard input.
Source code in cp_snippets/io.py
5 6 7 | |
list_input(dtype=int)
Reads a line of space-separated values and returns a list. Default element type is int.
Source code in cp_snippets/io.py
15 16 17 | |
matrix_input(n, m=None, dtype=int)
Reads a matrix of size n x m. If m is None, reads n lines where each line can have arbitrary number of elements.
Source code in cp_snippets/io.py
28 29 30 31 32 33 34 35 | |
multi_input(dtype=int)
Reads a line of space-separated values and returns a map object. Usage: a, b, c = multi_input()
Source code in cp_snippets/io.py
20 21 22 23 24 25 | |
print_list(arr, sep=' ')
Prints elements of a list separated by 'sep'.
Source code in cp_snippets/io.py
48 49 50 | |
print_yes_no(cond)
Prints 'YES' if cond is True, else 'NO'.
Source code in cp_snippets/io.py
53 54 55 | |
read_all()
Reads all input from stdin until EOF and returns a list of tokens.
Source code in cp_snippets/io.py
43 44 45 | |
str_input()
Reads a single line of string from standard input, stripping leading/trailing whitespace.
Source code in cp_snippets/io.py
10 11 12 | |
Misc
ceil_div(a, b)
Ceiling division for integers.
Works for negative values as well.
Source code in cp_snippets/misc.py
9 10 11 12 13 14 15 16 | |
chunks(arr, size)
Yields consecutive chunks of length size from arr.
Source code in cp_snippets/misc.py
44 45 46 47 48 49 | |
coordinate_compress(values)
Coordinate compression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Sequence[T]
|
Any sortable values. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
List[int]
|
(compressed, uniq, index) |
|
compressed |
List[T]
|
list of ints, same length as values |
uniq |
Dict[T, int]
|
sorted unique values |
index |
Tuple[List[int], List[T], Dict[T, int]]
|
mapping from value -> compressed index |
Source code in cp_snippets/misc.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
floor_div(a, b)
Floor division for integers (same as a // b, here for symmetry).
Source code in cp_snippets/misc.py
19 20 21 22 23 | |
Trees
BinaryLiftingLCA
Lowest Common Ancestor for a rooted tree via binary lifting.
Complexity
Preprocess: O(n log n) Query LCA: O(log n)
Source code in cp_snippets/trees.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
dist(a, b)
Number of edges on the path between a and b.
Source code in cp_snippets/trees.py
171 172 173 174 | |
kth_ancestor(v, k)
Returns the k-th ancestor of v (0-th ancestor is v).
Source code in cp_snippets/trees.py
143 144 145 146 147 148 149 150 151 | |
lca(a, b)
Returns LCA(a, b).
Source code in cp_snippets/trees.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
FenwickTree
Fenwick Tree (Binary Indexed Tree) for point updates and prefix sums.
Indexing
Public methods accept 0-based indices; internally we use 1-based.
Source code in cp_snippets/trees.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
add(idx, delta)
Adds delta to a[idx].
Source code in cp_snippets/trees.py
29 30 31 32 33 34 | |
sum_prefix(r)
Returns sum(a[0..r]) inclusive. If r < 0 returns 0.
Source code in cp_snippets/trees.py
36 37 38 39 40 41 42 43 44 45 | |
sum_range(l, r)
Returns sum(a[l..r]) inclusive.
Source code in cp_snippets/trees.py
47 48 49 50 51 | |
SegmentTree
Iterative segment tree for range queries and point updates.
Default operation is sum; you can supply any associative op with identity e.
Query semantics
query(l, r) returns op over the half-open interval [l, r).
Source code in cp_snippets/trees.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
query(l, r)
Returns op(a[l..r))
Source code in cp_snippets/trees.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
update(idx, value)
Sets a[idx] = value.
Source code in cp_snippets/trees.py
82 83 84 85 86 87 88 89 | |
Strings
RollingHash
Double rolling hash implementation for string matching and hashing. 1-based indexing for hash queries is often easier, but we stick to 0-based for consistency with Python.
Source code in cp_snippets/strings.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
get_hash(l, r)
Returns the double hash of substring s[l...r] (inclusive).
Source code in cp_snippets/strings.py
87 88 89 90 91 92 93 94 | |
compute_pi(s)
Computes the prefix function (pi array) for KMP algorithm. pi[i] is the length of the longest proper prefix of s[0...i] that is also a suffix of s[0...i].
Source code in cp_snippets/strings.py
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
is_palindrome(s)
Checks if the string s is a palindrome.
Source code in cp_snippets/strings.py
97 98 99 | |
kmp_search(text, pattern)
Finds all occurrences of pattern in text using KMP algorithm. Returns a list of starting indices (0-based).
Source code in cp_snippets/strings.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
manacher(s)
Computes Manacher's algorithm to find longest palindromic substring. Returns the P array where P[i] is the length of the palindrome radius centered at T[i]. The input string s is transformed to T = #s[0]#s[1]...#s[n-1]# to handle even length palindromes. The length of the palindrome centered at original index i (mapped to T) is P[2*i + 2] - 1.
Source code in cp_snippets/strings.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
z_function(s)
Computes the Z-function for string s. z[i] is the length of the longest common prefix between s and the suffix of s starting at i.
Source code in cp_snippets/strings.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |