### Install Project Dependencies Source: https://github.com/trekhleb/javascript-algorithms/blob/master/README.md Run this command in the root directory to install all necessary npm packages for the project. ```bash npm install ``` -------------------------------- ### Z Algorithm Example 1 Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/string/z-algorithm/README.md Example of Z array computation for a given string. ```text Index 0 1 2 3 4 5 6 7 8 9 10 11 Text a a b c a a b x a a a z Z values X 1 0 0 3 1 0 0 2 2 1 0 ``` -------------------------------- ### Combination Sum Example 1 Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/sets/combination-sum/README.md Example input and expected output for the Combination Sum problem with candidates [2,3,6,7] and target 7. ```text Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,2,3] ] ``` -------------------------------- ### Combination Sum Example 2 Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/sets/combination-sum/README.md Example input and expected output for the Combination Sum problem with candidates [2,3,5] and target 8. ```text Input: candidates = [2,3,5], target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ] ``` -------------------------------- ### Complex Number Division Example (Step-by-step) Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/complex-number/README.md Step-by-step example of dividing complex numbers by multiplying the numerator and denominator by the conjugate of the denominator. ```text (2 + 3i) * (4 + 5i) 8 + 10i + 12i + 15i^2 = ------------------- = ---------------------- (4 - 5i) * (4 + 5i) 16 + 20i - 20i - 25i^2 ``` ```text 8 + 10i + 12i - 15 -7 + 22i -7 22 = ------------------- = -------- = -- + -- * i 16 + 20i - 20i + 25 41 41 41 ``` -------------------------------- ### Z Algorithm Example 2 Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/string/z-algorithm/README.md Example of Z array computation for a string of repeating characters. ```text str = a a a a a a Z[] = x 5 4 3 2 1 ``` -------------------------------- ### Complex Number Multiplication Example (FOIL) Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/complex-number/README.md Example demonstrating complex number multiplication using the FOIL method. ```text (3 + 2i)(1 + 7i) = 3*1 + 3*7i + 2i*1+ 2i*7i = 3 + 21i + 2i + 14i^2 = 3 + 21i + 2i - 14 (because i^2 = -1) = -11 + 23i ``` -------------------------------- ### Complex Number Addition Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/complex-number/README.md Example demonstrating the addition of two complex numbers: (3 + 5i) + (4 - 3i). ```text (3 + 5i) + (4 - 3i) = (3 + 4) + (5 - 3)i = 7 + 2i ``` -------------------------------- ### Z Algorithm Example 3 Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/string/z-algorithm/README.md Example of Z array computation for a string with mixed characters. ```text str = a a b a a c d Z[] = x 1 0 2 1 0 0 ``` -------------------------------- ### Dynamic Programming Matrix Example (3x2 Grid) Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/unique-paths/README.md Visualizes the dynamic programming matrix for a 3x2 grid, showing the number of unique paths to each cell. ```text | | 0 | 1 | 1 | |:---:|:---:|:---:|:---:| |**0**| 0 | 1 | 1 | |**1**| 1 | 2 | 3 | ``` -------------------------------- ### Z Algorithm Example 4 Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/string/z-algorithm/README.md Example of Z array computation for a string with alternating patterns. ```text str = a b a b a b a b Z[] = x 0 6 0 4 0 2 0 ``` -------------------------------- ### Example 1: Trapping Rain Water Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/rain-terraces/README.md Demonstrates trapping water with a simple input array [2, 0, 2]. ```plaintext Input: arr[] = [2, 0, 2] Output: 2 ``` -------------------------------- ### Complex Number Multiplication Example (Simplified) Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/complex-number/README.md Example demonstrating complex number multiplication using the simplified formula. ```text (3 + 2i)(1 + 7i) = (3*1 - 2*7) + (3*7 + 2*1)i = -11 + 23i ``` -------------------------------- ### Complex Number Subtraction Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/complex-number/README.md Example demonstrating the subtraction of two complex numbers: (3 + 5i) - (4 - 3i). ```text (3 + 5i) - (4 - 3i) = (3 - 4) + (5 + 3)i = -1 + 8i ``` -------------------------------- ### N-Queens Output Matrix Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/n-queens/README.md Represents a solution to the 4-Queens problem as a binary matrix, where 1 indicates a queen's position. ```plaintext { 0, 1, 0, 0} { 0, 0, 0, 1} { 1, 0, 0, 0} { 0, 0, 1, 0} ``` -------------------------------- ### Combination Sum Decision Tree Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/sets/combination-sum/README.md Illustrates the decision tree for the Combination Sum problem with candidates [2, 3] and target 6, showing the recursive backtracking process. ```text 0 / \ +2 +3 / \ \ +2 +3 +3 / \ / \ \ +2 ✘ ✘ ✘ ✓ / \ ✓ ✘ ``` -------------------------------- ### Run Tests by Name Source: https://github.com/trekhleb/javascript-algorithms/blob/master/README.md Use this command to run specific tests by providing a name or pattern. For example, to run tests related to 'LinkedList'. ```bash npm test -- 'LinkedList' ``` -------------------------------- ### Example of Repeating Items by Weight Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/statistics/weighted-random/README.md This snippet demonstrates the straightforward approach of repeating items based on their weights to create a list from which a random item can be picked. This method can be memory-intensive for large weights. ```javascript const items = [ '🍌', '🍎', '🥕' ]; const weights = [ 3, 7, 1 ]; // Repeating the items based on weights. const weightedItems = [ '🍌', '🍌', '🍌', '🍎', '🍎', '🍎', '🍎', '🍎', '🍎', '🍎', '🥕', ]; // And now just pick the random item from weightedItems array. ``` -------------------------------- ### Example 2: Trapping Rain Water Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/rain-terraces/README.md Illustrates trapping water with a more complex input array [3, 0, 0, 2, 0, 4]. ```plaintext Input: arr[] = [3, 0, 0, 2, 0, 4] Output: 10 ``` -------------------------------- ### Convert Bit Array to Floating-Point Number Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/binary-floating-point/README.md This example demonstrates how to convert an array of bits into a floating-point number. It's an artificial example designed to illustrate the conversion process based on the IEEE 754 standard. ```javascript import { bitsToFloat } from './bitsToFloat'; // Example usage: const bits = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // Represents +1.0 in half-precision const floatNumber = bitsToFloat(bits); console.log(floatNumber); // Output: 1 ``` -------------------------------- ### JavaScript ImageData Extraction Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/image-processing/seam-carving/README.md Demonstrates how to extract ImageData from an HTML canvas context, which is required as input for the seam carving algorithm. ```javascript const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, imgWidth, imgHeight); ``` -------------------------------- ### Hill Cipher Encryption Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/cryptography/hill-cipher/README.md Demonstrates the encryption of a message block using a 3x3 key matrix and modular arithmetic. ```plaintext | 6 24 1 | | 13 16 10 | | 20 17 15 | ``` ```plaintext | 0 | | 2 | | 19 | ``` ```plaintext | 6 24 1 | | 0 | | 67 | | 15 | | 13 16 10 | | 2 | = | 222 | ≡ | 14 | (mod 26) | 20 17 15 | | 19 | | 319 | | 7 | ``` ```plaintext | 2 | | 0 | | 19 | ``` ```plaintext | 6 24 1 | | 2 | | 31 | | 5 | | 13 16 10 | | 0 | = | 216 | ≡ | 8 | (mod 26) | 20 17 15 | | 19 | | 325 | | 13 | ``` -------------------------------- ### Convert Floating-Point Number to Binary String Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/binary-floating-point/README.md This example shows how to obtain the binary string representation of a floating-point number in JavaScript. This is useful for understanding the internal binary format of numbers. ```javascript import { floatAsBinaryString } from './floatAsBinaryString'; // Example usage: const number = 1.5; const binaryString = floatAsBinaryString(number); console.log(binaryString); // Output: "0100000000000000" (for half-precision representation) ``` -------------------------------- ### Example 3: Trapping Rain Water Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/rain-terraces/README.md Shows trapping water with a longer input array [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]. ```plaintext Input: arr[] = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] Output: 6 ``` -------------------------------- ### Integer Representation in Binary Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/binary-floating-point/README.md Demonstrates how integers are represented using a fixed number of bits, showing the conversion of binary to decimal for both a small number and the maximum value within 16 bits. ```text (0000000000000000)₂ = (0)₁₀ (0000000000010001)₂ = (1 × 2⁴) + (0 × 2³) + (0 × 2²) + (0 × 2¹) + (1 × 2⁰) = (17)₁₀ (1111111111111111)₂ = (1 × 2¹⁵) + (1 × 2¹⁴) + (1 × 2¹³) + (1 × 2¹²) + (1 × 2¹¹) + (1 × 2¹⁰) + (1 × 2⁹) + (1 × 2⁸) + (1 × 2⁷) + (1 × 2⁶) + (1 × 2⁵) + (1 × 2⁴) + (1 × 2³) + (1 × 2²) + (1 × 2¹) + (1 × 2⁰) = (65535)₁₀ ``` -------------------------------- ### Run All Project Tests Source: https://github.com/trekhleb/javascript-algorithms/blob/master/README.md Execute this command to run the entire test suite for the project. This ensures all algorithms and data structures function correctly. ```bash npm test ``` -------------------------------- ### Run Playground Tests Source: https://github.com/trekhleb/javascript-algorithms/blob/master/README.md Execute this command to test your custom code written in the playground file. This is useful for experimenting with data structures and algorithms. ```bash npm test -- 'playground' ``` -------------------------------- ### Divide and Conquer Approach (Conceptual) Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/README.md Illustrates the recursive breakdown of the problem. This approach explores all combinations but is highly inefficient with O(2^n) time complexity. ```javascript function profit(prices) { // Base case: no prices, no profit. if (prices.length === 0) { return 0; } // Option 1: Keep the money (don't buy/sell at current price). const keepProfit = profit(prices.slice(1)); // Option 2: Buy/sell at current price. // We assume we bought at the current price and sell at the highest possible price later. // This is a simplified representation; a full implementation would need to consider all future sell points. // For demonstration, we'll just consider selling at the next available price if it's higher. let buySellProfit = 0; if (prices.length > 1 && prices[1] > prices[0]) { buySellProfit = prices[1] - prices[0] + profit(prices.slice(2)); } else { // If the next price is not higher, we might still buy and sell later. // A more complete D&C would explore all future sell points. // For simplicity here, we'll just consider the profit from the rest of the array. buySellProfit = profit(prices.slice(1)); } // The overall profit is the maximum of keeping the money or buying/selling now. return Math.max(keepProfit, buySellProfit); } ``` -------------------------------- ### Run ESLint for Code Quality Source: https://github.com/trekhleb/javascript-algorithms/blob/master/README.md Execute this command to check the code quality using ESLint. This helps maintain consistent coding standards. ```bash npm run lint ``` -------------------------------- ### Run Playground Tests Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/playground/README.md Use this command to run tests specifically for the playground code. ```bash npm test -- -t 'playground' ``` -------------------------------- ### Hill Cipher Decryption Example Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/cryptography/hill-cipher/README.md Demonstrates the decryption of a ciphertext block using the inverse of the 3x3 key matrix and modular arithmetic. ```plaintext -1 | 6 24 1 | | 8 5 10 | | 13 16 10 | (mod 26) ≡ | 21 8 21 | | 20 17 15 | | 21 12 8 | ``` ```plaintext | 8 5 10 | | 15 | | 260 | | 0 | | 21 8 21 | | 14 | = | 574 | ≡ | 2 | (mod 26) | 21 12 8 | | 7 | | 539 | | 19 | ``` -------------------------------- ### Search for Value in BST Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/tree/binary-search-tree/README.md Recursively searches for a given value within the BST starting from the root. Returns true if found, false otherwise. ```pseudocode contains(root, value) Pre: root is the root node of the tree, value is what we would like to locate Post: value is either located or not if root = ø return false end if if root.value = value return true else if value < root.value return contains(root.left, value) else return contains(root.right, value) end if end contains ``` -------------------------------- ### Full Adder Implementation Logic Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/bits/README.md Illustrates the logic of a full adder using bitwise operations to sum two 32-bit integers. It details the process of handling individual bits and carry-ins to produce a sum bit and a carry-out bit for each stage. ```plaintext A = 3: 011 B = 6: 110 ┌──────┬────┬────┬─────────┬──────────┬─────────┬───────────┬───────────┐ │ bit │ ai │ bi │ carryIn │ carryOut │ bitSum │ resultBin │ resultDec │ ├──────┼────┼────┼─────────┼──────────┼─────────┼───────────┼───────────┤ │ 0 │ 1 │ 0 │ 0 │ 0 │ 1 │ 1 │ 1 │ │ 1 │ 1 │ 1 │ 0 │ 1 │ 0 │ 01 │ 1 │ │ 2 │ 0 │ 1 │ 1 │ 1 │ 0 │ 001 │ 1 │ │ 3 │ 0 │ 0 │ 1 │ 0 │ 1 │ 1001 │ 9 │ └──────┴────┴────┴─────────┴──────────┴─────────┴───────────┴───────────┘ ``` -------------------------------- ### Pseudocode for Doubly Linked List Reverse Traversal Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/doubly-linked-list/README.md This pseudocode shows how to traverse a doubly linked list starting from the tail node and moving towards the head. ```text ReverseTraversal(tail) Pre: tail is the node of the list to traverse Post: the list has been traversed in reverse order n ← tail while n != ø yield n.value n ← n.previous end while end Reverse Traversal ``` -------------------------------- ### Get Pixel Color from ImageData Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/image-processing/seam-carving/README.md Retrieves the RGBA color values for a specific pixel at (x, y) from an ImageData object. It converts 2D coordinates to a 1D array index. ```typescript const getPixel = (img: ImageData, { x, y }: Coordinate): Color => { const i = y * img.width + x; const cellsPerColor = 4; // RGBA return img.data.subarray(i * cellsPerColor, i * cellsPerColor + cellsPerColor); }; ``` -------------------------------- ### Accumulator Approach (JavaScript) Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/README.md Calculates maximum profit by summing all positive price differences between consecutive days. This is a simple O(n) time and O(1) space solution. ```javascript function accumulatorBestTimeToBuySellStocks(prices) { let maxProfit = 0; for (let i = 1; i < prices.length; i++) { // If the price increased from the previous day, add the profit. if (prices[i] > prices[i - 1]) { maxProfit += prices[i] - prices[i - 1]; } } return maxProfit; } ``` -------------------------------- ### Linked List Contains Operation Pseudocode Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/linked-list/README.md Pseudocode for searching for a specific value within a linked list starting from the head. Returns true if the value is found, false otherwise. ```pseudocode Contains(head, value) Pre: head is the head node in the list value is the value to search for Post: the item is either in the linked list, true; otherwise false n ← head while n != ø and n.value != value n ← n.next end while if n = ø return false end if return true end Contains ``` -------------------------------- ### Naive Algorithm for Hamiltonian Cycle Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/graph/hamiltonian-cycle/README.md This pseudocode outlines a brute-force approach to finding a Hamiltonian cycle by generating all vertex permutations and checking for cycle validity. It is highly inefficient due to its O(n!) time complexity. ```pseudocode while there are untried configurations { generate the next configuration if ( there are edges between two consecutive vertices of this configuration and there is an edge from the last vertex to the first ). { print this configuration; break; } } ``` -------------------------------- ### Linked List Reverse Traversal Pseudocode Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/linked-list/README.md Pseudocode for traversing a linked list in reverse order, starting from the tail. This implementation requires iterating to find the predecessor of the current node in each step. ```pseudocode ReverseTraversal(head, tail) Pre: head and tail belong to the same list Post: the items in the list have been traversed in reverse order if tail != ø curr ← tail while curr != head prev ← head while prev.next != curr prev ← prev.next end while yield curr.value curr ← prev end while yield curr.value end if end ReverseTraversal ``` -------------------------------- ### Naive Algorithm Pseudocode Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/uncategorized/n-queens/README.md A brute-force approach to solving the N-Queens problem by generating and checking all possible configurations. ```plaintext while there are untried configurations { generate the next configuration if queens don't attack in this configuration then { print this configuration; } } ``` -------------------------------- ### Newton's Method Iteration Formula for Square Root Source: https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/math/square-root/README.md This is the core iterative step for Newton's method when applied to finding the square root of a number S. It refines the current guess 'x' to get closer to the actual square root. ```text x := x - (x² - S) / (2x) ``` -------------------------------- ### Clean and Reinstall Node Modules Source: https://github.com/trekhleb/javascript-algorithms/blob/master/README.md If facing issues with linting or testing, try removing the 'node_modules' directory and reinstalling packages. This resolves potential dependency conflicts. ```bash rm -rf ./node_modules npm i ```