snippets 0.1.0
Loading...
Searching...
No Matches
hsc_snippets Namespace Reference

Classes

class  BigInteger
 Implements a class for representing and manipulating large integers beyond the native integer range. More...
 
class  CircularDeque
 
class  DisjointSet
 
class  DominantTracker
 
struct  Interval
 
class  IntervalMap
 
class  IntervalSet
 
struct  ListNode
 
struct  Maximum
 
class  MonotonicStack
 
struct  Override
 
class  RationalNumber
 
class  SegmentTree
 
class  SlidingWindowMax
 
struct  TreeNode
 

Concepts

concept  numeric
 

Typedefs

template<typename T >
using MonotonicDecreasingStack = MonotonicStack<T, std::less_equal<T>>
 
template<typename T >
using MonotonicIncreasingStack = MonotonicStack<T, std::greater_equal<T>>
 

Functions

static TreeNodenew_binary_tree (const std::vector< std::optional< int > > v)
 
static std::vector< std::optional< int > > binary_tree_to_vector (TreeNode *root)
 
static void delete_binary_tree (TreeNode *root)
 
static int get_binary_tree_depth (TreeNode *root)
 
static void inorder (TreeNode *root, std::function< void(int)> func)
 
static void preorder (TreeNode *root, std::function< void(int)> func)
 
static void postorder (TreeNode *root, std::function< void(int)> func)
 
static std::unordered_map< int, std::vector< int > > binary_tree_to_adjacency_list (TreeNode *root)
 
static std::vector< std::vector< std::pair< int, int > > > make_weighted_directed_adjacency_list (int n, const std::vector< std::vector< int > > &edges)
 
static std::vector< std::vector< int > > make_unweighted_undirected_adjacency_list (int n, const std::vector< std::vector< int > > &edges)
 
static std::vector< std::vector< std::pair< int, int > > > make_weighted_undirected_adjacency_list (int n, const std::vector< std::vector< int > > &edges)
 
static std::vector< std::vector< int > > make_unweighted_directed_adjacency_list (int n, const std::vector< std::vector< int > > &edges)
 
static void breadth_first_search (std::vector< std::vector< int > > &adjacency_list, int root, std::function< void(int, int)> callback)
 
static void breadth_first_search (std::unordered_map< int, std::vector< int > > &adjacency_list, int root, std::function< void(int, int)> callback)
 
static void depth_first_search (std::vector< std::vector< int > > &adjacency_list, int root, std::function< void(int, int)> callback)
 
static int dijkstra (int n, const std::vector< std::vector< std::pair< int, int > > > &adjacency_list, int src, int dst)
 
static std::vector< int > find_euler_path_directed (const std::vector< std::vector< int > > &edges)
 
static std::vector< std::vector< int > > find_connected_components (std::unordered_map< int, std::vector< int > > &adj)
 
static int count_connected_components (const std::unordered_map< int, std::vector< int > > &adj)
 
template<std::integral T>
static bool operator< (const Interval< T > &interval, T x)
 
template<std::integral T>
static bool operator< (T x, const Interval< T > &interval)
 
template<std::integral T>
static bool operator< (const Interval< T > &interval1, const Interval< T > &interval2)
 
static int get_linked_list_length (ListNode *head)
 
static ListNodemake_linked_list (const std::vector< int > &v)
 
static std::vector< int > linked_list_to_vector (ListNode *head)
 
static void linked_list_delete (ListNode *head)
 
static ListNodelinked_list_remove (ListNode *head, size_t begin, size_t end)
 
static ListNodeget_linked_list_ith_node (ListNode *head, size_t i)
 
constexpr int modular_add (int x, int y)
 
constexpr int additive_inverse (int x)
 
constexpr int modular_subtract (int x, int y)
 
constexpr int modular_multiply (int x, int y)
 
constexpr int modular_square (int x)
 
constexpr int modular_cube (int x)
 
static int modular_pow2 (size_t exponent)
 
template<typename T >
std::vector< T > nextGreaterElement (const std::vector< T > &nums, std::function< T()> no_greater)
 
static int largestRectangleInHistogram (const std::vector< int > &heights)
 
template<std::integral T>
int numDigits (T num)
 
template<std::integral T>
int numBits (T num)
 
static std::vector< int > SieveOfEratosthenes (int n)
 
static bool isPerfectSquare (std::int32_t num)
 
template<std::integral T>
static std::vector< T > getPrefixMax (const std::vector< T > &v)
 Computes the prefix maximums of a given vector.
 
template<std::integral T>
static std::vector< T > getSuffixMax (const std::vector< T > &v)
 Computes the suffix maximums of a given vector.
 
