Returns the aliquot sum of the provided number Source: TheAlgorithms/TypeScript (MIT)
/**
* @function aliquotSum
* @description Returns the aliquot sum of the provided number
* @summary The aliquot sum of a number n is the sum of all the proper divisors
* of n apart from n itself.
* So, for example, the number 6 has three proper divisors, 1, 2, 3
* Hence its aliquot sum is 1 + 2 + 3 = 6
* For all prime numbers, the aliquot sum is 1, and for 1, the aliquot sum is 0
* @param {number} num The input number
* @return {number} The aliquot sum of the number
* @see [Wikipedia](https://en.wikipedia.org/wiki/Aliquot_sum)
* @example aliquotSum(18) = 21
* @example aliquotSum(15...
Check if the provided number is an Armstrong number or not. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function armstrongNumber
* @description Check if the provided number is an Armstrong number or not.
* @summary Armstrong numbers are numbers, the sum of whose digits each raised
* to the power of the number of digits is equal to the number itself.
* For example:
* 370 is an Armstrong number since 3^3 + 7^3 + 0^3 = 370
* (These numbers are also known as Narcissistic numbers, and Pluperfect numbers)
* @param {number} num The number you want to check for
* @return {boolean} Whether the input number is an Armstrong number
* @see [Wikipedia](https://en.wikipedia.org/wiki/Armstrong_...
Compute the shortest path from a source node to all other nodes. If there is negative weight cycle, returns undefined. The input graph is in adjacency list form. It is a multidimensional array of edges. graph[i] holds the edges for the i'th node. Each edge is a 2-tuple where the 0'th item is the destination node, and the 1'th item is the edge weight. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function bellmanFord
* @description Compute the shortest path from a source node to all other nodes. If there is negative weight cycle, returns undefined. The input graph is in adjacency list form. It is a multidimensional array of edges. graph[i] holds the edges for the i'th node. Each edge is a 2-tuple where the 0'th item is the destination node, and the 1'th item is the edge weight.
* @Complexity_Analysis
* Time complexity: O(E*V)
* Space Complexity: O(V)
* @param {[number, number][][]} graph - The graph in adjacency list form
* @param {number} start - The source node
* @retu...
binary search algorithm (iterative & recursive implementations) for a sorted array. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function binarySearch
* @description binary search algorithm (iterative & recursive implementations) for a sorted array.
*
* The algorithm searches for a specific value in a sorted array in logarithmic time.
* It repeatedly halves the portion of the list that could contain the item,
* until you've narrowed down the possible indices to just one.
*
* @param {number[]} array - sorted list of numbers
* @param {number} target - target number to search for
* @return {number} - index of the target number in the list, or null if not found
* @see [BinarySearch](https://www.geeksforgee...
Calculate the binomial coefficient (n choose k) of two input numbers Source: TheAlgorithms/TypeScript (MIT)
/**
* @function binomialCoefficient
* @description Calculate the binomial coefficient (n choose k) of two input numbers
* using the factorial-based formula: C(n, k) = n! / (k! * (n-k)!)
* @param {number} n - the total number of items
* @param {number} k - the number of items to be chosen
* @return {number} - Binomial coefficient (n choose k)
* @see https://en.wikipedia.org/wiki/Binomial_coefficient
* @example binomialCoefficient(5, 2) = 10
* @example binomialCoefficient(10, 3) = 120
* @example binomialCoefficient(6, 0) = 1
* @Complexity_Analysis
* Time complexity - O(n)
* Space co...
Determines if a given graph is bipartite. Source: TheAlgorithms/TypeScript (MIT)
const dfs = (
graph: number[][],
colors: number[],
node: number,
color: number
): boolean => {
if (colors[node] !== 0) {
return colors[node] === color
}
colors[node] = color
for (const neighbor of graph[node]) {
if (!dfs(graph, colors, neighbor, -color)) {
return false
}
}
return true
}
/**
* Determines if a given graph is bipartite.
*
* A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
* U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from
* V to U
*
* @param {number[][]} ...
Bubble sort algorithm is simple and easy. In bubble sort every pair of adjacent value is compared and swap if the first value is greater than the second one. By this with every iteration the greatest value goes to the right side making it ascending order.This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function bubbleSort
* @description Bubble sort algorithm is simple and easy. In bubble sort every pair of adjacent value is compared and swap if the first value is greater than the second one. By this with every iteration the greatest value goes to the right side making it ascending order.This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
* @Complexity_Analysis
* Space complexity - O(1)
* Time complexity
* Best case - O(n^2)
* The best case occurs when an array is already sorted.
* Wo...
Capitalize the first letter of a string
export function capitalize(str: string): string {
if (!str) return str;
return str.charAt(0).toUpperCase() + str.slice(1);
}
Given a set of categories of coins C and an amount of money S, the goal is: Source: TheAlgorithms/TypeScript (MIT)
export interface CoinChange {
minCoins: number
coins: number[]
}
/**
* Given a set of categories of coins C and an amount of money S, the goal is:
* to give change for S but to use a minimum number of coins. Suppose each category of coin has an infinite number of pieces.
* @param money - amon of money.
* @param coins - The coins that are available.
* @returns CoinChange, the minimum number of coins, and which coins are selected
*/
export const coinChange = (money: number, coins: number[]): CoinChange => {
const minCoins: number[] = Array(money + 1).fill(Infinity)
const lastCoin:...
@author dev-madhurendra Source: TheAlgorithms/TypeScript (MIT)
/**
* @author dev-madhurendra
* Counting sort is an algorithm for sorting a collection
* of objects according to keys that are small integers.
* @see https://en.wikipedia.org/wiki/Counting_sort
* @example
* const array = [3, 0, 2, 5, 4, 1]
* countingSort(array, 0, 5)
*/
export const countingSort = (inputArr: number[], min: number, max: number) => {
const sortedArr = []
const count = new Array(max - min + 1).fill(0)
for (const element of inputArr) count[element - min]++
count[0] -= 1
for (let i = 1; i < count.length; i++) count[i] += count[i - 1]
for (let i = inputArr....
Cycle sort is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm. It is based on the idea that the permutation to be sorted can be factored into cycles, which can individually be rotated to give a sorted result. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function cycleSort
* @description Cycle sort is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm. It is based on the idea that the permutation to be sorted can be factored into cycles, which can individually be rotated to give a sorted result.
* @param {number[]}array - The input array
* @return {number[]} - The sorted array.
* @see [CycleSort] https://en.wikipedia.org/wiki/Cycle_sort
* @example cycleSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, ...
@description counts the positive integers up to a given integer n that are relatively prime to n. Source: TheAlgorithms/TypeScript (MIT)
/**
* @description counts the positive integers up to a given integer n that are relatively prime to n.
* @param {number} n - A natural number.
* @return {number} - euler's totient.
* @see https://en.wikipedia.org/wiki/Euler%27s_totient_function
* @example phi(4) = 2
* @example phi(5) = 4
*/
export const phi = (n: number): number => {
let result: number = n
for (let i = 2; i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) n = n / i
result -= Math.floor(result / i)
}
}
if (n > 1) result -= Math.floor(result / n)
return result
}
@description Exponential search algorithm for a sorted array. Source: TheAlgorithms/TypeScript (MIT)
/**
* @description Exponential search algorithm for a sorted array.
*
* The algorithm searches for a specific value in a sorted array by first finding a range
* where the value may be present and then performing a binary search within that range.
*
* Compared with binary search, exponential search can be more convenient and advantageous
* in cases where the element to be searched is closer to the beginning of the array,
* thus avoiding several comparisons that would make the search more verbose.
*
* @param {number[]} array - sorted list of numbers
* @param {number} x - target number...
A function to get nth Fibonacci number. Source: TheAlgorithms/TypeScript (MIT)
/**
* A function to get nth Fibonacci number.
*
* Time Complexity: linear (O(n))
*
* @param number The index of the number in the Fibonacci sequence.
* @return The Fibonacci number on the nth index in the sequence.
*
* @example nthFibonacci(4) => 3 | nthFibonacci(6) => 8
* @see https://en.m.wikipedia.org/wiki/Fibonacci_number
* @author MohdFaisalBidda <https://github.com/MohdFaisalBidda>
*/
function* generateFibonacci(): Generator<number> {
let a = 0
let b = 1
while (true) {
yield a
const c = a + b
a = b
b = c
}
}
export const nthFibonacci = (number: number)...
@description Fibonacci search algorithm for a sorted array. Source: TheAlgorithms/TypeScript (MIT)
/**
* @description Fibonacci search algorithm for a sorted array.
*
* The algorithm searches for a specific value in a sorted array using Fibonacci numbers
* to divide the array into smaller subarrays. This algorithm is useful for large arrays where
* the cost of accessing elements is high.
*
* @param {number[]} array - sorted list of numbers
* @param {number} target - target number to search for
* @return {number | null} - index of the target number in the list, or null if not found
* @see [FibonacciSearch](https://www.geeksforgeeks.org/fibonacci-search/)
* @example fibonacciSearch...
Compute the shortest path for all pairs of nodes for a graph without negative weight edges. The input graph is a adjacency matrix, where graph[i][j] holds the weight of edges a->b. If the edge does not exist, the value in the matrix is Infinity. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function floydWarshall
* @description Compute the shortest path for all pairs of nodes for a graph without negative weight edges. The input graph is a adjacency matrix, where graph[i][j] holds the weight of edges a->b. If the edge does not exist, the value in the matrix is Infinity.
* @Complexity_Analysis
* Time complexity: O(V^3)
* Space Complexity: O(V^2). This space is required to hold the result
* @param {number[][]} graph - The graph in adjacency matrix form
* @return {number[][]} - A matrix holding the shortest path for each pair of nodes. matrix[i][j] holds the distance of...
Solves a system of linear equations using Gaussian Elimination with partial pivoting. Source: TheAlgorithms/TypeScript (MIT)
export function gaussianElimination(matrix: number[][]): number[]
/**
* Solves a system of linear equations using Gaussian Elimination with partial pivoting.
*
* @param {number[][]} matrix - The augmented matrix representing the system of equations.
* @returns {number[]} An array representing the solutions to the equations.
*/
export function gaussianElimination(matrix: number[][]): number[] {
const result: number[] = new Array(matrix.length)
function partialPivot(): void {
for (let row = 0; row < matrix.length; row++) {
let pivotRow = row
for (let column = row + 1; column < matrix.length; column++) {
if (Math.abs(matrix[co...
Gnome sort is a sort algorithm that moving an element to its proper place is accomplished by a series of swap Source: TheAlgorithms/TypeScript (MIT)
/**
* @function GnomeSort
* @description Gnome sort is a sort algorithm that moving an element to its proper place is accomplished by a series of swap
* @param {number[]} arr - The input array
* @return {number[]} - The sorted array.
* @see [GnomeSort] https://en.wikipedia.org/wiki/Gnome_sort
* @example gnomeSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
*/
export const gnomeSort = (arr: number[]): number[] => {
if (arr.length <= 1) {
return arr
}
let i: number = 1
while (i < arr.length) {
if (arr[i - 1] <= arr[i]) {
i++ //increment index if sub-array[0:i] alread...
is a comparison-based sorting algorithm that uses a binary heap data structure to repeatedly select and remove the maximum (for max-heap) or minimum (for min-heap) element and place it at the end of the sorted array. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function heapsort
* @description is a comparison-based sorting algorithm that uses a binary heap data structure to repeatedly select and remove the maximum (for max-heap) or minimum (for min-heap) element and place it at the end of the sorted array.
* @see [Heap Sort](https://www.geeksforgeeks.org/heap-sort/)
* @example MergeSort([7, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 7]
* @Complexity_Analysis
* Space complexity - O(1)
* Time complexity
* Best case - O(nlogn)
* Worst case - O(nlogn)
* Average case - O(nlogn)
*/
// Function to perform the Heap Sort
expor...
simple sortion algorithm for a small number of elements. It compares the `key` element with the previous elements. If the previous elements are greater than the `key` element, then you move the previous element to the next position. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function insertionSort
* @description simple sortion algorithm for a small number of elements. It compares the `key` element with the previous elements. If the previous elements are greater than the `key` element, then you move the previous element to the next position.
* @param {number[]} num - The input array
* @return {number[]} - The sorted array.
* @see [Insertion Sort](https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c#insertion-sort)
* @example insertionSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
*/
export const insertionSo...
Interpolation search is an algorithm for searching for a Source: TheAlgorithms/TypeScript (MIT)
/**
* @function interpolationSearch
* @description Interpolation search is an algorithm for searching for a
* key in an array that has been ordered by numerical values assigned
* to the keys (key values)
* @param {number[]} array - list of numbers
* @param {number} target - target number to search for
* @return {number} - index of the target number in the list, or -1 if not found
* @see https://en.wikipedia.org/wiki/Interpolation_search
* @example interpolationSearch([1, 3, 5, 7, 9, 11], 1) => 0
*/
export const interpolationSearch = (
array: number[],
target: number
): number =...
Validate if a string is a valid email address
export function isEmail(str: string): boolean {
const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
return emailRegex.test(str);
}
The juggler sequence is a integer sequence that starts with an positive integer a and the subsequent terms are Source: TheAlgorithms/TypeScript (MIT)
/**
* The juggler sequence is a integer sequence that starts with an positive integer a and the subsequent terms are
* described as following:
* if a_k is even:
* a_k+1 = floor(sqrt(a_k))
* else:
* a_k+1 = floor(sqrt(a_k^3))
*
* Time Complexity: linear (O(n))
*
* @param a The number to start with
* @param n The index of the searched number in the sequence.
* @returns The number at index n in the sequence.
* @see https://en.wikipedia.org/wiki/Juggler_sequence
*/
export const jugglerSequence = (a: number, n: number) => {
let k: number = a
for (let i: number = 0; i < n; i++)...
Jump search algorithm for a sorted array. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function jumpSearch
* @description Jump search algorithm for a sorted array.
*
* Jump search is a searching algorithm for sorted arrays that checks elements
* by jumping ahead by fixed steps. The optimal step size is the square root of the array length.
*
* The algorithm works as follows:
* 1.Start from the first element and jump by step size until finding an element that is greater than or equal to the target value.
* 2.Go back one step and perform a linear search from there until finding the target value or reaching the end of the subarray.
* 3.If the target value is found, ...
Solves the 0-1 Knapsack Problem. Source: TheAlgorithms/TypeScript (MIT)
/**
* Solves the 0-1 Knapsack Problem.
* @param capacity Knapsack capacity
* @param weights Array of item weights
* @param values Array of item values
* @returns Maximum value subset such that sum of the weights of this subset is smaller than or equal to capacity
* @throws If weights and values arrays have different lengths
* @see [Knapsack](https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/)
* @example knapsack(3, [3, 4, 5], [30, 50, 60]) // Output: 90
*/
export const knapsack = (
capacity: number,
weights: number[],
values: number[]
): number => {
if (weights.length ...
Given a graph, find the strongly connected components(SCC). A set of nodes form a SCC if there is a path between all pairs of points within that set. Source: TheAlgorithms/TypeScript (MIT)
// Compute the node priorities, which will be used to determine the order in which we perform transposed DFS.
const getNodePriorities = (
graph: number[][],
visited: boolean[],
stack: number[],
node: number
) => {
if (visited[node]) {
return
}
visited[node] = true
for (const dest of graph[node]) {
getNodePriorities(graph, visited, stack, dest)
}
// Nodes that end their DFS earlier are pushed onto the stack first and have lower priority.
stack.push(node)
}
// Return the transpose of graph. The tranpose of a directed graph is a graph where each of the edges are fl...
Find the Longest Common Subsequence (LCS) of two strings. Source: TheAlgorithms/TypeScript (MIT)
/**
* Find the Longest Common Subsequence (LCS) of two strings.
* @param text1 - The first input string.
* @param text2 - The second input string.
* @returns The longest common subsequence as a string.
*/
export const longestCommonSubsequence = (
text1: string,
text2: string
): string => {
const m = text1.length
const n = text2.length
// Create a 2D array to store the lengths of LCS
const dp: number[][] = Array.from({ length: m + 1 }, () =>
Array(n + 1).fill(0)
)
// Fill in the DP table
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (te...
linear search is the simplest search possible in a array Source: TheAlgorithms/TypeScript (MIT)
/**
* @function linearSearch
* @description linear search is the simplest search possible in a array
* it has a linear cost, if the value is present in the array, then the index of the first occurence will be returned
* if it's not present, the return it will be -1
* @param {number[]} array - list of numbers
* @param {number} target - target number to search for
* @return {number} - index of the target number in the list, or -1 if not found
* @see https://en.wikipedia.org/wiki/Linear_search\\
* @example linearSearch([1,2,3,5], 3) => 2
* @example linearSearch([1,5,6], 2) => -1
*/
e...
Multiply a matrix with either another matrix, a vector or a scalar Source: TheAlgorithms/TypeScript (MIT)
/**
* @function matrixMultiplication
* @description Multiply a matrix with either another matrix, a vector or a scalar
* @param {Number[][]} matA - An array of an array of numbers
* @param {Number[][] | Number[] | Number} b - Either an array of an array of numbers, an array of numbers, or a number
* @return {Number[][] | Number[]} - Either an array of an array of numbers, or an array of numbers
* @example matrixMultiplication([[1, 2], [3, 4]], [[1, 2], [3, 4]]) = [[7, 10], [15, 22]]
* @example GreatestCommonFactor([[1, 2], [3, 4]], 2) = [[2, 4], [6, 8]]
* @example GreatestCommonFactor(...
keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Source: TheAlgorithms/TypeScript (MIT)
export function mergeSort(array: number[]): number[]
/**
* @function mergeSort
* @description keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted.
* @see [Merge Sort](https://www.javatpoint.com/merge-sort)
* @example MergeSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
* @Complexity_Analysis
* Space complexity - O(n)
* Time complexity
* Best case - O(nlogn)
* Worst case - O(nlogn)
* Average case - O(nlogn)
*
* Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation.
* T(n...
Pascal's Triangle is an array of binomial coefficients. It can be used for unwrapping terms like Source: TheAlgorithms/TypeScript (MIT)
/**
* Pascal's Triangle is an array of binomial coefficients. It can be used for unwrapping terms like
* (a + b)^5.
* To construct Pascal's Triangle you add the numbers above the child entry together. Here are the first five rows:
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
*
* Time Complexity: quadratic (O(n^2)).
*
* @param n The exponent / The index of the searched row.
* @returns The nth row of Pascal's Triangle
* @see https://en.wikipedia.org/wiki/Pascal's_triangle
*/
export const pascalsTriangle = (n: number): number[] => {
const arr: number[][] = []
for (let i: n...
@description Get exponenets of each prime number in factorization of a number n Source: TheAlgorithms/TypeScript (MIT)
/**
* @description Get exponenets of each prime number in factorization of a number n
* @param {number} n - A natural number.
* @return {Map<number, number>} - factorization of number n.
* @see https://en.wikipedia.org/wiki/Integer_factorization
* @example factorize(4) = Map {2 => 2}
* @example factorize(5) = Map {5 => 1}
*/
export const factorize = (n: number): Map<number, number> => {
const result: Map<number, number> = new Map()
for (let i = 2; i * i <= n; i++) {
while (n % i == 0) {
let occurence = result.get(i)
if (!occurence) occurence = 0
result.set(i, ...
Implementation of the Sieve of Eratosthenes algorithm. Source: TheAlgorithms/TypeScript (MIT)
export function sieveOfEratosthenes(limit: number): number[]
/**
* Implementation of the Sieve of Eratosthenes algorithm.
*
* @param limit An integer _n_ > 1
* @returns All prime numbers from 2 through {@link limit}
*
* @see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
*/
export function sieveOfEratosthenes(limit: number): number[] {
if (!Number.isInteger(limit) || limit <= 1) {
throw new Error('limit should be an integer greater than 1')
}
const maybePrime: boolean[] = new Array(limit + 1).fill(true)
for (let i = 2; i * i <= limit; i++) {
if (!maybePrime[i]) continue
for (let j = i * i; j <= limit; j += i) {
may...
is an algorithm based on the QuickSort approach that selects the kth smallest element from an array Source: TheAlgorithms/TypeScript (MIT)
/**
* @function QuickSelect
* @description is an algorithm based on the QuickSort approach that selects the kth smallest element from an array
* @param {number[]} array - The array from which to select the element
* @param {number} k - The index representing the kth smallest element to find
* @param {number} left - The left boundary of the array or subarray to consider (default: 0)
* @param {number} right - The right boundary of the array or subarray to consider (default: array.length - 1)
* @returns {number} - The kth smallest element from the array
* @throws {Error} - If k is out of ...
is an algorithm based on divide and conquer approach in which an array is split into sub-arrays and these sub arrays are recursively sorted to get final array Source: TheAlgorithms/TypeScript (MIT)
/**
* @function quickSort
* @description is an algorithm based on divide and conquer approach in which an array is split into sub-arrays and these sub arrays are recursively sorted to get final array
* @see [Quick Sort](https://www.javatpoint.com/quick-sort)
* @example QuickSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
*/
export const partition = (
array: number[],
left: number = 0,
right: number = array.length - 1
) => {
const pivotIndex = choosePivot(left, right)
const pivot = array[pivotIndex]
;[array[pivotIndex], array[right]] = [array[right], array[pivotIndex]]
let i =...
Selection sort algorithm is simple and easy. In selection sort the smallest value is selected from the unsorted part and placed at the beginning. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function selectionSort
* @description Selection sort algorithm is simple and easy. In selection sort the smallest value is selected from the unsorted part and placed at the beginning. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
* @Complexity_Analysis
* Space complexity - O(1)
* Time complexity
* Best case - O(n^2)
* The best case occurs when an array is already sorted.
* Worst case - O(n^2)
* The worst case occurs when an array is reverse sorted.
* ...
Sentinel search algorithm for array. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function sentinelSearch
* @description Sentinel search algorithm for array.
*
* Sentinel linear search is a variation of the standard linear search algorithm used to
* find a target value in an array or list. The basic idea behind this algorithm is to add a
* sentinel value at the end of the array which is equal to the target value we are looking for.
* This helps to avoid checking the array boundary condition during each iteration of the loop,
* as the sentinel value acts as a stopper for the loop.
*
* @param {number[]} array - sorted list of numbers
* @param {number} target...
Shell sort algorithm is the optimization for insertion sort algorithm. Source: TheAlgorithms/TypeScript (MIT)
export function shellSort<T>(arr: T[]): T[]
/**
* @function shellSort
* @description Shell sort algorithm is the optimization for insertion sort algorithm.
* @Complexity_Analysis
* Space complexity - O(1)
* Time complexity
* Best case - Ω(n log(n))
* Worst case - O(n^2)
* Average case - O(n log(n)^2)
*
* @param {T[]} arr - The input array
* @return {T[]} - The sorted array.
* @see [Shell Sort] (https://www.geeksforgeeks.org/shellsort/)
* @example shellSort([4, 1, 8, 10, 3, 2, 5, 0, 7, 6, 9]) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*/
export function shellSort<T>(arr: T[]): T[] {
// start with the bigg...
Find the prime numbers between 2 and n Source: TheAlgorithms/TypeScript (MIT)
export function sieveOfEratosthenes(n: number): number[]
/**
* @function sieveOfEratosthenes
* @description Find the prime numbers between 2 and n
* @param {number} n - numbers set the limit that the algorithm needs to look to find the primes
* @return {number[]} - List of prime numbers
* @see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\\
* @example sieveOfEratosthenes(5) = [2,3,5]
* @example sieveOfEratosthenes(10) = [2,3,5,7]
*/
export function sieveOfEratosthenes(n: number): number[] {
if (n < 0 || !Number.isInteger(n)) {
throw new Error('Only natural numbers are supported')
}
const numbers = new Array<boolean>(n + 1).f...
Convert a string to a URL-friendly slug
export function slugify(str: string): string {
return str
.toLowerCase()
.trim()
.replace(/[^\\w\\s-]/g, "")
.replace(/\\s+/g, "-")
.replace(/-+/g, "-");
}
Finding the square root of a number using Newton's method. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function squareRoot
* @description Finding the square root of a number using Newton's method.
* @param {number} num - A number.
* @param {number} precision - Precision of square root, 1e-15 by default.
* @returns {number} - Square root of the given number.
* @see https://www.geeksforgeeks.org/find-root-of-a-number-using-newtons-method/
* @example SquareRoot(36) = 6
* @example SquareRoot(50) = 7.0710678118654755
*/
export const squareRoot = (num: number, precision: number = 1e-15): number => {
if (num < 0) throw new Error('number must be non-negative number')
if (num === 0)...
Sum all numbers in an array
export function sumArray(arr: number[]): number {
return arr.reduce((sum, n) => sum + n, 0);
}
@author : dev-madhurendra<https://github.com/dev-madhurendra> Source: TheAlgorithms/TypeScript (MIT)
/**
* @author : dev-madhurendra<https://github.com/dev-madhurendra>
* @description
* Swap Sort is an algorithm to find the number of swaps required to sort an array.
* @param {number[]} inputArr - Array of numbers
* @return {number} - Number of swaps required to sort the array.
* @see <https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/>
*/
export const minSwapsToSort = (inputArr: number[]): number => {
const sortedArray = inputArr.slice()
sortedArray.sort()
const indexMap = new Map()
for (let i = 0; i < inputArr.length; i++) indexMap.set(inputArr[i], i)...
Given a graph, find the strongly connected components(SCC) in reverse topological order. A set of nodes form a SCC if there is a path between all pairs of points within that set. Source: TheAlgorithms/TypeScript (MIT)
/**
* @function tarjan
* @description Given a graph, find the strongly connected components(SCC) in reverse topological order. A set of nodes form a SCC if there is a path between all pairs of points within that set.
* @Complexity_Analysis
* Time complexity: O(V + E). We perform a DFS of (V + E)
* Space Complexity: O(V). We hold numerous structures all of which at worst holds O(V) nodes.
* @param {[number, number][][]} graph - The graph in adjacency list form
* @return {number[][]} - An array of SCCs, where an SCC is an array with the indices of each node within that SCC. The order of S...
@generator Source: TheAlgorithms/TypeScript (MIT)
/**
* @generator
* @description Generates ugly numbers
* @summary Ugly numbers are natural numbers whose only prime factors are 2, 3 and 5.
* They can be represented in the form 2^a * 3^b * 5*c. By convention, 1 is also considered to be
* an ugly number.
* The first few terms of the sequence are: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20...
*
* For the provided n, the nth ugly number shall be computed.
* @see [GeeksForGeeks](https://www.geeksforgeeks.org/ugly-numbers/)
*/
function* uglyNumbers(): Generator<number, void, unknown> {
yield 1
let idx2 = 0,
idx3 = 0,
idx...
Calculate the day of the week for any Julian or Gregorian calendar date. Source: TheAlgorithms/TypeScript (MIT)
export enum Calendar {
Gregorian,
Julian
}
/**
* @function getWeekday
* @description Calculate the day of the week for any Julian or Gregorian calendar date.
* @param {number} year - Year with century.
* @param {number} month - Month of the year (1-12).
* @param {number} day - Day of the month (1-31).
* @return {number} Day of the week, where 0 represents Sunday.
* @see https://en.wikipedia.org/wiki/Zeller's_congruence
* @example getWeekday(2000, 1, 1) = 6
* @example getWeekday(1500, 1, 1, Calendar.Julian) = 3
*/
export const getWeekday = (
year: number,
month: number,
day...