| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
This repository provides examples of algorithms, data structures, and problem-solving approaches for practical applications. These examples are implemented in C++, Python, Go, and Java, with each language utilizing its own test framework. Running the tests allows you to execute methods or functions on the underlying algorithmic logic.
Each project is configured in specific environments, as described below:
| Language | Version | Build | Packages | Remarks |
|---|---|---|---|---|
| C++ | C++20 | CMake | GNU Scientific Library (GSL), Google Test, Google Benchmark, fmt | vcpkg |
| Python | 3.12 | Poetry | NumPy, SciPy, NetworkX, pytest, pytest-benchmark | |
| Go | 1.22 | Go | Gonum, Testify | |
| Java | 21 | Gradle | Google Guava, JUnit, Java Microbenchmark Harness (JMH) |
C++ declaration/methods
auto v = std::vector{1, 2, 3, 4, 5};
auto sub_v = std::vector<int>{v.begin(), v.end() - 1};
auto arr = std::array{1, 2, 3, 4, 5};
auto sub_arr = std::array{arr.begin(), arr.end() - 1};
// algorithm
std::ranges::any_of(v, [](auto x) { return x % 2 == 0; })
std::ranges::all_of(v, [](auto x) { return x % 2 == 0; })
std::ranges::none_of(v, [](auto x) { return x % 2 == 0; })
std::ranges::for_each(v, [](auto x) { std::cout << x << " "; }).fun
std::ranges::count(v, 42)
std::ranges::count_if(v, [](auto x) { return x % 2 == 0; })
std::ranges::reverse(v)
std::ranges::rotate(v, v.end() - k)
std::ranges::sort(v)
std::ranges::min_element(v)
std::ranges::max_element(v)
std::ranges::minmax_element(v)Python declaration/functions
# list
number_list: list[int] = [1, 2, 3, 4, 5]
append(6), insert(3, 3), remove(4), pop(), pop(0), index(3), count(3), clear(), extend([6, 7, 8])
number_list.reverse() # in-place
reversed(number_list) # return an iterator
number_list.sort() # in-place
sorted(number_list) # return a new list(copy)
del(number_list[0]) # delete the first element
del(number_list[0:2]) # remove the slice
bisect.bisect_left(number_list, 3), bisect.bisect_right(number_list, 3), bisect.bisect(number_list, 3)
bisect.insort_left(number_list, 3), bisect.insort_right(number_list, 3), bisect.insort(number_list, 3)
# tuple
sample_tuple: tuple[int] = (1, 2, 3, 4, 5)
index(3), count(3)
### list comprehension
# single level of loop
even_list = [x for x in number_list if x % 2 == 0]
# two levels of loop
sample_list = [[1, 2, 3], [4, 5, 6]]
square_list = [[n ** 2 for n in row] for row in sample_list]
# multi levels of loop
list_a: list[int] = [1, 3, 5]
list_b: list[str] = ['a', 'b']
set_ab: set[tuple[int, str]] = {(a, b) for a in list_a for b in list_b}
# 2d array to 1d array
list_2d = [['a', 'b', 'c'], ['d', 'e', 'f']]
list_1d: list[str] = [ch for row in list_2d for ch in row]
# any/all
any(x % 2 == 0 for x in number_list)
all(x % 2 == 0 for x in number_list)Java declaration/methods
int[] arr = new int[]{1, 2, 3, 4, 5}; // array
int[][] matrix = new int[m][n]; // 2d array (m by n matrix)import java.util.*;
// Arrays
binarySearch(arr, 3), equals(arr, another_arr), copyOf(arr, arr.length), copyOfRange(arr, from, to),
sort(arr), sort(arr, from, to), fill(arr, 42), fill(arr, from, to, 42),
// Arrays.stream()
anyMatch(x -> x % 2 == 0), allMatch(x -> x % 2 == 0), noneMatch(x -> x % 2 == 0),
count(), sum(), min(), max(), average(), map(x -> x * 2).toArray(), filter(x -> x % 2 == 0).count()
// Collections
sort(list), binarySearch(list, 3), min(list), max(list), swap(list, 0, 1), replaceAll(list, 1, 2),
frequency(list, 1), reverse(list), rotate(list, 1), shuffle(list), unmodifiableList(list)
// list
var list = Arrays.asList(boxedArray);
Arrays.stream(arr).boxed().collect(Collectors.toList())
sort(), sort(Comparator.naturalOrder()), sort(Comparator.reverseOrder())
// string
String.join(", ", arr) // array to string
str.split(""), str.split(" "), str.split(", ") // string to array
str.toCharArray() // string to char array
str.chars().toArray() // string to int array
// boxing
var arr1 = Arrays.stream(arr).boxed().toArray(Integer[]::new); // int[] to Integer[]
var arr2 = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new); // int[] to String[]
var arr3 = Arrays.stream(arr).boxed().collect(Collectors.toList()); // int[] to List<Integer>
// integer sequence
var arr = IntStream.range(0, n).toArray(); // range to int array in [0, n)
var arr = IntStream.rangeClosed(1, n).toArray(); // range to int array in [1, n]
var list = IntStream.range(0, n).boxed().toList(); // range to list
var list = List.of(arr); // array to list
var list = Arrays.asList(arr); // array to list
var arr = strList.toArray(String[]::new); // List<String> to String[]
var arr = intList.stream().mapToInt(Integer::intValue).toArray(); // List<Integer> to int[]
var list = Arrays.stream(arr).boxed().sorted().collect(Collectors.toCollection(ArrayList::new)); // array to sorted list
// guava
import com.google.common.collect.*;
List<String> list = Lists.newArrayList();
List<String> list = Lists.asList(boxedArray);Examples
Python declaration/functions
# networkx
import networkx
graph = networkx.Graph()
# edges
edges = [(seattle, chicago), (seattle, san_francisco), ...]
graph.add_edges_from(edges)
# weighted edges
weighted_edges = [(seattle, chicago, 1737), (seattle, san_francisco, 678), ...]
graph.add_weighted_edges_from(weighted_edges)
# operations
networkx.bfs_layers(graph, "Boston")
networkx.minimum_spanning_tree(graph, algorithm="kruskal")
networkx.dijkstra_path(graph, "Los Angeles", "Boston")Java declaration/methods
// guava graph
import com.google.common.graph.*;
MutableGraph<Integer> graph = GraphBuilder.undirected().build();
MutableValueGraph<City, Distance> roads = ValueGraphBuilder.directed()
.incidentEdgeOrder(ElementOrder.stable())
.build();Graph algorithms
NOTE: In the following, the C++ implementations are currently only available on MSVC.
algorithm BellmanFord(G, source):
// Initialize single source
for each u in G.V:
u.distance = ∞
u.parent = NIL
source.distance = 0
for i = 0 to |G.V| - 2:
for each edge (u, v) in G.E:
// Relaxation
if v.distance > u.distance + w(u, v):
v.distance = u.distance + w(u, v)
v.parent = u
for each edge (u, v) in G.E:
if v.distance > u.distance + w(u, v):
return false
return truealgorithm BFS(G, source):
for each u in G.V:
u.color = WHITE
u.distance = ∞
u.parent = NIL
source.color = GRAY
source.distance = 0
source.parent = NIL
Queue = ∅
Queue.enqueue(source)
while Queue != ∅:
u = Queue.dequeue()
for each v in G.Adj[u]:
if v.color == WHITE:
v.color = GRAY
v.distance = u.distance + 1
v.parent = u
Queue.enqueue(v)
u.color = BLACKalgorithm DFS(G):
for each u in G.V:
u.color = WHITE
u.parent = NIL
time = 0
for each u in G.V:
if u.color == WHITE:
DFS-VISIT(G, u)
algorithm DFS-VISIT(G, u):
time = time + 1 // discovered
u.discovered = time
u.color = GRAY
for each v in G.Adj[u]:
if v.color == WHITE:
v.parent = u
DFS-VISIT(G, v)
u.color = BLACK
time = time + 1 // finished
u.finished = timealgorithm Dijkstra(G, source):
// Initialize single source
for each u in G.V:
u.distance = ∞
u.parent = NIL
source.distance = 0
Set = ∅
Queue = G.V
while Queue != ∅:
u = EXTRACT-MIN(Queue)
Set = Set ∪ {u}
for each v in G.Adj[u]:
// Relaxation
if v.distance > u.distance + w(u, v):
v.distance = u.distance + w(u, v)
v.parent = ualgorithm InitializeAdjacencyMatrix(G):
d = matrix of size |G.V| × |G.V|
for each u in G.V:
for each v in G.V:
if u == v:
d[u][v] = 0
else if (u, v) in G.E:
d[u][v] = w(u, v)
else:
d[u][v] = ∞
return d
algorithm FloydWarshall(G):
d = InitializeAdjacencyMatrix(G)
for k = 0 to |G.V| - 1:
for i = 0 to |G.V| - 1:
for j = 0 to |G.V| - 1:
dᵏ[i, j] = MIN(dᵏ⁻¹[i, j], dᵏ⁻¹[i, k] + dᵏ⁻¹[k, j])
return dalgorithm Kruskal(G, w):
Set = ∅
for each v in G.V:
MAKE-SET(v) // initialize vertice
for each edge (u, v) in G.E ordered by w(u, v), increasing:
if FIND-SET(u) != FIND-SET(v):
Set = Set ∪ {(u, v)}
UNION(u, v) // combine trees
return Setalgorithm Prim(G, root):
for each u in G.V:
u.key = ∞
u.parent = NIL
root.key = 0
Queue = G.V // queue is a min priority queue
while Queue != ∅:
u = EXTRACT-MIN(Queue)
for each v in G.Adj[u]:
if v in Queue and w(u, v) < v.key:
v.parent = u
v.key = w(u, v)Examples
NOTE: In the following, the C++ implementations are currently only available on MSVC.
(CLRS#11)
C++ declaration/methods
// map
auto map = std::unordered_map<std::string, int>{{"a", 1}, {"b", 2}};
insert({"c", 3}), emplace("d", 4), find("b"), end(), erase("a"), size(), empty()
// set
auto set = std::unordered_set{1, 2, 3, 4, 5};
insert(42), emplace(42), find(42), end(), erase(42), size(), empty()
// tuple
auto t1 = std::tuple{-1, -1};
auto t2 = std::make_tuple(-1, -1);
auto [x, y] = t1;
// transform
std::ranges::transform(nums, std::inserter(map, map.end()),
[i = 0](auto num) mutable { return std::pair{num, i++}; });Python declaration/functions
# set
number_set: set[int] = set()
add(1), update([2, 3, 4])
# dictionary
sample_dict: dict[str, int] = {'a': 1, 'b': 2, 'c': 3}
# defaultdict
sample_dict: collections.defaultdict[str, int] = collections.defaultdict(int)
sample_dict['a'] = 1
sample_dict.update({'b': 2, 'c': 3})
# counter
sample_counter: collections.Counter = collections.Counter()
sample_counter.update([1, 1, 2, 2, 3])Java declaration/methods
import java.util.*;
// map
Map<String, Integer> map = new HashMap<>();
put("a", 1), putIfAbsent("b", 2), get("a"), getOrDefault("f", 6), remove("a"), size(), isEmpty(),
keySet(), values(), entrySet(), containsKey("a"), containsValue(1), replace("a", 2), clear()
var keys = map.keySet().toArray(String[]::new);
var values = map.values().toArray(Integer[]::new);
// set
Set<Integer> set = new HashSet<>();
add(1), remove(1), size(), isEmpty(), contains(1), clear(), iterator()
var arr = set.toArray(Integer[]::new);
// enum map
Map<City, Integer> map = new EnumMap<>(City.class);
// linked hash map, linked hash set
Map<String, Integer> map = new LinkedHashMap<>();
Set<Integer> set = new LinkedHashSet<>();
// unboxing
int[] result = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(Map.Entry::getKey)
.mapToInt(Integer::parseInt)
.toArray();
// guava
import com.google.common.collect.*;
Map<String, Integer> map = Maps.newHashMap();
Set<Integer> set = Sets.newHashSet();
Map<City, Country> map = Maps.newEnumMap(City.class);
Map<String, Integer> map = Maps.newLinkedHashMap();
Set<Integer> set = Sets.newLinkedHashSet();
// guava multiset (implements Multiset<E>)
Multiset<String> multiset = HashMultiset.create();
Multiset<String> multiset = TreeMultiset.create();
Multiset<String> multiset = LinkedHashMultiset.create();
Multiset<String> multiset = ConcurrentHashMultiset.create();
Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c");
// guava multimap (implements Multimap<K, V>)
Multimap<String, Integer> multimap = ArrayListMultimap.create();
Multimap<String, Integer> multimap = HashMultimap.create();
Multimap<String, Integer> multimap = LinkedListMultimap.create();
Multimap<String, Integer> multimap = LinkedHashMultimap.create();
Multimap<String, Integer> multimap = TreeMultimap.create();
Multimap<String, Integer> multimap = ImmutableListMultimap.of("a", 1, "a", 2, "b", 3);
Multimap<String, Integer> multimap = ImmutableSetMultimap.of("a", 1, "a", 2, "b", 3);
// guava bimap (implements BiMap<K, V>, Map<K, V>)
BiMap<String, Integer> bimap = HashBiMap.create();
BiMap<String, Integer> bimap = ImmutableBiMap.of("a", 1, "b", 2);
BiMap<City, Country> bimap = EnumBiMap.create(City.class, Country.class);
BiMap<City, Integer> bimap = EnumHashBiMap.create(City.class);
// guava table (implements Table<R, C, V>)
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
Table<Vertex, Vertex, Double> weightedGraph = TreeBasedTable.create();
Table<Vertex, Vertex, Double> weightedGraph = ArrayTable.create(Arrays.asList(v1, v2), Arrays.asList(v3, v4));
Table<Vertex, Vertex, Double> weightedGraph = ImmutableTable.of(v1, v2, 4.0);Examples
A min-heap/max-heap is ideal for maintaining a collection of elements when we need to add arbitrary values and extract the smallest/largest element.
C++ declaration/methods
auto queue = std::priority_queue<int>{}; // max heap
auto queue = std::priority_queue<int, std::vector<int>, std::greater<int>>{}; // min heap
push(1), emplace(2), pop(), top(), size(), empty()Python declaration/functions
number_list: list[int] = [5, 4, 3, 2, 1]
heapq.heapify(number_list)
heapq.nlargest(3, number_list), heapq.nsmallest(3, number_list)
heapq.heappush(number_list, 6), heapq.heappop(number_list), heapq.heapreplace(number_list, 0)Java declaration/methods
import java.util.*;
Queue<Integer> queue = new PriorityQueue<>();
Queue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
add(1), peek(), poll(), remove(), size(), isEmpty(),
contains(1), clear(), iterator()
// guava
import com.google.common.collect.*;
Queue<Integer> queue = Queues.newPriorityQueue();Heap algorithms
Examples
A linked list is a data structure that consists of a sequence of elements, where each element points to the next. (CLRS#10.2)
In Python, there is no built-in type or library for LinkedList.
C++ declaration/methods
auto list = std::list{1, 2, 3}; // doubly linked list
push_front(4), emplace_front(5), push_back(6), emplace_back(7),
pop_front(), pop_back(), reverse(), sort(), insert(list.begin(), 11),
emplace(list.end(), 12), splice(list.end(), std::list{8, 9, 10})
auto list = std::forward_list{1, 2, 3}; // singly linked list
push_front(4), emplace_front(5), pop_front(), reverse(), sort()Java declaration/methods
import java.util.*;
// doubly linked list
List<Integer> list = new LinkedList<>();
add(1), addAll(List.of(2, 3, 4, 5)),
remove(0), removeFirst(), removeLast(), removeIf(x -> x % 2 == 0), subList(1, 3),
get(0), getFirst(), getLast(), size(), isEmpty(), contains(1), containsAll(List.of(1, 2, 3)),
iterator(), listIterator()
// dynamically resized array
List<Integer> list = new ArrayList<>();
add(1), addAll(List.of(2, 3, 4, 5)), remove(0), subList(1, 3),
get(0), size(), isEmpty(), contains(3), containsAll(List.of(3, 4)),
iterator(), listIterator()
// guava
import com.google.common.collect.*;
List<Integer> list = Lists.newLinkedList();
List<Integer> list = Lists.newArrayList();Examples
A queue is a data structure that implements the FIFO (first-in, first-out) policy. It has the following operations: enqueue (insert an element), dequeue (delete the least recently inserted element). (CLRS#10.1)
C++ declaration/methods
auto container = std::queue<int>{};
push(1), emplace(2), pop(), front(), back(), size(), empty()
auto container = std::deque<int>{};
push_back(1), emplace_back(2), push_front(3), emplace_front(4),
pop_back(), pop_front(), front(), back(), size(), empty()Python declaration/functions
deque: collections.deque = collections.deque([1, 2, 3, 4, 5])
deque[0], deque[-1]
append(6), appendleft(7), pop(), popleft()Java declaration/methods
import java.util.*;
Deque<Integer> deque = new ArrayDeque<>();
add(1), remove(), pop(), size(), isEmpty(), contains(1), clear(),
offerFirst(6), offerLast(7), pollFirst(), pollLast(), peekFirst(), peekLast(),
addFirst(8), addLast(9), removeFirst(), removeLast(), getFirst(), getLast(),
iterator(), descendingIterator()
var array = deque.toArray(Integer[]::new); // deque to array
var list = new ArrayList<>(deque); // deque to list
// guava
import com.google.common.collect.*;
Deque<Integer> deque = Queues.newArrayDeque();Examples
A stack is a data structure that implements the LIFO (last-in, first-out) policy. It has the following operations: push (insert an element), pop (delete the most recently inserted element). (CLRS#10.1)
C++ declaration/methods
auto stack = std::stack<int>{};
push(1), emplace(2), pop(), top(), size(), empty()Python declaration/functions
# use list type
stack: list[int] = [1, 2, 3]
stack[-1], len(stack)
append(4), pop()Java declaration/methods
import java.util.*;
Stack<Integer> stack = new Stack<>();
push(1), add(1, 2), addAll(anotherList), pop(), peek(), size(), isEmpty(),
contains(1), search(1), size(),
remove(1), removeIf(x -> x == 1), clear(),
iterator(), listIterator()
var array = stack.toArray(Integer[]::new); // stack to array
var list = new ArrayList<>(stack); // stack to listExamples
The tree is a specific type of graph. A tree is an undirected graph in which any two vertices are connected by exactly one path. It is connected without cycles.
C++ declaration/methods (binary search tree based)
// map
auto map = std::map<std::string, int>{{"a", 1}, {"b", 2}};
insert({"c", 3}), emplace("d", 4), erase("a"), find("b"), size(), empty(), equal_range("c")
// set
auto set = std::set{1, 2, 3, 4, 5};
insert(42), emplace(42), erase(42), find(42), size(), equal_range(3)Python declaration/functions (binary search tree based)
# sortedcontainers
sort_list = SortedList([1, 2, 3, 4, 5])
sort_set = SortedSet([1, 2, 3, 4, 5])
sort_dict = SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})Java declaration/methods (binary search tree based)
import java.util.*;
// tree map (based on red-black tree)
Map<Integer, Integer> map = new TreeMap<>();
Map<Integer, Integer> map = new TreeMap<>(Collections.reverseOrder());
Map<String, Integer> map = new TreeMap<>(Map.of("a", 1, "b", 2, "c", 3));
put("a", 1), putIfAbsent("b", 2), get("a"), getOrDefault("f", 6), remove("a"), size(), isEmpty(),
keySet(), values(), entrySet(), containsKey("a"), containsValue(1), replace("a", 2), clear()
firstKey(), lastKey(), lowerKey("b"), higherKey("b"), floorKey("b"), ceilingKey("b"),pollFirstEntry(), pollLastEntry(),
headMap("c"), tailMap("c"), subMap("a", "c"), descendingMap(), descendingKeySet()
// tree set (based on red-black tree)
Set<Integer> set = new TreeSet<>();
Set<Integer> set = new TreeSet<>(Collections.reverseOrder());
Set<Integer> set = new TreeSet<>(List.of(1, 2, 3, 4, 5));
add(1), remove(1), size(), isEmpty(), contains(1), clear(), iterator(), descendingIterator(),
first(), last(), lower(3), higher(3), floor(3), ceiling(3), pollFirst(), pollLast(),
headSet(3), tailSet(3), subSet(2, 4), descendingSet()
// guava
import com.google.common.collect.*;
Map<Integer, Integer> map = Maps.newTreeMap();
Set<Integer> set = Sets.newTreeSet();Properties of Trees
Balanced binary tree
Tree traversal in binary tree
Tree algorithms
Examples
(CLRS#15)
Examples
(CLRS#16)
Examples
C++ declaration/methods
std::numeric_limits<int>::min(), std::numeric_limits<float>::max(), std::numeric_limits<double>::infinity()
// cmath
std::abs(-34), std::fabs(-3.14), std::ceil(2.17), std::floor(3.14), std::min(x, -4), std::max(3.14, y),
pow(2.17, 3.14), log(7.12), sqrt(225)Python declaration/functions
float('inf'), float('-inf')
# math
math.inf, -math.inf
math.fabs(-34.5), math.ceil(2.17), math.floor(3.14), math.max(x, -3), math.min(x, 3.14),
math.pow(2.71, 3.15), math.round(3.14), math.sqrt(225)Java declaration/methods
Integer.MIN_VALUE, Float.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Boolean.TRUE
// math
Math.abs(-34.5), Math.ceil(2.17), Math.floor(3.14), Math.max(x, -3), Math.min(x, 3.14),
Math.pow(2.71, 3.15), Math.round(3.14), Math.sqrt(225)Mathematical algorithms
Examples
C++ declaration/methods
std::to_string(42), std::swap(x, y)
std::numeric_limits<int>::min(), std::numeric_limits<float>::max(), std::numeric_limits<double>::infinity()
std::abs(-34), std::fabs(-3.14), std::ceil(2.17), std::floor(3.14), std::min(x, -4), std::max(3.14, y), pow(2.17, 3.14), log(7.12), sqrt(225) // cmath
std::stoi("42"), std::stod("3.14"), std::stoi("42", nullptr, 16), std::stoi("1000010", nullptr, 2) // string -> int/double/hex/binary
std::bitset<8>(42), std::bitset<8>(3.14), std::bitset<8>(0x42), std::bitset<8>(0b1000010) // int/double/hex/binary -> bitset
std::uniform_int_distribution<int> distribution(1, 6), std::uniform_real_distribution<double> distribution(0.0, 1.0) // random
// random values
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_int_distribution distribution(1, 10); // integer in [1, 10]
const auto i = distribution(generator);
const auto d = std::generate_canonical<double, 10>(generator); // floating point number in [0, 1)Python declaration/functions
float('inf'), float('-inf'),
math.inf, -math.inf,
math.fabs(-34.5), math.ceil(2.17), math.floor(3.14), math.max(x, -3), math.min(x, 3.14),
math.pow(2.71,3.15), math.round(3.14), math.sqrt(225)
abs(-34), min(number_list), max(number_list), sum(number_list), sorted(number_list)
len(sample_string), len(number_list), len(sample_dict) # length
str(42), str(3.14), str(True) # int/float/bool -> string
int("42"), float("3.14"), bool("true") # string -> int/float/bool
int("1000010", 2), int("52", 8), int("2a", 16) # string -> binary/octal/hex
bin(42), oct(42), hex(42) # int -> binary/octal/hex
ascii('a'), chr(97), ord('a') # unicode <-> ascii code
# copy
copy.deepcopy(number_list) # deep copy
copy.copy(number_list) # shallow copy
# random
random.randrange(28) # [0, 28)
random.randrange(1, 100) # [1, 100)
random.randrange(8, 16) # [8, 16)
random.randrange(8, 16, 2) # [8, 16) with step 2
random.shuffle(number_list)
random.choice(number_list)Java declaration/methods
Integer.MIN_VALUE, Float.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Boolean.TRUE
Math.abs(-34.5), Math.ceil(2.17), Math.floor(3.14), Math.max(x, -3), Math.min(x, 3.14), Math.pow(2.71, 3.15), Math.round(3.14), Math.sqrt(225) // math
Integer.valueOf("1"), Double.valueOf("3.14"), Boolean.valueOf("true"), Float.toString(3.14f) // reference type
Integer.parseInt("42"), Double.parseDouble("3.14") // primitive type
Double.compare(x, 1.23) == 0, Integer.compare(x, 2) == 0 // comparing values
// bitwise operation
Integer.parseInt("1000010", 2), Integer.parseInt("52", 8), Integer.parseInt("2a", 16) // string -> binary/octal/hex
Integer.toBinaryString(42), Integer.toHexString(42), Integer.toOctalString(42) // int -> binary/hex/octal string
Integer.toString(num, base) // int -> string with base
Integer.bitCount(42) // number of 1-bits
Long.parseLong("1000010", 2), Long.parseLong("52", 8), Long.parseLong("2a", 16) // string -> binary/octal/hex
Long.toBinaryString(42), Long.toHexString(42), Long.toOctalString(42) // long -> binary/hex/octal string
Long.toString(num, base) // long -> string with base
Long.bitCount(42) // number of 1-bits
// bitset
import java.util.*;
new BitSet(16), set(0), set(0, 8), set(0, 8, true)
// hex digits
import java.util.*;
HexFormat hex = HexFormat.of();
byte b = 127;
String byteStr = hex.toHexDigits(b);
// random values
import java.util.Random;
var random = new Random();
var randomInt = random.nextInt(100); // [0, 100)
var randomLong = random.nextLong(); // [0, 2^48)
var randomDouble = random.nextDouble(); // [0.0, 1.0)
var randomBoolean = random.nextBoolean(); // true/falsePrimitive type algorithms
Examples
C++ declaration/methods
// map
auto map = std::map<std::string, int>{{"a", 1}, {"b", 2}};
insert({"c", 3}), emplace("d", 4), erase("a"), find("b"), size(), empty(), equal_range("c")
// set
auto set = std::set{1, 2, 3, 4, 5};
insert(42), emplace(42), erase(42), find(42), size(), equal_range(3)
// algorithm
std::ranges::find(v, 42)
std::ranges::find(v, 42)
std::ranges::find_if(v, [](auto x) { return x % 2 == 0; })
std::ranges::find_end(v, sub_v).begin() // result - v.begin()
std::ranges::binary_search(v, 42)
std::ranges::lower_bound(v, 42)
std::ranges::upper_bound(v, 42)Python declaration/functions
bisect.bisect_left(number_list, 3), bisect.bisect_right(number_list, 3), bisect.bisect(number_list, 3)Java declaration/methods
import java.util.*;
int[] array = new int[]{1, 2, 3, 4, 5};
List<Integer> arrayList = new ArrayList<>(List.of(1, 2, 3, 4, 5));
List<Integer> linkedList = new LinkedList<>(List.of(1, 2, 3, 4, 5));
Set<Integer> hashSet = new HashSet<>(List.of(1, 2, 3, 4, 5));
Set<Integer> linkedHashSet = new LinkedHashSet<>(List.of(1, 2, 3, 4, 5));
Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
// binary search
Arrays.binarySearch(array, 3) // for array
Collections.binarySearch(arrayList, 3); // for listSearch algorithms
Examples
C++ declaration/methods
std::ranges::sort(v); // introsort (quick sort + heap sort + insertion sort)
std::ranges::stable_sort(v); // merge sortPython declaration/functions
number_list: list[int] = [1, 2, 3, 4, 5]
number_list.sort() # in-place
result = sorted(number_list) # return a new list(copy)Java declaration/methods
Arrays.sort() and Collections.sort() sort the array and list in ascending order in-place.
import java.util.*;
// Arrays
Arrays.sort(arr); // dual pivot quick sort (primitive types)
// timsort (insertion sort + merge sort) (reference types)
Arrays.sort(arr, Comparator.comparingInt(String::length));
Arrays.sort(arr, Comparator.comparingInt(String::length).reversed());
// Collections
Collections.sort(list); // timsort (insertion sort + merge sort)
list.sort(Comparator.naturalOrder());
list.sort(Comparator.reverseOrder());
list.sort(Comparator.comparingInt(String::length));Sorting algorithms
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n)$ | when the input list is already sorted in the desired order (ascending or descending) |
| Worst | $O(n^2)$ | when the input list is already sorted in the reverse order of the desired sorting order |
| Average | $O(n^2)$ | when the input list is in jumbled order |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n + k)$ | when input elements are uniformly distributed and each bucket contains roughly the same number of elements |
| Worst | $O(n^2)$ | when all elements are placed into a single bucket |
| Average | $O(n)$ |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n + k)$ | when the input elements have a small range of values |
| Worst | $O(n + k)$ | when the input elements have a large range of values |
| Average | $O(n + k)$ | when the elements are distributed randomly in the array |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n log n)$ | |
| Worst | $O(n log n)$ | |
| Average | $O(n log n)$ |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n)$ | if the list is already sorted. this case has linear running time |
| Worst | $O(n^2)$ | if the list is sorted in reverse order. this case has quadratic running time |
| Average | $O(n^2)$ | this case has quadratic running time |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n log n)$ | running time of sorting for input length $n$ is $T(n)$. $T(n) = 2T(n/2) + O(n) \approx O(n log n)$ |
| Worst | $O(n log n)$ | |
| Average | $O(n log n)$ |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n log n)$ | |
| Worst | $O(n^2)$ | |
| Average | $O(n log n)$ |
| Case | Time complexity | Remarks |
|---|---|---|
| Best | $O(n^2)$ | if the list is already sorted |
| Worst | $O(n^2)$ | when sorted in ascending order, if you want to sort in descending order (vice versa) |
| Average | $O(n^2)$ | when the input list is in jumbled order |
Examples
C++ declaration/methods
auto str = std::string{"hello"};
append("_world"), push_back('!'), pop_back(), insert(5, "_world"), substr(0, 5), compare("hello_world")
// string stream
std::stringstream ss(str);
good(), bad(), fail(), eof(), clear(), operator<<(), operator>>()Python declaration/functions
hello_world: str = 'hello world'
len(hello_world), count('l'), find('world'), rfind('world'), index('world'), rindex('world'),
strip(), split(' '), replace(' ', ''), startswith('hello'), endswith('world'),
lower(), upper(), capitalize(), title(), swapcase()
# string concatenation
s = s[6:]
s += 'abc'Java declaration/methods
var str = "Hello World";
length(), charAt(0), substring(0, 5), indexOf("Java"), lastIndexOf("Java"),
contains("Java"), startsWith("Hello"), endsWith("World"),
compareTo("Hello Java"), compareToIgnoreCase("hello world"),
concat("!"), replace("World", "Java"), toUpperCase(), toLowerCase(), trim(),
toCharArray(), chars()
// static methods
String.format("%s %s", "Hello", "World")
String.join(" ", "Hello", "World")
String.valueOf(123)
// string builder
var sb = new StringBuilder();
append("!"), insert(0, "Hello"), delete(0, 5), deleteCharAt(0),
length(), charAt(0), indexOf("Java"), lastIndexOf("Java"),
reverse(), replace(0, 5, "World"), substring(0, 5), toString(),
subSequence(0, 5), chars()
// character
var ch = new Character('a');
Character.isDigit('0'), Character.isLetter('a'), Character.isLetterOrDigit('a'), Character.isAlphabetic('a'),
Character.isLowerCase('a'), Character.isUpperCase('A'), Character.toLowerCase('A'), Character.toUpperCase('a'),
Character.isWhitespace(' ')
// list/stack/deque to string
var str = collection.stream()
.map(String::valueOf)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);String algorithms
Examples
| Back | FazBrowse Home | New Git URL |