template<std::integral T>
static std::vector< T > getPrefixMin (const std::vector< T > &v)
 Computes the prefix minimums of a given vector.
 
template<std::integral T>
static std::vector< T > getSuffixMin (const std::vector< T > &v)
 Computes the suffix minimums of a given vector.
 
template<std::integral T>
static std::vector< T > getPrefixSum (const std::vector< T > &v)
 Computes the prefix sums of a given vector.
 
template<std::integral T>
static std::vector< T > getSuffixSum (const std::vector< T > &v)
 Computes the suffix sums of a given vector.
 
static int subarraysWithAtMostKDistinct (const std::vector< int > &nums, int k)
 
template<std::totally_ordered T>
int numOfGreaterElements (const std::vector< T > &v, T value)
 
template<std::integral T>
bool containsInRange (const std::vector< T > &vec, T start, T end)
 
template<typename T , std::integral I = int>
std::optional< I > deferred_binary_search (I low, I high, const T &value, auto &&func)
 
template<typename T , std::integral I = int>
deferred_upper_bound (I low, I high, const T &value, auto &&func, auto &&comp)
 
template<typename T , std::integral I = int>
deferred_upper_bound (I low, I high, const T &value, auto &&func)
 
template<typename T , std::integral I = int>
deferred_lower_bound (I low, I high, const T &value, auto &&func, auto &&comp)
 
template<typename T , std::integral I = int>
deferred_lower_bound (I low, I high, const T &value, auto &&func)
 
template<std::integral T>
void sortThree (T &a, T &b, T &c)
 
static std::tuple< std::function< int(int)>, int > create_compression_mapper (const std::vector< int > &nums)
 
static std::vector< int > kmpSearch (const std::string &pat, const std::string &txt)
 
static bool isPalindrome (const std::string &s)
 
template<std::integral T>
std::string to_string (const std::vector< T > &vec)
 
template<std::integral T>
std::string to_string (std::pair< T, T > p)
 
template<std::integral T>
std::string to_string (const std::vector< std::pair< T, T > > &vec)
 
static std::string to_string (const std::vector< std::string > &vec)
 
template<std::integral T>
std::string to_string (const std::vector< std::vector< T > > &vec)
 
static std::vector< std::string > string_split (const std::string &s, char delimiter)
 
static std::string string_repeat (const std::string &s, size_t n)
 
static std::string string_repeat (char c, size_t n)
 
static std::string string_join (const std::vector< std::string > &strings, const std::string &delimiter)
 
template<numeric T>
bool lessThanAll (T x, T val)
 
template<numeric T, numeric... Args>
bool lessThanAll (T x, T val, Args... args)
 
template<numeric T>
bool lessThanOrEqualToAll (T x, T val)
 
template<numeric T, numeric... Args>
bool lessThanOrEqualToAll (T x, T val, Args... args)
 
template<numeric T>
bool greaterThanAll (T x, T val)
 
template<numeric T, numeric... Args>
bool greaterThanAll (T x, T val, Args... args)
 
template<numeric T>
bool greaterThanOrEqualToAll (T x, T val)
 
template<numeric T, numeric... Args>
bool greaterThanOrEqualToAll (T x, T val, Args... args)
 
template<numeric T>
sum (T x)
 
template<numeric T, numeric... Args>
sum (T x, Args... args)
 

Variables

static constexpr int MODULO = static_cast<int>(1e9 + 7)
 

Typedef Documentation

◆ MonotonicDecreasingStack

template<typename T >
using hsc_snippets::MonotonicDecreasingStack = MonotonicStack<T, std::less_equal<T>>

◆ MonotonicIncreasingStack

template<typename T >
using hsc_snippets::MonotonicIncreasingStack = MonotonicStack<T, std::greater_equal<T>>

Function Documentation

◆ additive_inverse()

int hsc_snippets::additive_inverse ( int x)
constexpr

◆ binary_tree_to_adjacency_list()

static std::unordered_map< int, std::vector< int > > hsc_snippets::binary_tree_to_adjacency_list ( TreeNode * root)
static

Converts a binary tree to an adjacency list representation. All node values in the binary tree must be unique. The adjacency list is bidirectional, meaning for each parent-child relation, both the parent's list contains the child and the child's list contains the parent.

Parameters
rootA pointer to the root node of the binary tree. If the tree is empty (nullptr), the function returns an empty adjacency list.
Returns
An unordered_map where keys are node values and values are vectors of integers representing the node values of adjacent nodes.

◆ binary_tree_to_vector()

static std::vector< std::optional< int > > hsc_snippets::binary_tree_to_vector ( TreeNode * root)
static

Converts a binary tree to a vector of optional integers.

