Skip to content

Builtins

Everything on this page works without imports or setup. For graphs, segment trees, and other data structures, see Stdlib.


BuiltinWhat it does
filled(n, val)new array of length n, every element set to val
filled(n, filled(m, 0))2D array (n rows, m cols)
zeros(n)shorthand for filled(n, 0)
zeros(n, m)shorthand for filled(n, filled(m, 0))
BuiltinWhat it does
sort(a)sort ascending in place
sort(a, desc)sort descending in place
sort(a, |x, y| cmp)sort with a custom comparator
sort_by(a, key = |x| ...)sort by a key function
sorted(a)return a sorted copy (original unchanged)
argsort(a)return the permutation that would sort a
BuiltinWhat it does
lower(a, x)first index where a[idx] >= x
upper(a, x)first index where a[idx] > x
BuiltinWhat it does
reverse(a)reverse in place
fill(a, val)overwrite every element with val
unique(a)remove consecutive duplicates in place
swap(a, b)swap two values
BuiltinWhat it does
len(a)length of an array or string
sum(a)sum of all elements
min(a)smallest element
max(a)largest element
count(a, pred)how many elements satisfy pred
count(a, val)how many elements equal val
any(a, pred)true if at least one element matches
all(a, pred)true if every element matches
find(a, pred)first element matching pred, or -1
min_by(a, key = |x| ...)element with smallest key
max_by(a, key = |x| ...)element with largest key

All of these also work as methods: a.sum(), a.min(), a.count(pred), etc.

BuiltinWhat it does
filter(a, pred)new array with only matching elements
map(a, f)new array with f applied to each element
flatten(a)flatten a nested array one level
chunk(a, size)split into groups of size
windows(a, k)sliding windows of width k
zip(a, b)pair up elements from two arrays
enumerate(a)pair each element with its index
reversed(a)return a reversed copy

Method-only helpers:

a.push(x) # append an element
a.compress() # coordinate compression
a.prefix_sum() # prefix-sum object with .query(l, r)
a.suffix_sum() # suffix-sum object with .query(l, r)
a.next_greater() # next-greater-element array
a.next_smaller() # next-smaller-element array
a.sliding_max(k) # sliding window maximum
a.sliding_min(k) # sliding window minimum
a.flat_map(f) # map then flatten

Iterating permutations, subsets, and combinations

Section titled “Iterating permutations, subsets, and combinations”

Use these in for loops to enumerate combinatorial objects:

for p in each_perm(a): # every permutation of a
...
for s in each_subset(mask): # every submask of a bitmask
...
for c in each_combo(a, k): # every k-element combination
...

Related helpers:

BuiltinWhat it does
next_perm(a)advance to next lexicographic permutation in place
prev_perm(a)go back to previous permutation in place

BuiltinWhat it does
abs(x)absolute value
min(a, b)smaller of two values
max(a, b)larger of two values
gcd(a, b)greatest common divisor
lcm(a, b)least common multiple
pow(a, b)integer exponentiation (same as a ** b)
isqrt(n)integer square root
floor_div(a, b)floor division (same as a // b)
ceil_div(a, b)ceiling division
comb(n, k)binomial coefficient modulo MOD
modinv(a)modular inverse of a modulo MOD
BuiltinWhat it does
sieve(n)boolean sieve of Eratosthenes up to n
primes(n)list of primes up to n
factorize(n)prime factorization of n
divisors(n)sorted list of all divisors of n

BuiltinWhat it does
popcount(x)number of set bits
has_bit(x, i)true if bit i is set
set_bit(x, i)return x with bit i set
clr_bit(x, i)return x with bit i cleared
lowbit(x)lowest set bit (value, not index)

BuiltinWhat it does
stoi(s)parse string to int
stoll(s)parse string to long
to_string(x)convert a value to its string representation
chr(code)character with the given ASCII code
ord(c)ASCII code of a character
BuiltinWhat it does
toupper(s)uppercase copy of a string
tolower(s)lowercase copy of a string
split(s, delim)split a string by delimiter
join(a, sep)join an array into a string with separator
replace(s, from, to)replace all occurrences of from with to
BuiltinWhat it does
isdigit(c)true if c is a digit
isalpha(c)true if c is a letter
isupper(c)true if c is uppercase
islower(c)true if c is lowercase
BuiltinWhat it does
z_func(s)Z-array
kmp_fail(s)KMP failure function
kmp_search(s, t)find all occurrences of pattern t in text s
suffix_array(s)suffix array
strhash(s)rolling hash object with .query(l, r) and .eq(l1, r1, l2, r2)

prefix(a, op = sum)
prefix(a, op = xor)
suffix(a, op = max)
prefix_2d(mat, op = sum)
prefix(a, init = 1, reducer = |acc: int, x: int| acc * x)

Built-in reducers: sum, xor, max, min, gcd.

prefix_2d is sum-only.

For custom folds, use the three-argument form with init and reducer.


BuiltinWhat it does
mex(a)minimum excludant
argsort(a)sort permutation
inversion_count(a)count inversions
lis(a)length of longest increasing subsequence
lcs(s, t)longest common subsequence
accumulate(a)cumulative prefix values

BuiltinWhat it does
bsearch(lo, hi, pred)first integer in [lo, hi] where pred is true
bsearch_last(lo, hi, pred)last integer in [lo, hi] where pred is true
bsearch_float(lo, hi, eps, pred)floating-point binary search to precision eps

These create the objects documented in Stdlib.

graph(n) # directed unweighted graph
graph(n, undirected = true) # undirected unweighted graph
wgraph(n) # directed weighted graph
wgraph(n, undirected = true) # undirected weighted graph
grid(mat) # grid with BFS, components, neighbors
grid(mat, dirs = 8) # 8-directional grid
grid_graph(mat) # convert grid to Graph object
grid_graph(mat, dirs = 8)
tree(n) # tree for LCA and distance queries
dsu(n) # disjoint set union
segtree(n, op = sum) # segment tree
segtree(a, op = sum) # segment tree from array
lazy_segtree(n, op = sum) # lazy segment tree
lazy_segtree(a, op = max)
bit(n) # Fenwick tree
sparse(a, op = min) # sparse table
strhash(s) # rolling hash

BuiltinWhat it does
println xprint x followed by a newline
print a, b, cprint values separated by spaces
println arrprint all array elements on one line
output arrprint one element per line
output arr, sep=" "custom separator
newlineemit a blank line
readline()read an entire line as a string
flush()flush stdout
debug(x)print x to stderr (useful for local testing)

BuiltinWhat it does
exit(code)terminate the program with exit code
assert(cond)abort if cond is false
get(tuple, i)access element i of a tuple (compile-time index)

NameValueWhen to use
INF~10^18sentinel for shortest-path / DP problems (64-bit)
NINF~-10^18negative sentinel
INF32~10^9sentinel when you need a 32-bit range
MOD10^9 + 7default modulus (changeable with #!mod)