Skip to content

Instantly share code, notes, and snippets.

@emcapsulation
emcapsulation / floyds-cycle-finding-algorithm.cpp
Last active October 4, 2025 01:35
Floyd's Cycle Finding Algorithm. This algorithm can be used to detect a cycle in a linked list, and return a pointer to the node where the cycle began.
/**
* Floyd's Cycle Finding Algorithm
* If a cycle is present in the linked list, returns a pointer to the node
* where that cycle begins.
* If no cycle is present, returns nullptr.
*
* @param head A pointer to the head of the linked list.
*
* @return A pointer to the node where the cycle begins.
*/
@emcapsulation
emcapsulation / boyer-moore-majority-vote-algorithm.cpp
Last active October 4, 2025 23:38
Boyer-Moore Majority Vote Algorithm. Returns the majority element, i.e. the element which appears more than n/2 times.
#include <iostream>
#include <vector>
/**
* Boyer-Moore Majority Vote Algorithm.
* Returns the majority element. The majority element is
* the element which appears more than half the time (> n/2).
*
* @param nums A list of numbers.
*
@emcapsulation
emcapsulation / 01-knapsack-problem.cpp
Last active September 29, 2025 05:52
0/1 Knapsack Problem. Given a list of items each with a weight and value, and a maximum weight limit of your bag W, knapsackSolver will return the best total value you can pack without exceeding the weight limit. knapsackSolverGetItems will return a list of items you can pack to achieve this optimal value.
#include <iostream>
#include <vector>
/**
* Creates the n+1 x W+1 dp table.
*
* @param n The number of items.
* @param W The capacity of the bag.
* @param weights The list of weights of each item.
* @param values The list of values of each item.
@emcapsulation
emcapsulation / dutch-national-flag-problem.cpp
Last active October 5, 2025 00:11
Dutch National Flag Problem. Given a list of elements, where each element can only be one of three distinct values, this algorithm arranges the elements into three groups (in order) in O(n) time.
#include <vector>
/**
* Dutch National Flag Problem
* Given a list of elements, where each element can only be one of three
* distinct values, this algorithm arranges the elements of the input
* list into the three groups.
*
* @param nums A list of numbers where each number can only be one of
* three unique values.
@emcapsulation
emcapsulation / bit-manipulation-tricks.cpp
Last active November 2, 2025 11:36
Bit Manipulation Tricks
/**
* Trick #1: Check if an integer is even or odd.
*/
bool isEven(int x) {
return ((x&1) == 0);
}
/**
* Trick #2: Multiply and divide by 2^k.