Parameters
rootA pointer to the root node of the binary tree.
Returns
A vector of std::optional<int> representing the binary tree in level-order traversal. An std::nullopt value indicates the absence of a node at that position.

◆ breadth_first_search() [1/2]

static void hsc_snippets::breadth_first_search ( std::unordered_map< int, std::vector< int > > & adjacency_list,
int root,
std::function< void(int, int)> callback )
static

Performs a breadth-first search (BFS) on an undirected graph starting from a given root node. It uses a queue to explore nodes level by level, ensuring each node is visited exactly once.

Parameters
adjacency_listThe graph represented as an adjacency list, where each key-value pair corresponds to a node and its list of adjacent nodes.
rootThe starting node for the BFS.
callbackA function to be called for each visited node. It takes the distance from the root and the node itself as arguments.

◆ breadth_first_search() [2/2]

static void hsc_snippets::breadth_first_search ( std::vector< std::vector< int > > & adjacency_list,
int root,
std::function< void(int, int)> callback )
static

Performs a breadth-first search (BFS) traversal on a graph represented by an adjacency list, starting from the specified root node.

Parameters
adjacency_listThe adjacency list representation of the graph. Each element represents a node and contains the indices of its adjacent nodes.
rootThe index of the root node from which the BFS traversal starts.
callbackA callback function invoked for each visited node during the BFS traversal. It takes two parameters: the distance of the current node from the root and the index of the current node.

◆ containsInRange()

template<std::integral T>
bool hsc_snippets::containsInRange ( const std::vector< T > & vec,
T start,
T end )

◆ count_connected_components()

static int hsc_snippets::count_connected_components ( const std::unordered_map< int, std::vector< int > > & adj)
static

Counts the number of connected components in an undirected graph.

Parameters
adjThe graph represented as an adjacency list, where keys are node identifiers and values are lists of adjacent nodes.
Returns
The number of connected components in the graph.

◆ create_compression_mapper()

static std::tuple< std::function< int(int)>, int > hsc_snippets::create_compression_mapper ( const std::vector< int > & nums)
static

Creates a compression mapper function for the given vector of integers.

This function performs coordinate compression on the input vector nums, mapping each unique value to a continuous index in ascending order starting from 0. The returned tuple contains a function for efficient lookup of the compressed index corresponding to any value in the original vector and the count of unique elements.

Parameters
numsThe input vector of integers to be compressed. The vector can contain duplicate values.
Returns
A tuple containing:
  • A function that maps an integer to its compressed index. The compressed index represents the position of the integer in the sorted, unique version of nums.
  • An integer representing the count of unique elements in nums.
Note
The returned function captures the compressed vector by value, ensuring the integrity and lifespan of the data required for index lookup.

◆ deferred_binary_search()

template<typename T , std::integral I = int>
std::optional< I > hsc_snippets::deferred_binary_search ( I low,
I high,
const T & value,
auto && func )

Performs a binary search on a function-generated sequence of values to find a specific value. This function assumes that the values generated by func are in a non-decreasing order within the specified range of indices.

Template Parameters
TThe type of the values generated by the function and the type of value.
IThe integral type used for indexing, with a default of int.
Parameters
lowThe lowest index of the search range (inclusive).
highThe highest index of the search range (inclusive).
valueThe target value to search for within the function-generated sequence.
funcA callable that takes an index of type I and returns a value of type T. This function must return values in a non-decreasing order over the range [low, high].
Returns
std::optional<I> containing the index at which the value equals func(index), or std::nullopt if no such index exists.

◆ deferred_lower_bound() [1/2]

template<typename T , std::integral I = int>
I hsc_snippets::deferred_lower_bound ( I low,
I high,
const T & value,
auto && func )

Finds the first position in [low, high] where func(position) is greater than or equal to value.

Parameters
lowThe start of the search range (inclusive).
highThe end of the search range (inclusive).
valueThe target value for comparison.
funcA callable that returns values in a non-decreasing order.
Returns
The index of the first position where func(position) is not less than value.

◆ deferred_lower_bound() [2/2]

template<typename T , std::integral I = int>
I hsc_snippets::deferred_lower_bound ( I low,
I high,
const T & value,
auto && func,
auto && comp )

Finds the first position in [low, high] where func(position) is greater than or equal to value, using a custom comparator.

Parameters
lowThe start of the search range (inclusive).
highThe end of the search range (inclusive).
valueThe target value for comparison.
funcA callable that returns values in a non-decreasing order.
compA comparator to compare func(position) and value.
Returns
The index of the first position where !comp(func(position), value).

◆ deferred_upper_bound() [1/2]

template<typename T , std::integral I = int>
I hsc_snippets::deferred_upper_bound ( I low,
I high,
const T & value,
auto && func )

Finds the first position in [low, high] where func(position) is strictly greater than value.

Parameters
lowThe start of the search range (inclusive).
highThe end of the search range (inclusive).
valueThe target value for comparison.
funcA callable that returns values in a non-decreasing order.
Returns
The index of the first position where func(position) is greater than value.

◆ deferred_upper_bound() [2/2]

template<typename T , std::integral I = int>
I hsc_snippets::deferred_upper_bound ( I low,
I high,
const T & value,
auto && func,
auto && comp )

Finds the first position in [low, high] where func(position) is strictly greater than value, using a custom comparator.

Parameters
lowThe start of the search range (inclusive).
highThe end of the search range (inclusive).
valueThe target value for comparison.
funcA callable that returns values in a non-decreasing order.
compA comparator to compare func(position) and value.
Returns
The index of the first position where comp(value, func(position)) returns true.

◆ delete_binary_tree()

static void hsc_snippets::delete_binary_tree ( TreeNode * root)
static

Deletes all nodes of a binary tree to free memory.

Parameters
rootA pointer to the root node of the binary tree. If the pointer is nullptr, the function does nothing, safely handling the case of an empty tree or reaching the end of a branch.

◆ depth_first_search()

static void hsc_snippets::depth_first_search ( std::vector< std::vector< int > > & adjacency_list,
int root,
std::function< void(int, int)> callback )
static

Performs a depth-first search (DFS) traversal on a graph represented by an adjacency list, starting from the specified root node.

Parameters
adjacency_listThe adjacency list representation of the graph. Each element represents a node and contains the indices of its adjacent nodes.
rootThe index of the root node from which the DFS traversal starts.
callbackA callback function invoked for each visited node during the DFS traversal. It takes two parameters: the distance of the current node from the root and the index of the current node.

◆ dijkstra()

static int hsc_snippets::dijkstra ( int n,
const std::vector< std::vector< std::pair< int, int > > > & adjacency_list,
int src,
int dst )
static

Dijkstra's algorithm to find the shortest path from source to destination in a graph.

Parameters
nNumber of vertices in the graph.
adjacency_listAdjacency list representation of the graph where each element is a pair representing an edge (to, weight).
srcSource vertex.
dstDestination vertex.
Returns
Shortest distance from source to destination. Returns -1 if no path exists.

◆ find_connected_components()

static std::vector< std::vector< int > > hsc_snippets::find_connected_components ( std::unordered_map< int, std::vector< int > > & adj)
static

Finds and returns all connected components in an undirected graph. It iterates over all nodes, using a BFS starting from each unvisited node to discover all nodes in the same connected component.

Parameters
adjThe graph represented as an adjacency list, where keys are node identifiers and values are lists of adjacent nodes.
Returns
A vector of vectors, where each inner vector represents a connected component of the graph and contains all node identifiers within that component.

◆ find_euler_path_directed()

static std::vector< int > hsc_snippets::find_euler_path_directed ( const std::vector< std::vector< int > > & edges)
static

Finds an Eulerian path or circuit in a directed graph.

This function assumes that the given graph has an Eulerian path or circuit, which means the graph is connected and either:

  • All vertices have equal in-degrees and out-degrees (Eulerian circuit), or
  • All but two vertices have equal in-degrees and out-degrees, and one of those two vertices has out-degree = in-degree + 1 (start), and the other has in-degree = out-degree + 1 (end) (Eulerian path).
Parameters
edgesA vector of pairs representing directed edges in the graph. Each pair (a, b) represents a directed edge from a to b.
Returns
A vector representing the Eulerian path or circuit as a sequence of vertex indices. If a circuit exists, the path can start from any vertex in the circuit.

◆ get_binary_tree_depth()

static int hsc_snippets::get_binary_tree_depth ( TreeNode * root)
static

Calculates the depth of a binary tree.

Parameters
rootA pointer to the root node of the binary tree. If the tree is empty (nullptr), the depth is considered to be 0.
Returns
The depth of the binary tree as an integer. An empty tree has a depth of 0.

◆ get_linked_list_ith_node()

static ListNode * hsc_snippets::get_linked_list_ith_node ( ListNode * head,
size_t i )
static

Retrieves a pointer to the ith element in the linked list.

Parameters
headA pointer to the head of the linked list.
iThe index of the element to retrieve.
Returns
A pointer to the ith element in the linked list. If the index is out of bounds, it returns nullptr.

◆ get_linked_list_length()

static int hsc_snippets::get_linked_list_length ( ListNode * head)
static

Calculates the length of a linked list.

Parameters
headA pointer to the head of the linked list.
Returns
The number of nodes in the linked list.

◆ getPrefixMax()

template<std::integral T>
static std::vector< T > hsc_snippets::getPrefixMax ( const std::vector< T > & v)
static

Computes the prefix maximums of a given vector.

This function returns a vector where each element at index i contains the maximum value in the inclusive subarray v[0] to v[i].

Template Parameters
TThe integral type of the elements in the input vector.
Parameters
vThe input vector of integral type T.
Returns
std::vector<T> A vector of the same size as v, where each element at index i is the maximum value of the inclusive subarray v[0] to v[i].

◆ getPrefixMin()

template<std::integral T>
static std::vector< T > hsc_snippets::getPrefixMin ( const std::vector< T > & v)
static

Computes the prefix minimums of a given vector.

This function returns a vector where each element at index i contains the minimum value in the inclusive subarray v[0] to v[i].

Template Parameters
TThe integral type of the elements in the input vector.
Parameters
vThe input vector of integral type T.
Returns
std::vector<T> A vector of the same size as v, where each element at index i is the minimum value of the inclusive subarray v[0] to v[i].

◆ getPrefixSum()

template<std::integral T>
static std::vector< T > hsc_snippets::getPrefixSum ( const std::vector< T > & v)
static

Computes the prefix sums of a given vector.

This function returns a vector where each element at index i contains the sum of the elements in the inclusive subarray v[0] to v[i].

Template Parameters
TThe integral type of the elements in the input vector.
Parameters
vThe input vector of integral type T.
Returns
std::vector<T> A vector of the same size as v, where each element at index i is the sum of the elements in the inclusive subarray v[0] to v[i].

◆ getSuffixMax()

template<std::integral T>
static std::vector< T > hsc_snippets::getSuffixMax ( const std::vector< T > & v)
static

Computes the suffix maximums of a given vector.

This function returns a vector where each element at index i contains the maximum value in the inclusive subarray v[i] to v[n-1], where n is the size of the vector.

Template Parameters
TThe integral type of the elements in the input vector.
Parameters
vThe input vector of integral type T.
Returns
std::vector<T> A vector of the same size as v, where each element at index i is the maximum value of the inclusive subarray v[i] to v[n-1].

◆ getSuffixMin()

template<std::integral T>
static std::vector< T > hsc_snippets::getSuffixMin ( const std::vector< T > & v)
static

Computes the suffix minimums of a given vector.

This function returns a vector where each element at index i contains the minimum value in the inclusive subarray v[i] to v[n-1], where n is the size of the vector.

Template Parameters
TThe integral type of the elements in the input vector.
Parameters
vThe input vector of integral type T.
Returns
std::vector<T> A vector of the same size as v, where each element at index i is the minimum value of the inclusive subarray v[i] to v[n-1].

◆ getSuffixSum()

template<std::integral T>
static std::vector< T > hsc_snippets::getSuffixSum ( const std::vector< T > & v)
static

Computes the suffix sums of a given vector.

This function returns a vector where each element at index i contains the sum of the elements in the inclusive subarray v[i] to v[n-1], where n is the size of the vector.

Template Parameters
TThe integral type of the elements in the input vector.
Parameters
vThe input vector of integral type T.
Returns
std::vector<T> A vector of the same size as v, where each element at index i is the sum of the elements in the inclusive subarray v[i] to v[n-1].

◆ greaterThanAll() [1/2]

template<numeric T>
bool hsc_snippets::greaterThanAll ( T x,
T val )

◆ greaterThanAll() [2/2]

template<numeric T, numeric... Args>
bool hsc_snippets::greaterThanAll ( T x,
T val,
Args... args )

◆ greaterThanOrEqualToAll() [1/2]

template<numeric T>
bool hsc_snippets::greaterThanOrEqualToAll ( T x,
T val )

◆ greaterThanOrEqualToAll() [2/2]

template<numeric T, numeric... Args>
bool hsc_snippets::greaterThanOrEqualToAll ( T x,
T val,
Args... args )

◆ inorder()

static void hsc_snippets::inorder ( TreeNode * root,
std::function< void(int)> func )
static

In-order traversal of a binary tree.

Parameters
rootRoot node of the binary tree.
funcFunction to process each node's value.

◆ isPalindrome()

static bool hsc_snippets::isPalindrome ( const std::string & s)
static

Checks if a given string is a palindrome.

Parameters
sThe string to check for palindromicity.
Returns
True if 's' is a palindrome, False otherwise.

◆ isPerfectSquare()

static bool hsc_snippets::isPerfectSquare ( std::int32_t num)
static

Checks if a given number is a perfect square using a precomputed array of squares.

Parameters
numThe number to check if it is a perfect square.
Returns
True if num is a perfect square, otherwise false.

◆ kmpSearch()

static std::vector< int > hsc_snippets::kmpSearch ( const std::string & pat,
const std::string & txt )
static

Searches for all occurrences of a pattern within a text using the Knuth-Morris-Pratt (KMP) algorithm.

The KMP algorithm pre-processes the pattern to construct an array of longest proper prefixes which are also suffixes (LPS array). It then uses this LPS array to skip redundant comparisons when a mismatch occurs, thereby improving the search efficiency.

Parameters
patThe pattern string to search for within the text.
txtThe text string in which to search for the pattern.
Returns
A vector containing the starting indices of all occurrences of 'pat' within 'txt'.

◆ largestRectangleInHistogram()

static int hsc_snippets::largestRectangleInHistogram ( const std::vector< int > & heights)
static

LeetCode 84: Largest Rectangle in Histogram This function calculates the maximum area of a rectangle that can be formed within a given histogram. Each bar's height is given in the 'heights' vector, where each element represents the height of a bar.

Parameters
heightsA vector of integers where each integer represents the height of a histogram bar.
Returns
The maximum area of the rectangle that can be formed in the histogram.

◆ lessThanAll() [1/2]

template<numeric T>
bool hsc_snippets::lessThanAll ( T x,
T val )

◆ lessThanAll() [2/2]

template<numeric T, numeric... Args>
bool hsc_snippets::lessThanAll ( T x,
T val,
Args... args )

◆ lessThanOrEqualToAll() [1/2]

template<numeric T>
bool hsc_snippets::lessThanOrEqualToAll ( T x,
T val )

◆ lessThanOrEqualToAll() [2/2]

template<numeric T, numeric... Args>
bool hsc_snippets::lessThanOrEqualToAll ( T x,
T val,
Args... args )

◆ linked_list_delete()

static void hsc_snippets::linked_list_delete ( ListNode * head)
static

Deletes all nodes in a linked list to free memory.

Parameters
headA pointer to the head of the linked list to be deleted.

◆ linked_list_remove()

static ListNode * hsc_snippets::linked_list_remove ( ListNode * head,
size_t begin,
size_t end )
static

Removes nodes from a linked list in the specified range.

Parameters
headPointer to the head of the linked list.
beginThe starting index of the range to remove nodes (inclusive).
endThe ending index of the range to remove nodes (exclusive).
Returns
A pointer to the head of the modified linked list.

◆ linked_list_to_vector()

static std::vector< int > hsc_snippets::linked_list_to_vector ( ListNode * head)
static

Converts a linked list to a vector of integers.

Parameters
headA pointer to the head of the linked list.
Returns
A vector of integers containing the values of the linked list nodes.

◆ make_linked_list()

static ListNode * hsc_snippets::make_linked_list ( const std::vector< int > & v)
static

Creates a linked list from a vector of integers.

Parameters
vA reference to a vector of integers from which to create the linked list.
Returns
A pointer to the head of the newly created linked list.

◆ make_unweighted_directed_adjacency_list()

static std::vector< std::vector< int > > hsc_snippets::make_unweighted_directed_adjacency_list ( int n,
const std::vector< std::vector< int > > & edges )
static

Constructs an unweighted, directed adjacency list representation of a graph from a given set of edges. Nodes are indexed from 0 to n-1.

Parameters
nThe number of nodes in the graph.
edgesA vector of vectors representing edges, where each inner vector contains two integers: [from, to], denoting a directed edge from node 'from' to node 'to'.
Returns
A vector of vectors representing the adjacency list of the graph. Each inner vector corresponds to a node, containing the indices of connected nodes (edges are unweighted in this representation).

◆ make_unweighted_undirected_adjacency_list()

static std::vector< std::vector< int > > hsc_snippets::make_unweighted_undirected_adjacency_list ( int n,
const std::vector< std::vector< int > > & edges )
static

Constructs an unweighted, undirected adjacency list representation of a graph from a given set of edges. Nodes are indexed from 0 to n-1.

Parameters
nThe number of nodes in the graph.
edgesA vector of vectors representing edges, where each inner vector contains two integers: [from, to], denoting an edge from node 'from' to node 'to'.
Returns
A vector of vectors representing the adjacency list of the graph. Each inner vector corresponds to a node, containing the indices of connected nodes (edges are unweighted in this representation).

◆ make_weighted_directed_adjacency_list()

static std::vector< std::vector< std::pair< int, int > > > hsc_snippets::make_weighted_directed_adjacency_list ( int n,
const std::vector< std::vector< int > > & edges )
static

Constructs a weighted, directed adjacency list representation of a graph from a given set of edges. Nodes are indexed from 0 to n-1.

Parameters
nThe number of nodes in the graph.
edgesA vector of vectors representing edges, where each inner vector contains three integers: [from, to, weight], denoting a weighted edge from node 'from' to node 'to' with the given weight.
Returns
A vector of vectors of pairs representing the adjacency list of the graph. Each inner vector corresponds to a node, containing pairs of connected nodes and their respective edge weights.

◆ make_weighted_undirected_adjacency_list()

static std::vector< std::vector< std::pair< int, int > > > hsc_snippets::make_weighted_undirected_adjacency_list ( int n,
const std::vector< std::vector< int > > & edges )
static

Constructs a weighted, undirected adjacency list representation of a graph from a given set of edges. Nodes are indexed from 0 to n-1.

Parameters
nThe number of nodes in the graph.
edgesA vector of vectors representing edges, where each inner vector contains three integers: [from, to, weight], denoting a weighted edge between node 'from' and node 'to' with the given weight.
Returns
A vector of vectors of pairs representing the adjacency list of the graph. Each inner vector corresponds to a node, containing pairs of connected nodes and their respective edge weights.

◆ modular_add()

int hsc_snippets::modular_add ( int x,
int y )
constexpr

◆ modular_cube()

int hsc_snippets::modular_cube ( int x)
constexpr

◆ modular_multiply()

int hsc_snippets::modular_multiply ( int x,
int y )
constexpr

◆ modular_pow2()

static int hsc_snippets::modular_pow2 ( size_t exponent)
static

◆ modular_square()

int hsc_snippets::modular_square ( int x)
constexpr

◆ modular_subtract()

int hsc_snippets::modular_subtract ( int x,
int y )
constexpr

◆ new_binary_tree()

static TreeNode * hsc_snippets::new_binary_tree ( const std::vector< std::optional< int > > v)
static

Constructs a binary tree from a vector of optional integers.

Parameters
vA vector of std::optional<int>, where each element represents a potential node in the binary tree. An std::nullopt value indicates the absence of a node at that position.
Returns
A pointer to the root node of the newly constructed binary tree. Returns nullptr if the input vector is empty.

◆ nextGreaterElement()

template<typename T >
std::vector< T > hsc_snippets::nextGreaterElement ( const std::vector< T > & nums,
std::function< T()> no_greater )

Finds the next greater element for each element in a sequence.

Template Parameters
TThe type of elements in the sequence.
Parameters
numsThe sequence of elements.
no_greaterFunction to call when no greater element is found.
Returns
A vector containing the next greater element for each element in nums.

◆ numBits()

template<std::integral T>
int hsc_snippets::numBits ( T num)

Calculates the number of bits required to represent an integer in binary. For negative numbers, it returns the number of bits in the type (e.g., 32 for int), assuming two's complement representation.

Template Parameters
TThe type of the input number, constrained to integral types.
Parameters
numThe input number whose binary bit count is to be calculated.
Returns
The number of bits required to represent num in binary, or the bit size of T for negative numbers.

◆ numDigits()

template<std::integral T>
int hsc_snippets::numDigits ( T num)

Calculates the number of digits in the decimal representation of an integer.

Template Parameters
TThe type of the input number, constrained to integral types.
Parameters
numThe input number whose number of decimal digits is to be calculated.
Returns
The number of digits in the decimal representation of num.

◆ numOfGreaterElements()

template<std::totally_ordered T>
int hsc_snippets::numOfGreaterElements ( const std::vector< T > & v,
T value )

◆ operator<() [1/3]

template<std::integral T>
static bool hsc_snippets::operator< ( const Interval< T > & interval,
T x )
static

◆ operator<() [2/3]

template<std::integral T>
static bool hsc_snippets::operator< ( const Interval< T > & interval1,
const Interval< T > & interval2 )
static

◆ operator<() [3/3]

template<std::integral T>
static bool hsc_snippets::operator< ( T x,
const Interval< T > & interval )
static

◆ postorder()

static void hsc_snippets::postorder ( TreeNode * root,
std::function< void(int)> func )
static

Post-order traversal of a binary tree.

Parameters
rootRoot node of the binary tree.
funcFunction to process each node's value.

◆ preorder()

static void hsc_snippets::preorder ( TreeNode * root,
std::function< void(int)> func )
static

Pre-order traversal of a binary tree.

Parameters
rootRoot node of the binary tree.
funcFunction to process each node's value.

◆ SieveOfEratosthenes()

static std::vector< int > hsc_snippets::SieveOfEratosthenes ( int n)
static

Implements the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit n.

Parameters
nThe upper limit (inclusive) up to which prime numbers are to be found.
Returns
A std::vector<int> containing all the prime numbers less than or equal to n.

◆ sortThree()

template<std::integral T>
void hsc_snippets::sortThree ( T & a,
T & b,
T & c )

Sorts three elements in non-decreasing order using a simple comparison and swap algorithm.

Template Parameters
TThe type of the elements to be sorted. Must be an integral type.
Parameters
aReference to the first element, will be the smallest after sorting.
bReference to the second element, will be the middle element after sorting.
cReference to the third element, will be the largest after sorting.

◆ string_join()

static std::string hsc_snippets::string_join ( const std::vector< std::string > & strings,
const std::string & delimiter )
static

Joins a vector of strings into a single string, using a specified delimiter between each string.

Parameters
stringsThe vector of strings to be joined.
delimiterThe string used as the delimiter between each element in the vector.
Returns
A new string consisting of the elements in strings, joined by delimiter.

◆ string_repeat() [1/2]

static std::string hsc_snippets::string_repeat ( char c,
size_t n )
static

Repeats a given character c for n times, producing a new string.

This function creates a string consisting of the character c repeated n times. It efficiently initializes the string with the required size and fills it with the character c.

Parameters
cThe character to be repeated.
nThe number of times to repeat the character.
Returns
A new string consisting of the character c repeated n times. If n is 0, returns an empty string.

◆ string_repeat() [2/2]

static std::string hsc_snippets::string_repeat ( const std::string & s,
size_t n )
static

Repeats a given string s for n times efficiently.

This function creates a new string by repeating the input string s for n times. It pre-allocates the required memory and employs a doubling strategy to minimize the number of concatenations, which enhances performance, especially for large n.

Parameters
sThe string to be repeated.
nThe number of times to repeat the string.
Returns
A new string consisting of s repeated n times.

◆ string_split()

static std::vector< std::string > hsc_snippets::string_split ( const std::string & s,
char delimiter )
static

Splits a given string into a vector of substrings based on a specified delimiter.

Parameters
sThe input string to be split.
delimiterThe character used as the delimiter to split the string.
Returns
A vector of substrings obtained by splitting the input string by the delimiter.

◆ subarraysWithAtMostKDistinct()

static int hsc_snippets::subarraysWithAtMostKDistinct ( const std::vector< int > & nums,
int k )
static

Counts subarrays with at most k distinct integers using a sliding window approach.

Related LeetCode Problem: https://leetcode.com/problems/subarrays-with-k-different-integers/description/

Parameters
numsA vector of integers.
kThe maximum number of distinct integers allowed in a subarray.
Returns
The total count of such subarrays.

◆ sum() [1/2]

template<numeric T>
T hsc_snippets::sum ( T x)

◆ sum() [2/2]

template<numeric T, numeric... Args>
T hsc_snippets::sum ( T x,
Args... args )

◆ to_string() [1/5]

template<std::integral T>
std::string hsc_snippets::to_string ( const std::vector< std::pair< T, T > > & vec)

Convert a vector of pairs of integral type T to its string representation.

Template Parameters
TThe integral type of the elements in the pairs within the vector.
Parameters
vecThe vector of pairs to convert to a string representation.
Returns
The string representation of the vector of pairs, formatted as "[{first1, second1}, {first2, second2}, ...]".

◆ to_string() [2/5]

static std::string hsc_snippets::to_string ( const std::vector< std::string > & vec)
static

Convert a vector of strings to its string representation, with elements separated by commas. The resulting string is enclosed in square brackets.

Parameters
vecThe vector of strings to convert. Each element in the vector is expected to be a string.
Returns
A string that represents the vector's contents, formatted as "[element1, element2, ...]". If the vector is empty, the returned string will be "[]".

◆ to_string() [3/5]

template<std::integral T>
std::string hsc_snippets::to_string ( const std::vector< std::vector< T > > & vec)

Convert a vector of vectors of integral type T to its string representation.

Template Parameters
TThe integral type of elements in the vectors.
Parameters
vecThe vector of vectors to convert.
Returns
The string representation of the vector of vectors.

◆ to_string() [4/5]

template<std::integral T>
std::string hsc_snippets::to_string ( const std::vector< T > & vec)

Convert a vector of integral type T to its string representation.

Template Parameters
TThe integral type of elements in the vector.
Parameters
vecThe vector to convert.
Returns
The string representation of the vector.

◆ to_string() [5/5]

template<std::integral T>
std::string hsc_snippets::to_string ( std::pair< T, T > p)

Convert a pair of integral type T to its string representation.

Template Parameters
TThe integral type of the pair elements.
Parameters
pThe pair to convert to a string representation.
Returns
The string representation of the pair, formatted as "{first, second}".

Variable Documentation

◆ MODULO

int hsc_snippets::MODULO = static_cast<int>(1e9 + 7)
staticconstexpr