repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/search/jump-search/__test__/jumpSearch.test.js
src/algorithms/search/jump-search/__test__/jumpSearch.test.js
import jumpSearch from '../jumpSearch'; describe('jumpSearch', () => { it('should search for an element in sorted array', () => { expect(jumpSearch([], 1)).toBe(-1); expect(jumpSearch([1], 2)).toBe(-1); expect(jumpSearch([1], 1)).toBe(0); expect(jumpSearch([1, 2], 1)).toBe(0); expect(jumpSearch([1, 2], 1)).toBe(0); expect(jumpSearch([1, 1, 1], 1)).toBe(0); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 2)).toBe(1); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 0)).toBe(-1); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 0)).toBe(-1); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 7)).toBe(-1); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 5)).toBe(2); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 20)).toBe(4); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 30)).toBe(7); expect(jumpSearch([1, 2, 5, 10, 20, 21, 24, 30, 48], 48)).toBe(8); }); it('should search object in sorted array', () => { const sortedArrayOfObjects = [ { key: 1, value: 'value1' }, { key: 2, value: 'value2' }, { key: 3, value: 'value3' }, ]; const comparator = (a, b) => { if (a.key === b.key) return 0; return a.key < b.key ? -1 : 1; }; expect(jumpSearch([], { key: 1 }, comparator)).toBe(-1); expect(jumpSearch(sortedArrayOfObjects, { key: 4 }, comparator)).toBe(-1); expect(jumpSearch(sortedArrayOfObjects, { key: 1 }, comparator)).toBe(0); expect(jumpSearch(sortedArrayOfObjects, { key: 2 }, comparator)).toBe(1); expect(jumpSearch(sortedArrayOfObjects, { key: 3 }, comparator)).toBe(2); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/search/linear-search/linearSearch.js
src/algorithms/search/linear-search/linearSearch.js
import Comparator from '../../../utils/comparator/Comparator'; /** * Linear search implementation. * * @param {*[]} array * @param {*} seekElement * @param {function(a, b)} [comparatorCallback] * @return {number[]} */ export default function linearSearch(array, seekElement, comparatorCallback) { const comparator = new Comparator(comparatorCallback); const foundIndices = []; array.forEach((element, index) => { if (comparator.equal(element, seekElement)) { foundIndices.push(index); } }); return foundIndices; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/search/linear-search/__test__/linearSearch.test.js
src/algorithms/search/linear-search/__test__/linearSearch.test.js
import linearSearch from '../linearSearch'; describe('linearSearch', () => { it('should search all numbers in array', () => { const array = [1, 2, 4, 6, 2]; expect(linearSearch(array, 10)).toEqual([]); expect(linearSearch(array, 1)).toEqual([0]); expect(linearSearch(array, 2)).toEqual([1, 4]); }); it('should search all strings in array', () => { const array = ['a', 'b', 'a']; expect(linearSearch(array, 'c')).toEqual([]); expect(linearSearch(array, 'b')).toEqual([1]); expect(linearSearch(array, 'a')).toEqual([0, 2]); }); it('should search through objects as well', () => { const comparatorCallback = (a, b) => { if (a.key === b.key) { return 0; } return a.key <= b.key ? -1 : 1; }; const array = [ { key: 5 }, { key: 6 }, { key: 7 }, { key: 6 }, ]; expect(linearSearch(array, { key: 10 }, comparatorCallback)).toEqual([]); expect(linearSearch(array, { key: 5 }, comparatorCallback)).toEqual([0]); expect(linearSearch(array, { key: 6 }, comparatorCallback)).toEqual([1, 3]); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/search/interpolation-search/interpolationSearch.js
src/algorithms/search/interpolation-search/interpolationSearch.js
/** * Interpolation search implementation. * * @param {*[]} sortedArray - sorted array with uniformly distributed values * @param {*} seekElement * @return {number} */ export default function interpolationSearch(sortedArray, seekElement) { let leftIndex = 0; let rightIndex = sortedArray.length - 1; while (leftIndex <= rightIndex) { const rangeDelta = sortedArray[rightIndex] - sortedArray[leftIndex]; const indexDelta = rightIndex - leftIndex; const valueDelta = seekElement - sortedArray[leftIndex]; // If valueDelta is less then zero it means that there is no seek element // exists in array since the lowest element from the range is already higher // then seek element. if (valueDelta < 0) { return -1; } // If range delta is zero then subarray contains all the same numbers // and thus there is nothing to search for unless this range is all // consists of seek number. if (!rangeDelta) { // By doing this we're also avoiding division by zero while // calculating the middleIndex later. return sortedArray[leftIndex] === seekElement ? leftIndex : -1; } // Do interpolation of the middle index. const middleIndex = leftIndex + Math.floor((valueDelta * indexDelta) / rangeDelta); // If we've found the element just return its position. if (sortedArray[middleIndex] === seekElement) { return middleIndex; } // Decide which half to choose for seeking next: left or right one. if (sortedArray[middleIndex] < seekElement) { // Go to the right half of the array. leftIndex = middleIndex + 1; } else { // Go to the left half of the array. rightIndex = middleIndex - 1; } } return -1; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/search/interpolation-search/__test__/interpolationSearch.test.js
src/algorithms/search/interpolation-search/__test__/interpolationSearch.test.js
import interpolationSearch from '../interpolationSearch'; describe('interpolationSearch', () => { it('should search elements in sorted array of numbers', () => { expect(interpolationSearch([], 1)).toBe(-1); expect(interpolationSearch([1], 1)).toBe(0); expect(interpolationSearch([1], 0)).toBe(-1); expect(interpolationSearch([1, 1], 1)).toBe(0); expect(interpolationSearch([1, 2], 1)).toBe(0); expect(interpolationSearch([1, 2], 2)).toBe(1); expect(interpolationSearch([10, 20, 30, 40, 50], 40)).toBe(3); expect(interpolationSearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 14)).toBe(13); expect(interpolationSearch([1, 6, 7, 8, 12, 13, 14, 19, 21, 23, 24, 24, 24, 300], 24)).toBe(10); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 600)).toBe(-1); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 1)).toBe(0); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 2)).toBe(1); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 3)).toBe(2); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 700)).toBe(3); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 800)).toBe(4); expect(interpolationSearch([0, 2, 3, 700, 800, 1200, 1300, 1400, 1900], 1200)).toBe(5); expect(interpolationSearch([1, 2, 3, 700, 800, 1200, 1300, 1400, 19000], 800)).toBe(4); expect(interpolationSearch([0, 10, 11, 12, 13, 14, 15], 10)).toBe(1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/statistics/weighted-random/weightedRandom.js
src/algorithms/statistics/weighted-random/weightedRandom.js
/** * Picks the random item based on its weight. * The items with higher weight will be picked more often (with a higher probability). * * For example: * - items = ['banana', 'orange', 'apple'] * - weights = [0, 0.2, 0.8] * - weightedRandom(items, weights) in 80% of cases will return 'apple', in 20% of cases will return * 'orange' and it will never return 'banana' (because probability of picking the banana is 0%) * * @param {any[]} items * @param {number[]} weights * @returns {{item: any, index: number}} */ /* eslint-disable consistent-return */ export default function weightedRandom(items, weights) { if (items.length !== weights.length) { throw new Error('Items and weights must be of the same size'); } if (!items.length) { throw new Error('Items must not be empty'); } // Preparing the cumulative weights array. // For example: // - weights = [1, 4, 3] // - cumulativeWeights = [1, 5, 8] const cumulativeWeights = []; for (let i = 0; i < weights.length; i += 1) { cumulativeWeights[i] = weights[i] + (cumulativeWeights[i - 1] || 0); } // Getting the random number in a range of [0...sum(weights)] // For example: // - weights = [1, 4, 3] // - maxCumulativeWeight = 8 // - range for the random number is [0...8] const maxCumulativeWeight = cumulativeWeights[cumulativeWeights.length - 1]; const randomNumber = maxCumulativeWeight * Math.random(); // Picking the random item based on its weight. // The items with higher weight will be picked more often. for (let itemIndex = 0; itemIndex < items.length; itemIndex += 1) { if (cumulativeWeights[itemIndex] >= randomNumber) { return { item: items[itemIndex], index: itemIndex, }; } } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/statistics/weighted-random/__test__/weightedRandom.test.js
src/algorithms/statistics/weighted-random/__test__/weightedRandom.test.js
import weightedRandom from '../weightedRandom'; describe('weightedRandom', () => { it('should throw an error when the number of weights does not match the number of items', () => { const getWeightedRandomWithInvalidInputs = () => { weightedRandom(['a', 'b', 'c'], [10, 0]); }; expect(getWeightedRandomWithInvalidInputs).toThrow('Items and weights must be of the same size'); }); it('should throw an error when the number of weights or items are empty', () => { const getWeightedRandomWithInvalidInputs = () => { weightedRandom([], []); }; expect(getWeightedRandomWithInvalidInputs).toThrow('Items must not be empty'); }); it('should correctly do random selection based on wights in straightforward cases', () => { expect(weightedRandom(['a', 'b', 'c'], [1, 0, 0])).toEqual({ index: 0, item: 'a' }); expect(weightedRandom(['a', 'b', 'c'], [0, 1, 0])).toEqual({ index: 1, item: 'b' }); expect(weightedRandom(['a', 'b', 'c'], [0, 0, 1])).toEqual({ index: 2, item: 'c' }); expect(weightedRandom(['a', 'b', 'c'], [0, 1, 1])).not.toEqual({ index: 0, item: 'a' }); expect(weightedRandom(['a', 'b', 'c'], [1, 0, 1])).not.toEqual({ index: 1, item: 'b' }); expect(weightedRandom(['a', 'b', 'c'], [1, 1, 0])).not.toEqual({ index: 2, item: 'c' }); }); it('should correctly do random selection based on wights', () => { // Number of times we're going to select the random items based on their weights. const ATTEMPTS_NUM = 1000; // The +/- delta in the number of times each item has been actually selected. // I.e. if we want the item 'a' to be selected 300 times out of 1000 cases (30%) // then 267 times is acceptable since it is bigger that 250 (which is 300 - 50) // ans smaller than 350 (which is 300 + 50) const THRESHOLD = 50; const items = ['a', 'b', 'c']; // The actual items values don't matter. const weights = [0.1, 0.3, 0.6]; const counter = []; for (let i = 0; i < ATTEMPTS_NUM; i += 1) { const randomItem = weightedRandom(items, weights); if (!counter[randomItem.index]) { counter[randomItem.index] = 1; } else { counter[randomItem.index] += 1; } } for (let itemIndex = 0; itemIndex < items.length; itemIndex += 1) { /* i.e. item with the index of 0 must be selected 100 times (ideally) or with the threshold of [100 - 50, 100 + 50] times. i.e. item with the index of 1 must be selected 300 times (ideally) or with the threshold of [300 - 50, 300 + 50] times. i.e. item with the index of 2 must be selected 600 times (ideally) or with the threshold of [600 - 50, 600 + 50] times. */ expect(counter[itemIndex]).toBeGreaterThan(ATTEMPTS_NUM * weights[itemIndex] - THRESHOLD); expect(counter[itemIndex]).toBeLessThan(ATTEMPTS_NUM * weights[itemIndex] + THRESHOLD); } }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/Sort.js
src/algorithms/sorting/Sort.js
import Comparator from '../../utils/comparator/Comparator'; /** * @typedef {Object} SorterCallbacks * @property {function(a: *, b: *)} compareCallback - If provided then all elements comparisons * will be done through this callback. * @property {function(a: *)} visitingCallback - If provided it will be called each time the sorting * function is visiting the next element. */ export default class Sort { constructor(originalCallbacks) { this.callbacks = Sort.initSortingCallbacks(originalCallbacks); this.comparator = new Comparator(this.callbacks.compareCallback); } /** * @param {SorterCallbacks} originalCallbacks * @returns {SorterCallbacks} */ static initSortingCallbacks(originalCallbacks) { const callbacks = originalCallbacks || {}; const stubCallback = () => {}; callbacks.compareCallback = callbacks.compareCallback || undefined; callbacks.visitingCallback = callbacks.visitingCallback || stubCallback; return callbacks; } sort() { throw new Error('sort method must be implemented'); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/SortTester.js
src/algorithms/sorting/SortTester.js
export const sortedArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; export const reverseArr = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]; export const notSortedArr = [15, 8, 5, 12, 10, 1, 16, 9, 11, 7, 20, 3, 2, 6, 17, 18, 4, 13, 14, 19]; export const equalArr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; export const negativeArr = [-1, 0, 5, -10, 20, 13, -7, 3, 2, -3]; export const negativeArrSorted = [-10, -7, -3, -1, 0, 2, 3, 5, 13, 20]; export class SortTester { static testSort(SortingClass) { const sorter = new SortingClass(); expect(sorter.sort([])).toEqual([]); expect(sorter.sort([1])).toEqual([1]); expect(sorter.sort([1, 2])).toEqual([1, 2]); expect(sorter.sort([2, 1])).toEqual([1, 2]); expect(sorter.sort([3, 4, 2, 1, 0, 0, 4, 3, 4, 2])).toEqual([0, 0, 1, 2, 2, 3, 3, 4, 4, 4]); expect(sorter.sort(sortedArr)).toEqual(sortedArr); expect(sorter.sort(reverseArr)).toEqual(sortedArr); expect(sorter.sort(notSortedArr)).toEqual(sortedArr); expect(sorter.sort(equalArr)).toEqual(equalArr); } static testNegativeNumbersSort(SortingClass) { const sorter = new SortingClass(); expect(sorter.sort(negativeArr)).toEqual(negativeArrSorted); } static testSortWithCustomComparator(SortingClass) { const callbacks = { compareCallback: (a, b) => { if (a.length === b.length) { return 0; } return a.length < b.length ? -1 : 1; }, }; const sorter = new SortingClass(callbacks); expect(sorter.sort([''])).toEqual(['']); expect(sorter.sort(['a'])).toEqual(['a']); expect(sorter.sort(['aa', 'a'])).toEqual(['a', 'aa']); expect(sorter.sort(['aa', 'q', 'bbbb', 'ccc'])).toEqual(['q', 'aa', 'ccc', 'bbbb']); expect(sorter.sort(['aa', 'aa'])).toEqual(['aa', 'aa']); } static testSortStability(SortingClass) { const callbacks = { compareCallback: (a, b) => { if (a.length === b.length) { return 0; } return a.length < b.length ? -1 : 1; }, }; const sorter = new SortingClass(callbacks); expect(sorter.sort(['bb', 'aa', 'c'])).toEqual(['c', 'bb', 'aa']); expect(sorter.sort(['aa', 'q', 'a', 'bbbb', 'ccc'])).toEqual(['q', 'a', 'aa', 'ccc', 'bbbb']); } static testAlgorithmTimeComplexity(SortingClass, arrayToBeSorted, numberOfVisits) { const visitingCallback = jest.fn(); const callbacks = { visitingCallback }; const sorter = new SortingClass(callbacks); sorter.sort(arrayToBeSorted); expect(visitingCallback).toHaveBeenCalledTimes(numberOfVisits); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/insertion-sort/InsertionSort.js
src/algorithms/sorting/insertion-sort/InsertionSort.js
import Sort from '../Sort'; export default class InsertionSort extends Sort { sort(originalArray) { const array = [...originalArray]; // Go through all array elements... for (let i = 1; i < array.length; i += 1) { let currentIndex = i; // Call visiting callback. this.callbacks.visitingCallback(array[i]); // Check if previous element is greater than current element. // If so, swap the two elements. while ( array[currentIndex - 1] !== undefined && this.comparator.lessThan(array[currentIndex], array[currentIndex - 1]) ) { // Call visiting callback. this.callbacks.visitingCallback(array[currentIndex - 1]); // Swap the elements. [ array[currentIndex - 1], array[currentIndex], ] = [ array[currentIndex], array[currentIndex - 1], ]; // Shift current index left. currentIndex -= 1; } } return array; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/insertion-sort/__test__/InsertionSort.test.js
src/algorithms/sorting/insertion-sort/__test__/InsertionSort.test.js
import InsertionSort from '../InsertionSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 19; const NOT_SORTED_ARRAY_VISITING_COUNT = 100; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 209; const EQUAL_ARRAY_VISITING_COUNT = 19; describe('InsertionSort', () => { it('should sort array', () => { SortTester.testSort(InsertionSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(InsertionSort); }); it('should do stable sorting', () => { SortTester.testSortStability(InsertionSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(InsertionSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( InsertionSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( InsertionSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( InsertionSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( InsertionSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/__test__/Sort.test.js
src/algorithms/sorting/__test__/Sort.test.js
import Sort from '../Sort'; describe('Sort', () => { it('should throw an error when trying to call Sort.sort() method directly', () => { function doForbiddenSort() { const sorter = new Sort(); sorter.sort(); } expect(doForbiddenSort).toThrow(); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/radix-sort/RadixSort.js
src/algorithms/sorting/radix-sort/RadixSort.js
import Sort from '../Sort'; // Using charCode (a = 97, b = 98, etc), we can map characters to buckets from 0 - 25 const BASE_CHAR_CODE = 97; const NUMBER_OF_POSSIBLE_DIGITS = 10; const ENGLISH_ALPHABET_LENGTH = 26; export default class RadixSort extends Sort { /** * @param {*[]} originalArray * @return {*[]} */ sort(originalArray) { // Assumes all elements of array are of the same type const isArrayOfNumbers = this.isArrayOfNumbers(originalArray); let sortedArray = [...originalArray]; const numPasses = this.determineNumPasses(sortedArray); for (let currentIndex = 0; currentIndex < numPasses; currentIndex += 1) { const buckets = isArrayOfNumbers ? this.placeElementsInNumberBuckets(sortedArray, currentIndex) : this.placeElementsInCharacterBuckets(sortedArray, currentIndex, numPasses); // Flatten buckets into sortedArray, and repeat at next index sortedArray = buckets.reduce((acc, val) => { return [...acc, ...val]; }, []); } return sortedArray; } /** * @param {*[]} array * @param {number} index * @return {*[]} */ placeElementsInNumberBuckets(array, index) { // See below. These are used to determine which digit to use for bucket allocation const modded = 10 ** (index + 1); const divided = 10 ** index; const buckets = this.createBuckets(NUMBER_OF_POSSIBLE_DIGITS); array.forEach((element) => { this.callbacks.visitingCallback(element); if (element < divided) { buckets[0].push(element); } else { /** * Say we have element of 1,052 and are currently on index 1 (starting from 0). This means * we want to use '5' as the bucket. `modded` would be 10 ** (1 + 1), which * is 100. So we take 1,052 % 100 (52) and divide it by 10 (5.2) and floor it (5). */ const currentDigit = Math.floor((element % modded) / divided); buckets[currentDigit].push(element); } }); return buckets; } /** * @param {*[]} array * @param {number} index * @param {number} numPasses * @return {*[]} */ placeElementsInCharacterBuckets(array, index, numPasses) { const buckets = this.createBuckets(ENGLISH_ALPHABET_LENGTH); array.forEach((element) => { this.callbacks.visitingCallback(element); const currentBucket = this.getCharCodeOfElementAtIndex(element, index, numPasses); buckets[currentBucket].push(element); }); return buckets; } /** * @param {string} element * @param {number} index * @param {number} numPasses * @return {number} */ getCharCodeOfElementAtIndex(element, index, numPasses) { // Place element in last bucket if not ready to organize if ((numPasses - index) > element.length) { return ENGLISH_ALPHABET_LENGTH - 1; } /** * If each character has been organized, use first character to determine bucket, * otherwise iterate backwards through element */ const charPos = index > element.length - 1 ? 0 : element.length - index - 1; return element.toLowerCase().charCodeAt(charPos) - BASE_CHAR_CODE; } /** * Number of passes is determined by the length of the longest element in the array. * For integers, this log10(num), and for strings, this would be the length of the string. */ determineNumPasses(array) { return this.getLengthOfLongestElement(array); } /** * @param {*[]} array * @return {number} */ getLengthOfLongestElement(array) { if (this.isArrayOfNumbers(array)) { return Math.floor(Math.log10(Math.max(...array))) + 1; } return array.reduce((acc, val) => { return val.length > acc ? val.length : acc; }, -Infinity); } /** * @param {*[]} array * @return {boolean} */ isArrayOfNumbers(array) { // Assumes all elements of array are of the same type return this.isNumber(array[0]); } /** * @param {number} numBuckets * @return {*[]} */ createBuckets(numBuckets) { /** * Mapping buckets to an array instead of filling them with * an array prevents each bucket from containing a reference to the same array */ return new Array(numBuckets).fill(null).map(() => []); } /** * @param {*} element * @return {boolean} */ isNumber(element) { return Number.isInteger(element); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/radix-sort/__test__/RadixSort.test.js
src/algorithms/sorting/radix-sort/__test__/RadixSort.test.js
import RadixSort from '../RadixSort'; import { SortTester } from '../../SortTester'; // Complexity constants. const ARRAY_OF_STRINGS_VISIT_COUNT = 24; const ARRAY_OF_INTEGERS_VISIT_COUNT = 77; describe('RadixSort', () => { it('should sort array', () => { SortTester.testSort(RadixSort); }); it('should visit array of strings n (number of strings) x m (length of longest element) times', () => { SortTester.testAlgorithmTimeComplexity( RadixSort, ['zzz', 'bb', 'a', 'rr', 'rrb', 'rrba'], ARRAY_OF_STRINGS_VISIT_COUNT, ); }); it('should visit array of integers n (number of elements) x m (length of longest integer) times', () => { SortTester.testAlgorithmTimeComplexity( RadixSort, [3, 1, 75, 32, 884, 523, 4343456, 232, 123, 656, 343], ARRAY_OF_INTEGERS_VISIT_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/merge-sort/MergeSort.js
src/algorithms/sorting/merge-sort/MergeSort.js
import Sort from '../Sort'; export default class MergeSort extends Sort { sort(originalArray) { // Call visiting callback. this.callbacks.visitingCallback(null); // If array is empty or consists of one element then return this array since it is sorted. if (originalArray.length <= 1) { return originalArray; } // Split array on two halves. const middleIndex = Math.floor(originalArray.length / 2); const leftArray = originalArray.slice(0, middleIndex); const rightArray = originalArray.slice(middleIndex, originalArray.length); // Sort two halves of split array const leftSortedArray = this.sort(leftArray); const rightSortedArray = this.sort(rightArray); // Merge two sorted arrays into one. return this.mergeSortedArrays(leftSortedArray, rightSortedArray); } mergeSortedArrays(leftArray, rightArray) { const sortedArray = []; // Use array pointers to exclude old elements after they have been added to the sorted array. let leftIndex = 0; let rightIndex = 0; while (leftIndex < leftArray.length && rightIndex < rightArray.length) { let minElement = null; // Find the minimum element between the left and right array. if (this.comparator.lessThanOrEqual(leftArray[leftIndex], rightArray[rightIndex])) { minElement = leftArray[leftIndex]; // Increment index pointer to the right leftIndex += 1; } else { minElement = rightArray[rightIndex]; // Increment index pointer to the right rightIndex += 1; } // Add the minimum element to the sorted array. sortedArray.push(minElement); // Call visiting callback. this.callbacks.visitingCallback(minElement); } // There will be elements remaining from either the left OR the right // Concatenate the remaining elements into the sorted array return sortedArray .concat(leftArray.slice(leftIndex)) .concat(rightArray.slice(rightIndex)); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/merge-sort/__test__/MergeSort.test.js
src/algorithms/sorting/merge-sort/__test__/MergeSort.test.js
import MergeSort from '../MergeSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 79; const NOT_SORTED_ARRAY_VISITING_COUNT = 102; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 87; const EQUAL_ARRAY_VISITING_COUNT = 79; describe('MergeSort', () => { it('should sort array', () => { SortTester.testSort(MergeSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(MergeSort); }); it('should do stable sorting', () => { SortTester.testSortStability(MergeSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(MergeSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( MergeSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( MergeSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( MergeSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( MergeSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/shell-sort/ShellSort.js
src/algorithms/sorting/shell-sort/ShellSort.js
import Sort from '../Sort'; export default class ShellSort extends Sort { sort(originalArray) { // Prevent original array from mutations. const array = [...originalArray]; // Define a gap distance. let gap = Math.floor(array.length / 2); // Until gap is bigger then zero do elements comparisons and swaps. while (gap > 0) { // Go and compare all distant element pairs. for (let i = 0; i < (array.length - gap); i += 1) { let currentIndex = i; let gapShiftedIndex = i + gap; while (currentIndex >= 0) { // Call visiting callback. this.callbacks.visitingCallback(array[currentIndex]); // Compare and swap array elements if needed. if (this.comparator.lessThan(array[gapShiftedIndex], array[currentIndex])) { const tmp = array[currentIndex]; array[currentIndex] = array[gapShiftedIndex]; array[gapShiftedIndex] = tmp; } gapShiftedIndex = currentIndex; currentIndex -= gap; } } // Shrink the gap. gap = Math.floor(gap / 2); } // Return sorted copy of an original array. return array; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/shell-sort/__test__/ShellSort.test.js
src/algorithms/sorting/shell-sort/__test__/ShellSort.test.js
import ShellSort from '../ShellSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 320; const NOT_SORTED_ARRAY_VISITING_COUNT = 320; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 320; const EQUAL_ARRAY_VISITING_COUNT = 320; describe('ShellSort', () => { it('should sort array', () => { SortTester.testSort(ShellSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(ShellSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(ShellSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( ShellSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( ShellSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( ShellSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( ShellSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/counting-sort/CountingSort.js
src/algorithms/sorting/counting-sort/CountingSort.js
import Sort from '../Sort'; export default class CountingSort extends Sort { /** * @param {number[]} originalArray * @param {number} [smallestElement] * @param {number} [biggestElement] */ sort(originalArray, smallestElement = undefined, biggestElement = undefined) { // Init biggest and smallest elements in array in order to build number bucket array later. let detectedSmallestElement = smallestElement || 0; let detectedBiggestElement = biggestElement || 0; if (smallestElement === undefined || biggestElement === undefined) { originalArray.forEach((element) => { // Visit element. this.callbacks.visitingCallback(element); // Detect biggest element. if (this.comparator.greaterThan(element, detectedBiggestElement)) { detectedBiggestElement = element; } // Detect smallest element. if (this.comparator.lessThan(element, detectedSmallestElement)) { detectedSmallestElement = element; } }); } // Init buckets array. // This array will hold frequency of each number from originalArray. const buckets = Array(detectedBiggestElement - detectedSmallestElement + 1).fill(0); originalArray.forEach((element) => { // Visit element. this.callbacks.visitingCallback(element); buckets[element - detectedSmallestElement] += 1; }); // Add previous frequencies to the current one for each number in bucket // to detect how many numbers less then current one should be standing to // the left of current one. for (let bucketIndex = 1; bucketIndex < buckets.length; bucketIndex += 1) { buckets[bucketIndex] += buckets[bucketIndex - 1]; } // Now let's shift frequencies to the right so that they show correct numbers. // I.e. if we won't shift right than the value of buckets[5] will display how many // elements less than 5 should be placed to the left of 5 in sorted array // INCLUDING 5th. After shifting though this number will not include 5th anymore. buckets.pop(); buckets.unshift(0); // Now let's assemble sorted array. const sortedArray = Array(originalArray.length).fill(null); for (let elementIndex = 0; elementIndex < originalArray.length; elementIndex += 1) { // Get the element that we want to put into correct sorted position. const element = originalArray[elementIndex]; // Visit element. this.callbacks.visitingCallback(element); // Get correct position of this element in sorted array. const elementSortedPosition = buckets[element - detectedSmallestElement]; // Put element into correct position in sorted array. sortedArray[elementSortedPosition] = element; // Increase position of current element in the bucket for future correct placements. buckets[element - detectedSmallestElement] += 1; } // Return sorted array. return sortedArray; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/counting-sort/__test__/CountingSort.test.js
src/algorithms/sorting/counting-sort/__test__/CountingSort.test.js
import CountingSort from '../CountingSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 60; const NOT_SORTED_ARRAY_VISITING_COUNT = 60; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 60; const EQUAL_ARRAY_VISITING_COUNT = 60; describe('CountingSort', () => { it('should sort array', () => { SortTester.testSort(CountingSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(CountingSort); }); it('should allow to use specify max/min integer value in array to make sorting faster', () => { const visitingCallback = jest.fn(); const sorter = new CountingSort({ visitingCallback }); // Detect biggest number in array in prior. const biggestElement = Math.max(...notSortedArr); // Detect smallest number in array in prior. const smallestElement = Math.min(...notSortedArr); const sortedArray = sorter.sort(notSortedArr, smallestElement, biggestElement); expect(sortedArray).toEqual(sortedArr); // Normally visitingCallback is being called 60 times but in this case // it should be called only 40 times. expect(visitingCallback).toHaveBeenCalledTimes(40); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( CountingSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( CountingSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( CountingSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( CountingSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/quick-sort/QuickSort.js
src/algorithms/sorting/quick-sort/QuickSort.js
import Sort from '../Sort'; export default class QuickSort extends Sort { /** * @param {*[]} originalArray * @return {*[]} */ sort(originalArray) { // Clone original array to prevent it from modification. const array = [...originalArray]; // If array has less than or equal to one elements then it is already sorted. if (array.length <= 1) { return array; } // Init left and right arrays. const leftArray = []; const rightArray = []; // Take the first element of array as a pivot. const pivotElement = array.shift(); const centerArray = [pivotElement]; // Split all array elements between left, center and right arrays. while (array.length) { const currentElement = array.shift(); // Call visiting callback. this.callbacks.visitingCallback(currentElement); if (this.comparator.equal(currentElement, pivotElement)) { centerArray.push(currentElement); } else if (this.comparator.lessThan(currentElement, pivotElement)) { leftArray.push(currentElement); } else { rightArray.push(currentElement); } } // Sort left and right arrays. const leftArraySorted = this.sort(leftArray); const rightArraySorted = this.sort(rightArray); // Let's now join sorted left array with center array and with sorted right array. return leftArraySorted.concat(centerArray, rightArraySorted); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/quick-sort/QuickSortInPlace.js
src/algorithms/sorting/quick-sort/QuickSortInPlace.js
import Sort from '../Sort'; export default class QuickSortInPlace extends Sort { /** Sorting in place avoids unnecessary use of additional memory, but modifies input array. * * This process is difficult to describe, but much clearer with a visualization: * @see: https://www.hackerearth.com/practice/algorithms/sorting/quick-sort/visualize/ * * @param {*[]} originalArray - Not sorted array. * @param {number} inputLowIndex * @param {number} inputHighIndex * @param {boolean} recursiveCall * @return {*[]} - Sorted array. */ sort( originalArray, inputLowIndex = 0, inputHighIndex = originalArray.length - 1, recursiveCall = false, ) { // Copies array on initial call, and then sorts in place. const array = recursiveCall ? originalArray : [...originalArray]; /** * The partitionArray() operates on the subarray between lowIndex and highIndex, inclusive. * It arbitrarily chooses the last element in the subarray as the pivot. * Then, it partially sorts the subarray into elements than are less than the pivot, * and elements that are greater than or equal to the pivot. * Each time partitionArray() is executed, the pivot element is in its final sorted position. * * @param {number} lowIndex * @param {number} highIndex * @return {number} */ const partitionArray = (lowIndex, highIndex) => { /** * Swaps two elements in array. * @param {number} leftIndex * @param {number} rightIndex */ const swap = (leftIndex, rightIndex) => { const temp = array[leftIndex]; array[leftIndex] = array[rightIndex]; array[rightIndex] = temp; }; const pivot = array[highIndex]; // visitingCallback is used for time-complexity analysis. this.callbacks.visitingCallback(pivot); let partitionIndex = lowIndex; for (let currentIndex = lowIndex; currentIndex < highIndex; currentIndex += 1) { if (this.comparator.lessThan(array[currentIndex], pivot)) { swap(partitionIndex, currentIndex); partitionIndex += 1; } } // The element at the partitionIndex is guaranteed to be greater than or equal to pivot. // All elements to the left of partitionIndex are guaranteed to be less than pivot. // Swapping the pivot with the partitionIndex therefore places the pivot in its // final sorted position. swap(partitionIndex, highIndex); return partitionIndex; }; // Base case is when low and high converge. if (inputLowIndex < inputHighIndex) { const partitionIndex = partitionArray(inputLowIndex, inputHighIndex); const RECURSIVE_CALL = true; this.sort(array, inputLowIndex, partitionIndex - 1, RECURSIVE_CALL); this.sort(array, partitionIndex + 1, inputHighIndex, RECURSIVE_CALL); } return array; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/quick-sort/__test__/QuickSort.test.js
src/algorithms/sorting/quick-sort/__test__/QuickSort.test.js
import QuickSort from '../QuickSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 190; const NOT_SORTED_ARRAY_VISITING_COUNT = 62; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 190; const EQUAL_ARRAY_VISITING_COUNT = 19; describe('QuickSort', () => { it('should sort array', () => { SortTester.testSort(QuickSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(QuickSort); }); it('should do stable sorting', () => { SortTester.testSortStability(QuickSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(QuickSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/quick-sort/__test__/QuickSortInPlace.test.js
src/algorithms/sorting/quick-sort/__test__/QuickSortInPlace.test.js
import QuickSortInPlace from '../QuickSortInPlace'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 19; const NOT_SORTED_ARRAY_VISITING_COUNT = 12; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 19; const EQUAL_ARRAY_VISITING_COUNT = 19; describe('QuickSortInPlace', () => { it('should sort array', () => { SortTester.testSort(QuickSortInPlace); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(QuickSortInPlace); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(QuickSortInPlace); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSortInPlace, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSortInPlace, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSortInPlace, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( QuickSortInPlace, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/bucket-sort/BucketSort.js
src/algorithms/sorting/bucket-sort/BucketSort.js
import RadixSort from '../radix-sort/RadixSort'; /** * Bucket Sort * * @param {number[]} arr * @param {number} bucketsNum * @return {number[]} */ export default function BucketSort(arr, bucketsNum = 1) { const buckets = new Array(bucketsNum).fill(null).map(() => []); const minValue = Math.min(...arr); const maxValue = Math.max(...arr); const bucketSize = Math.ceil(Math.max(1, (maxValue - minValue) / bucketsNum)); // Place elements into buckets. for (let i = 0; i < arr.length; i += 1) { const currValue = arr[i]; const bucketIndex = Math.floor((currValue - minValue) / bucketSize); // Edge case for max value. if (bucketIndex === bucketsNum) { buckets[bucketsNum - 1].push(currValue); } else { buckets[bucketIndex].push(currValue); } } // Sort individual buckets. for (let i = 0; i < buckets.length; i += 1) { // Let's use the Radix Sorter here. This may give us // the average O(n + k) time complexity to sort one bucket // (where k is a number of digits in the longest number). buckets[i] = new RadixSort().sort(buckets[i]); } // Merge sorted buckets into final output. const sortedArr = []; for (let i = 0; i < buckets.length; i += 1) { sortedArr.push(...buckets[i]); } return sortedArr; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/bucket-sort/__test__/BucketSort.test.js
src/algorithms/sorting/bucket-sort/__test__/BucketSort.test.js
import BucketSort from '../BucketSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, } from '../../SortTester'; describe('BucketSort', () => { it('should sort the array of numbers with different buckets amounts', () => { expect(BucketSort(notSortedArr, 4)).toEqual(sortedArr); expect(BucketSort(equalArr, 4)).toEqual(equalArr); expect(BucketSort(reverseArr, 4)).toEqual(sortedArr); expect(BucketSort(sortedArr, 4)).toEqual(sortedArr); expect(BucketSort(notSortedArr, 10)).toEqual(sortedArr); expect(BucketSort(equalArr, 10)).toEqual(equalArr); expect(BucketSort(reverseArr, 10)).toEqual(sortedArr); expect(BucketSort(sortedArr, 10)).toEqual(sortedArr); expect(BucketSort(notSortedArr, 50)).toEqual(sortedArr); expect(BucketSort(equalArr, 50)).toEqual(equalArr); expect(BucketSort(reverseArr, 50)).toEqual(sortedArr); expect(BucketSort(sortedArr, 50)).toEqual(sortedArr); }); it('should sort the array of numbers with the default buckets of 1', () => { expect(BucketSort(notSortedArr)).toEqual(sortedArr); expect(BucketSort(equalArr)).toEqual(equalArr); expect(BucketSort(reverseArr)).toEqual(sortedArr); expect(BucketSort(sortedArr)).toEqual(sortedArr); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/selection-sort/SelectionSort.js
src/algorithms/sorting/selection-sort/SelectionSort.js
import Sort from '../Sort'; export default class SelectionSort extends Sort { sort(originalArray) { // Clone original array to prevent its modification. const array = [...originalArray]; for (let i = 0; i < array.length - 1; i += 1) { let minIndex = i; // Call visiting callback. this.callbacks.visitingCallback(array[i]); // Find minimum element in the rest of array. for (let j = i + 1; j < array.length; j += 1) { // Call visiting callback. this.callbacks.visitingCallback(array[j]); if (this.comparator.lessThan(array[j], array[minIndex])) { minIndex = j; } } // If new minimum element has been found then swap it with current i-th element. if (minIndex !== i) { [array[i], array[minIndex]] = [array[minIndex], array[i]]; } } return array; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/selection-sort/__test__/SelectionSort.test.js
src/algorithms/sorting/selection-sort/__test__/SelectionSort.test.js
import SelectionSort from '../SelectionSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 209; const NOT_SORTED_ARRAY_VISITING_COUNT = 209; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 209; const EQUAL_ARRAY_VISITING_COUNT = 209; describe('SelectionSort', () => { it('should sort array', () => { SortTester.testSort(SelectionSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(SelectionSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(SelectionSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( SelectionSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( SelectionSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( SelectionSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( SelectionSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/bubble-sort/BubbleSort.js
src/algorithms/sorting/bubble-sort/BubbleSort.js
import Sort from '../Sort'; export default class BubbleSort extends Sort { sort(originalArray) { // Flag that holds info about whether the swap has occur or not. let swapped = false; // Clone original array to prevent its modification. const array = [...originalArray]; for (let i = 1; i < array.length; i += 1) { swapped = false; // Call visiting callback. this.callbacks.visitingCallback(array[i]); for (let j = 0; j < array.length - i; j += 1) { // Call visiting callback. this.callbacks.visitingCallback(array[j]); // Swap elements if they are in wrong order. if (this.comparator.lessThan(array[j + 1], array[j])) { [array[j], array[j + 1]] = [array[j + 1], array[j]]; // Register the swap. swapped = true; } } // If there were no swaps then array is already sorted and there is // no need to proceed. if (!swapped) { return array; } } return array; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/bubble-sort/__test__/BubbleSort.test.js
src/algorithms/sorting/bubble-sort/__test__/BubbleSort.test.js
import BubbleSort from '../BubbleSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. const SORTED_ARRAY_VISITING_COUNT = 20; const NOT_SORTED_ARRAY_VISITING_COUNT = 189; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 209; const EQUAL_ARRAY_VISITING_COUNT = 20; describe('BubbleSort', () => { it('should sort array', () => { SortTester.testSort(BubbleSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(BubbleSort); }); it('should do stable sorting', () => { SortTester.testSortStability(BubbleSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(BubbleSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( BubbleSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( BubbleSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( BubbleSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( BubbleSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/heap-sort/HeapSort.js
src/algorithms/sorting/heap-sort/HeapSort.js
import Sort from '../Sort'; import MinHeap from '../../../data-structures/heap/MinHeap'; export default class HeapSort extends Sort { sort(originalArray) { const sortedArray = []; const minHeap = new MinHeap(this.callbacks.compareCallback); // Insert all array elements to the heap. originalArray.forEach((element) => { // Call visiting callback. this.callbacks.visitingCallback(element); minHeap.add(element); }); // Now we have min heap with minimal element always on top. // Let's poll that minimal element one by one and thus form the sorted array. while (!minHeap.isEmpty()) { const nextMinElement = minHeap.poll(); // Call visiting callback. this.callbacks.visitingCallback(nextMinElement); sortedArray.push(nextMinElement); } return sortedArray; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/sorting/heap-sort/__test__/HeapSort.test.js
src/algorithms/sorting/heap-sort/__test__/HeapSort.test.js
import HeapSort from '../HeapSort'; import { equalArr, notSortedArr, reverseArr, sortedArr, SortTester, } from '../../SortTester'; // Complexity constants. // These numbers don't take into account up/dow heapifying of the heap. // Thus these numbers are higher in reality. const SORTED_ARRAY_VISITING_COUNT = 40; const NOT_SORTED_ARRAY_VISITING_COUNT = 40; const REVERSE_SORTED_ARRAY_VISITING_COUNT = 40; const EQUAL_ARRAY_VISITING_COUNT = 40; describe('HeapSort', () => { it('should sort array', () => { SortTester.testSort(HeapSort); }); it('should sort array with custom comparator', () => { SortTester.testSortWithCustomComparator(HeapSort); }); it('should sort negative numbers', () => { SortTester.testNegativeNumbersSort(HeapSort); }); it('should visit EQUAL array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( HeapSort, equalArr, EQUAL_ARRAY_VISITING_COUNT, ); }); it('should visit SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( HeapSort, sortedArr, SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit NOT SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( HeapSort, notSortedArr, NOT_SORTED_ARRAY_VISITING_COUNT, ); }); it('should visit REVERSE SORTED array element specified number of times', () => { SortTester.testAlgorithmTimeComplexity( HeapSort, reverseArr, REVERSE_SORTED_ARRAY_VISITING_COUNT, ); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/tree/breadth-first-search/breadthFirstSearch.js
src/algorithms/tree/breadth-first-search/breadthFirstSearch.js
import Queue from '../../../data-structures/queue/Queue'; /** * @typedef {Object} Callbacks * @property {function(node: BinaryTreeNode, child: BinaryTreeNode): boolean} allowTraversal - * Determines whether BFS should traverse from the node to its child. * @property {function(node: BinaryTreeNode)} enterNode - Called when BFS enters the node. * @property {function(node: BinaryTreeNode)} leaveNode - Called when BFS leaves the node. */ /** * @param {Callbacks} [callbacks] * @returns {Callbacks} */ function initCallbacks(callbacks = {}) { const initiatedCallback = callbacks; const stubCallback = () => {}; const defaultAllowTraversal = () => true; initiatedCallback.allowTraversal = callbacks.allowTraversal || defaultAllowTraversal; initiatedCallback.enterNode = callbacks.enterNode || stubCallback; initiatedCallback.leaveNode = callbacks.leaveNode || stubCallback; return initiatedCallback; } /** * @param {BinaryTreeNode} rootNode * @param {Callbacks} [originalCallbacks] */ export default function breadthFirstSearch(rootNode, originalCallbacks) { const callbacks = initCallbacks(originalCallbacks); const nodeQueue = new Queue(); // Do initial queue setup. nodeQueue.enqueue(rootNode); while (!nodeQueue.isEmpty()) { const currentNode = nodeQueue.dequeue(); callbacks.enterNode(currentNode); // Add all children to the queue for future traversals. // Traverse left branch. if (currentNode.left && callbacks.allowTraversal(currentNode, currentNode.left)) { nodeQueue.enqueue(currentNode.left); } // Traverse right branch. if (currentNode.right && callbacks.allowTraversal(currentNode, currentNode.right)) { nodeQueue.enqueue(currentNode.right); } callbacks.leaveNode(currentNode); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/tree/breadth-first-search/__test__/breadthFirstSearch.test.js
src/algorithms/tree/breadth-first-search/__test__/breadthFirstSearch.test.js
import BinaryTreeNode from '../../../../data-structures/tree/BinaryTreeNode'; import breadthFirstSearch from '../breadthFirstSearch'; describe('breadthFirstSearch', () => { it('should perform BFS operation on tree', () => { const nodeA = new BinaryTreeNode('A'); const nodeB = new BinaryTreeNode('B'); const nodeC = new BinaryTreeNode('C'); const nodeD = new BinaryTreeNode('D'); const nodeE = new BinaryTreeNode('E'); const nodeF = new BinaryTreeNode('F'); const nodeG = new BinaryTreeNode('G'); nodeA.setLeft(nodeB).setRight(nodeC); nodeB.setLeft(nodeD).setRight(nodeE); nodeC.setLeft(nodeF).setRight(nodeG); // In-order traversing. expect(nodeA.toString()).toBe('D,B,E,A,F,C,G'); const enterNodeCallback = jest.fn(); const leaveNodeCallback = jest.fn(); // Traverse tree without callbacks first to check default ones. breadthFirstSearch(nodeA); // Traverse tree with callbacks. breadthFirstSearch(nodeA, { enterNode: enterNodeCallback, leaveNode: leaveNodeCallback, }); expect(enterNodeCallback).toHaveBeenCalledTimes(7); expect(leaveNodeCallback).toHaveBeenCalledTimes(7); // Check node entering. expect(enterNodeCallback.mock.calls[0][0].value).toEqual('A'); expect(enterNodeCallback.mock.calls[1][0].value).toEqual('B'); expect(enterNodeCallback.mock.calls[2][0].value).toEqual('C'); expect(enterNodeCallback.mock.calls[3][0].value).toEqual('D'); expect(enterNodeCallback.mock.calls[4][0].value).toEqual('E'); expect(enterNodeCallback.mock.calls[5][0].value).toEqual('F'); expect(enterNodeCallback.mock.calls[6][0].value).toEqual('G'); // Check node leaving. expect(leaveNodeCallback.mock.calls[0][0].value).toEqual('A'); expect(leaveNodeCallback.mock.calls[1][0].value).toEqual('B'); expect(leaveNodeCallback.mock.calls[2][0].value).toEqual('C'); expect(leaveNodeCallback.mock.calls[3][0].value).toEqual('D'); expect(leaveNodeCallback.mock.calls[4][0].value).toEqual('E'); expect(leaveNodeCallback.mock.calls[5][0].value).toEqual('F'); expect(leaveNodeCallback.mock.calls[6][0].value).toEqual('G'); }); it('allow users to redefine node visiting logic', () => { const nodeA = new BinaryTreeNode('A'); const nodeB = new BinaryTreeNode('B'); const nodeC = new BinaryTreeNode('C'); const nodeD = new BinaryTreeNode('D'); const nodeE = new BinaryTreeNode('E'); const nodeF = new BinaryTreeNode('F'); const nodeG = new BinaryTreeNode('G'); nodeA.setLeft(nodeB).setRight(nodeC); nodeB.setLeft(nodeD).setRight(nodeE); nodeC.setLeft(nodeF).setRight(nodeG); // In-order traversing. expect(nodeA.toString()).toBe('D,B,E,A,F,C,G'); const enterNodeCallback = jest.fn(); const leaveNodeCallback = jest.fn(); // Traverse tree without callbacks first to check default ones. breadthFirstSearch(nodeA); // Traverse tree with callbacks. breadthFirstSearch(nodeA, { allowTraversal: (node, child) => { // Forbid traversing left half of the tree. return child.value !== 'B'; }, enterNode: enterNodeCallback, leaveNode: leaveNodeCallback, }); expect(enterNodeCallback).toHaveBeenCalledTimes(4); expect(leaveNodeCallback).toHaveBeenCalledTimes(4); // Check node entering. expect(enterNodeCallback.mock.calls[0][0].value).toEqual('A'); expect(enterNodeCallback.mock.calls[1][0].value).toEqual('C'); expect(enterNodeCallback.mock.calls[2][0].value).toEqual('F'); expect(enterNodeCallback.mock.calls[3][0].value).toEqual('G'); // Check node leaving. expect(leaveNodeCallback.mock.calls[0][0].value).toEqual('A'); expect(leaveNodeCallback.mock.calls[1][0].value).toEqual('C'); expect(leaveNodeCallback.mock.calls[2][0].value).toEqual('F'); expect(leaveNodeCallback.mock.calls[3][0].value).toEqual('G'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/tree/depth-first-search/depthFirstSearch.js
src/algorithms/tree/depth-first-search/depthFirstSearch.js
/** * @typedef {Object} TraversalCallbacks * * @property {function(node: BinaryTreeNode, child: BinaryTreeNode): boolean} allowTraversal * - Determines whether DFS should traverse from the node to its child. * * @property {function(node: BinaryTreeNode)} enterNode - Called when DFS enters the node. * * @property {function(node: BinaryTreeNode)} leaveNode - Called when DFS leaves the node. */ /** * Extend missing traversal callbacks with default callbacks. * * @param {TraversalCallbacks} [callbacks] - The object that contains traversal callbacks. * @returns {TraversalCallbacks} - Traversal callbacks extended with defaults callbacks. */ function initCallbacks(callbacks = {}) { // Init empty callbacks object. const initiatedCallbacks = {}; // Empty callback that we will use in case if user didn't provide real callback function. const stubCallback = () => {}; // By default we will allow traversal of every node // in case if user didn't provide a callback for that. const defaultAllowTraversalCallback = () => true; // Copy original callbacks to our initiatedCallbacks object or use default callbacks instead. initiatedCallbacks.allowTraversal = callbacks.allowTraversal || defaultAllowTraversalCallback; initiatedCallbacks.enterNode = callbacks.enterNode || stubCallback; initiatedCallbacks.leaveNode = callbacks.leaveNode || stubCallback; // Returned processed list of callbacks. return initiatedCallbacks; } /** * Recursive depth-first-search traversal for binary. * * @param {BinaryTreeNode} node - binary tree node that we will start traversal from. * @param {TraversalCallbacks} callbacks - the object that contains traversal callbacks. */ export function depthFirstSearchRecursive(node, callbacks) { // Call the "enterNode" callback to notify that the node is going to be entered. callbacks.enterNode(node); // Traverse left branch only if case if traversal of the left node is allowed. if (node.left && callbacks.allowTraversal(node, node.left)) { depthFirstSearchRecursive(node.left, callbacks); } // Traverse right branch only if case if traversal of the right node is allowed. if (node.right && callbacks.allowTraversal(node, node.right)) { depthFirstSearchRecursive(node.right, callbacks); } // Call the "leaveNode" callback to notify that traversal // of the current node and its children is finished. callbacks.leaveNode(node); } /** * Perform depth-first-search traversal of the rootNode. * For every traversal step call "allowTraversal", "enterNode" and "leaveNode" callbacks. * See TraversalCallbacks type definition for more details about the shape of callbacks object. * * @param {BinaryTreeNode} rootNode - The node from which we start traversing. * @param {TraversalCallbacks} [callbacks] - Traversal callbacks. */ export default function depthFirstSearch(rootNode, callbacks) { // In case if user didn't provide some callback we need to replace them with default ones. const processedCallbacks = initCallbacks(callbacks); // Now, when we have all necessary callbacks we may proceed to recursive traversal. depthFirstSearchRecursive(rootNode, processedCallbacks); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/tree/depth-first-search/__test__/depthFirstSearch.test.js
src/algorithms/tree/depth-first-search/__test__/depthFirstSearch.test.js
import BinaryTreeNode from '../../../../data-structures/tree/BinaryTreeNode'; import depthFirstSearch from '../depthFirstSearch'; describe('depthFirstSearch', () => { it('should perform DFS operation on tree', () => { const nodeA = new BinaryTreeNode('A'); const nodeB = new BinaryTreeNode('B'); const nodeC = new BinaryTreeNode('C'); const nodeD = new BinaryTreeNode('D'); const nodeE = new BinaryTreeNode('E'); const nodeF = new BinaryTreeNode('F'); const nodeG = new BinaryTreeNode('G'); nodeA.setLeft(nodeB).setRight(nodeC); nodeB.setLeft(nodeD).setRight(nodeE); nodeC.setLeft(nodeF).setRight(nodeG); // In-order traversing. expect(nodeA.toString()).toBe('D,B,E,A,F,C,G'); const enterNodeCallback = jest.fn(); const leaveNodeCallback = jest.fn(); // Traverse tree without callbacks first to check default ones. depthFirstSearch(nodeA); // Traverse tree with callbacks. depthFirstSearch(nodeA, { enterNode: enterNodeCallback, leaveNode: leaveNodeCallback, }); expect(enterNodeCallback).toHaveBeenCalledTimes(7); expect(leaveNodeCallback).toHaveBeenCalledTimes(7); // Check node entering. expect(enterNodeCallback.mock.calls[0][0].value).toEqual('A'); expect(enterNodeCallback.mock.calls[1][0].value).toEqual('B'); expect(enterNodeCallback.mock.calls[2][0].value).toEqual('D'); expect(enterNodeCallback.mock.calls[3][0].value).toEqual('E'); expect(enterNodeCallback.mock.calls[4][0].value).toEqual('C'); expect(enterNodeCallback.mock.calls[5][0].value).toEqual('F'); expect(enterNodeCallback.mock.calls[6][0].value).toEqual('G'); // Check node leaving. expect(leaveNodeCallback.mock.calls[0][0].value).toEqual('D'); expect(leaveNodeCallback.mock.calls[1][0].value).toEqual('E'); expect(leaveNodeCallback.mock.calls[2][0].value).toEqual('B'); expect(leaveNodeCallback.mock.calls[3][0].value).toEqual('F'); expect(leaveNodeCallback.mock.calls[4][0].value).toEqual('G'); expect(leaveNodeCallback.mock.calls[5][0].value).toEqual('C'); expect(leaveNodeCallback.mock.calls[6][0].value).toEqual('A'); }); it('allow users to redefine node visiting logic', () => { const nodeA = new BinaryTreeNode('A'); const nodeB = new BinaryTreeNode('B'); const nodeC = new BinaryTreeNode('C'); const nodeD = new BinaryTreeNode('D'); const nodeE = new BinaryTreeNode('E'); const nodeF = new BinaryTreeNode('F'); const nodeG = new BinaryTreeNode('G'); nodeA.setLeft(nodeB).setRight(nodeC); nodeB.setLeft(nodeD).setRight(nodeE); nodeC.setLeft(nodeF).setRight(nodeG); // In-order traversing. expect(nodeA.toString()).toBe('D,B,E,A,F,C,G'); const enterNodeCallback = jest.fn(); const leaveNodeCallback = jest.fn(); // Traverse tree without callbacks first to check default ones. depthFirstSearch(nodeA); // Traverse tree with callbacks. depthFirstSearch(nodeA, { allowTraversal: (node, child) => { // Forbid traversing left part of the tree. return child.value !== 'B'; }, enterNode: enterNodeCallback, leaveNode: leaveNodeCallback, }); expect(enterNodeCallback).toHaveBeenCalledTimes(4); expect(leaveNodeCallback).toHaveBeenCalledTimes(4); // Check node entering. expect(enterNodeCallback.mock.calls[0][0].value).toEqual('A'); expect(enterNodeCallback.mock.calls[1][0].value).toEqual('C'); expect(enterNodeCallback.mock.calls[2][0].value).toEqual('F'); expect(enterNodeCallback.mock.calls[3][0].value).toEqual('G'); // Check node leaving. expect(leaveNodeCallback.mock.calls[0][0].value).toEqual('F'); expect(leaveNodeCallback.mock.calls[1][0].value).toEqual('G'); expect(leaveNodeCallback.mock.calls[2][0].value).toEqual('C'); expect(leaveNodeCallback.mock.calls[3][0].value).toEqual('A'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/n-queens/QueenPosition.js
src/algorithms/uncategorized/n-queens/QueenPosition.js
/** * Class that represents queen position on the chessboard. */ export default class QueenPosition { /** * @param {number} rowIndex * @param {number} columnIndex */ constructor(rowIndex, columnIndex) { this.rowIndex = rowIndex; this.columnIndex = columnIndex; } /** * @return {number} */ get leftDiagonal() { // Each position on the same left (\) diagonal has the same difference of // rowIndex and columnIndex. This fact may be used to quickly check if two // positions (queens) are on the same left diagonal. // @see https://youtu.be/xouin83ebxE?t=1m59s return this.rowIndex - this.columnIndex; } /** * @return {number} */ get rightDiagonal() { // Each position on the same right diagonal (/) has the same // sum of rowIndex and columnIndex. This fact may be used to quickly // check if two positions (queens) are on the same right diagonal. // @see https://youtu.be/xouin83ebxE?t=1m59s return this.rowIndex + this.columnIndex; } toString() { return `${this.rowIndex},${this.columnIndex}`; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/n-queens/nQueensBitwise.js
src/algorithms/uncategorized/n-queens/nQueensBitwise.js
/** * Checks all possible board configurations. * * @param {number} boardSize - Size of the squared chess board. * @param {number} leftDiagonal - Sequence of N bits that show whether the corresponding location * on the current row is "available" (no other queens are threatening from left diagonal). * @param {number} column - Sequence of N bits that show whether the corresponding location * on the current row is "available" (no other queens are threatening from columns). * @param {number} rightDiagonal - Sequence of N bits that show whether the corresponding location * on the current row is "available" (no other queens are threatening from right diagonal). * @param {number} solutionsCount - Keeps track of the number of valid solutions. * @return {number} - Number of possible solutions. */ function nQueensBitwiseRecursive( boardSize, leftDiagonal = 0, column = 0, rightDiagonal = 0, solutionsCount = 0, ) { // Keeps track of the number of valid solutions. let currentSolutionsCount = solutionsCount; // Helps to identify valid solutions. // isDone simply has a bit sequence with 1 for every entry up to the Nth. For example, // when N=5, done will equal 11111. The "isDone" variable simply allows us to not worry about any // bits beyond the Nth. const isDone = (2 ** boardSize) - 1; // All columns are occupied (i.e. 0b1111 for boardSize = 4), so the solution must be complete. // Since the algorithm never places a queen illegally (ie. when it can attack or be attacked), // we know that if all the columns have been filled, we must have a valid solution. if (column === isDone) { return currentSolutionsCount + 1; } // Gets a bit sequence with "1"s wherever there is an open "slot". // All that's happening here is we're taking col, ld, and rd, and if any of the columns are // "under attack", we mark that column as 0 in poss, basically meaning "we can't put a queen in // this column". Thus all bits position in poss that are '1's are available for placing // queen there. let availablePositions = ~(leftDiagonal | rightDiagonal | column); // Loops as long as there is a valid place to put another queen. // For N=4 the isDone=0b1111. Then if availablePositions=0b0000 (which would mean that all places // are under threatening) we must stop trying to place a queen. while (availablePositions & isDone) { // firstAvailablePosition just stores the first non-zero bit (ie. the first available location). // So if firstAvailablePosition was 0010, it would mean the 3rd column of the current row. // And that would be the position will be placing our next queen. // // For example: // availablePositions = 0b01100 // firstAvailablePosition = 100 const firstAvailablePosition = availablePositions & -availablePositions; // This line just marks that position in the current row as being "taken" by flipping that // column in availablePositions to zero. This way, when the while loop continues, we'll know // not to try that location again. // // For example: // availablePositions = 0b0100 // firstAvailablePosition = 0b10 // 0b0110 - 0b10 = 0b0100 availablePositions -= firstAvailablePosition; /* * The operators >> 1 and 1 << simply move all the bits in a bit sequence one digit to the * right or left, respectively. So calling (rd|bit)<<1 simply says: combine rd and bit with * an OR operation, then move everything in the result to the left by one digit. * * More specifically, if rd is 0001 (meaning that the top-right-to-bottom-left diagonal through * column 4 of the current row is occupied), and bit is 0100 (meaning that we are planning to * place a queen in column 2 of the current row), (rd|bit) results in 0101 (meaning that after * we place a queen in column 2 of the current row, the second and the fourth * top-right-to-bottom-left diagonals will be occupied). * * Now, if add in the << operator, we get (rd|bit)<<1, which takes the 0101 we worked out in * our previous bullet point, and moves everything to the left by one. The result, therefore, * is 1010. */ currentSolutionsCount += nQueensBitwiseRecursive( boardSize, (leftDiagonal | firstAvailablePosition) >> 1, column | firstAvailablePosition, (rightDiagonal | firstAvailablePosition) << 1, solutionsCount, ); } return currentSolutionsCount; } /** * @param {number} boardSize - Size of the squared chess board. * @return {number} - Number of possible solutions. * @see http://gregtrowbridge.com/a-bitwise-solution-to-the-n-queens-problem-in-javascript/ */ export default function nQueensBitwise(boardSize) { return nQueensBitwiseRecursive(boardSize); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/n-queens/nQueens.js
src/algorithms/uncategorized/n-queens/nQueens.js
import QueenPosition from './QueenPosition'; /** * @param {QueenPosition[]} queensPositions * @param {number} rowIndex * @param {number} columnIndex * @return {boolean} */ function isSafe(queensPositions, rowIndex, columnIndex) { // New position to which the Queen is going to be placed. const newQueenPosition = new QueenPosition(rowIndex, columnIndex); // Check if new queen position conflicts with any other queens. for (let queenIndex = 0; queenIndex < queensPositions.length; queenIndex += 1) { const currentQueenPosition = queensPositions[queenIndex]; if ( // Check if queen has been already placed. currentQueenPosition && ( // Check if there are any queen on the same column. newQueenPosition.columnIndex === currentQueenPosition.columnIndex // Check if there are any queen on the same row. || newQueenPosition.rowIndex === currentQueenPosition.rowIndex // Check if there are any queen on the same left diagonal. || newQueenPosition.leftDiagonal === currentQueenPosition.leftDiagonal // Check if there are any queen on the same right diagonal. || newQueenPosition.rightDiagonal === currentQueenPosition.rightDiagonal ) ) { // Can't place queen into current position since there are other queens that // are threatening it. return false; } } // Looks like we're safe. return true; } /** * @param {QueenPosition[][]} solutions * @param {QueenPosition[]} previousQueensPositions * @param {number} queensCount * @param {number} rowIndex * @return {boolean} */ function nQueensRecursive(solutions, previousQueensPositions, queensCount, rowIndex) { // Clone positions array. const queensPositions = [...previousQueensPositions].map((queenPosition) => { return !queenPosition ? queenPosition : new QueenPosition( queenPosition.rowIndex, queenPosition.columnIndex, ); }); if (rowIndex === queensCount) { // We've successfully reached the end of the board. // Store solution to the list of solutions. solutions.push(queensPositions); // Solution found. return true; } // Let's try to put queen at row rowIndex into its safe column position. for (let columnIndex = 0; columnIndex < queensCount; columnIndex += 1) { if (isSafe(queensPositions, rowIndex, columnIndex)) { // Place current queen to its current position. queensPositions[rowIndex] = new QueenPosition(rowIndex, columnIndex); // Try to place all other queens as well. nQueensRecursive(solutions, queensPositions, queensCount, rowIndex + 1); // BACKTRACKING. // Remove the queen from the row to avoid isSafe() returning false. queensPositions[rowIndex] = null; } } return false; } /** * @param {number} queensCount * @return {QueenPosition[][]} */ export default function nQueens(queensCount) { // Init NxN chessboard with zeros. // const chessboard = Array(queensCount).fill(null).map(() => Array(queensCount).fill(0)); // This array will hold positions or coordinates of each of // N queens in form of [rowIndex, columnIndex]. const queensPositions = Array(queensCount).fill(null); /** @var {QueenPosition[][]} solutions */ const solutions = []; // Solve problem recursively. nQueensRecursive(solutions, queensPositions, queensCount, 0); return solutions; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/n-queens/__test__/nQueens.test.js
src/algorithms/uncategorized/n-queens/__test__/nQueens.test.js
import nQueens from '../nQueens'; describe('nQueens', () => { it('should not hae solution for 3 queens', () => { const solutions = nQueens(3); expect(solutions.length).toBe(0); }); it('should solve n-queens problem for 4 queens', () => { const solutions = nQueens(4); expect(solutions.length).toBe(2); // First solution. expect(solutions[0][0].toString()).toBe('0,1'); expect(solutions[0][1].toString()).toBe('1,3'); expect(solutions[0][2].toString()).toBe('2,0'); expect(solutions[0][3].toString()).toBe('3,2'); // Second solution (mirrored). expect(solutions[1][0].toString()).toBe('0,2'); expect(solutions[1][1].toString()).toBe('1,0'); expect(solutions[1][2].toString()).toBe('2,3'); expect(solutions[1][3].toString()).toBe('3,1'); }); it('should solve n-queens problem for 6 queens', () => { const solutions = nQueens(6); expect(solutions.length).toBe(4); // First solution. expect(solutions[0][0].toString()).toBe('0,1'); expect(solutions[0][1].toString()).toBe('1,3'); expect(solutions[0][2].toString()).toBe('2,5'); expect(solutions[0][3].toString()).toBe('3,0'); expect(solutions[0][4].toString()).toBe('4,2'); expect(solutions[0][5].toString()).toBe('5,4'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/n-queens/__test__/QueensPosition.test.js
src/algorithms/uncategorized/n-queens/__test__/QueensPosition.test.js
import QueenPosition from '../QueenPosition'; describe('QueenPosition', () => { it('should store queen position on chessboard', () => { const position1 = new QueenPosition(0, 0); const position2 = new QueenPosition(2, 1); expect(position2.columnIndex).toBe(1); expect(position2.rowIndex).toBe(2); expect(position1.leftDiagonal).toBe(0); expect(position1.rightDiagonal).toBe(0); expect(position2.leftDiagonal).toBe(1); expect(position2.rightDiagonal).toBe(3); expect(position2.toString()).toBe('2,1'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/n-queens/__test__/nQueensBitwise.test.js
src/algorithms/uncategorized/n-queens/__test__/nQueensBitwise.test.js
import nQueensBitwise from '../nQueensBitwise'; describe('nQueensBitwise', () => { it('should have solutions for 4 to N queens', () => { expect(nQueensBitwise(4)).toBe(2); expect(nQueensBitwise(5)).toBe(10); expect(nQueensBitwise(6)).toBe(4); expect(nQueensBitwise(7)).toBe(40); expect(nQueensBitwise(8)).toBe(92); expect(nQueensBitwise(9)).toBe(352); expect(nQueensBitwise(10)).toBe(724); expect(nQueensBitwise(11)).toBe(2680); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/rain-terraces/dpRainTerraces.js
src/algorithms/uncategorized/rain-terraces/dpRainTerraces.js
/** * DYNAMIC PROGRAMMING approach of solving Trapping Rain Water problem. * * @param {number[]} terraces * @return {number} */ export default function dpRainTerraces(terraces) { let waterAmount = 0; // Init arrays that will keep the list of left and right maximum levels for specific positions. const leftMaxLevels = new Array(terraces.length).fill(0); const rightMaxLevels = new Array(terraces.length).fill(0); // Calculate the highest terrace level from the LEFT relative to the current terrace. [leftMaxLevels[0]] = terraces; for (let terraceIndex = 1; terraceIndex < terraces.length; terraceIndex += 1) { leftMaxLevels[terraceIndex] = Math.max( terraces[terraceIndex], leftMaxLevels[terraceIndex - 1], ); } // Calculate the highest terrace level from the RIGHT relative to the current terrace. rightMaxLevels[terraces.length - 1] = terraces[terraces.length - 1]; for (let terraceIndex = terraces.length - 2; terraceIndex >= 0; terraceIndex -= 1) { rightMaxLevels[terraceIndex] = Math.max( terraces[terraceIndex], rightMaxLevels[terraceIndex + 1], ); } // Not let's go through all terraces one by one and calculate how much water // each terrace may accumulate based on previously calculated values. for (let terraceIndex = 0; terraceIndex < terraces.length; terraceIndex += 1) { // Pick the lowest from the left/right highest terraces. const currentTerraceBoundary = Math.min( leftMaxLevels[terraceIndex], rightMaxLevels[terraceIndex], ); if (currentTerraceBoundary > terraces[terraceIndex]) { waterAmount += currentTerraceBoundary - terraces[terraceIndex]; } } return waterAmount; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/rain-terraces/bfRainTerraces.js
src/algorithms/uncategorized/rain-terraces/bfRainTerraces.js
/** * BRUTE FORCE approach of solving Trapping Rain Water problem. * * @param {number[]} terraces * @return {number} */ export default function bfRainTerraces(terraces) { let waterAmount = 0; for (let terraceIndex = 0; terraceIndex < terraces.length; terraceIndex += 1) { // Get left most high terrace. let leftHighestLevel = 0; for (let leftIndex = terraceIndex - 1; leftIndex >= 0; leftIndex -= 1) { leftHighestLevel = Math.max(leftHighestLevel, terraces[leftIndex]); } // Get right most high terrace. let rightHighestLevel = 0; for (let rightIndex = terraceIndex + 1; rightIndex < terraces.length; rightIndex += 1) { rightHighestLevel = Math.max(rightHighestLevel, terraces[rightIndex]); } // Add current terrace water amount. const terraceBoundaryLevel = Math.min(leftHighestLevel, rightHighestLevel); if (terraceBoundaryLevel > terraces[terraceIndex]) { // Terrace will be able to store the water if the lowest of two left and right highest // terraces are still higher than the current one. waterAmount += terraceBoundaryLevel - terraces[terraceIndex]; } } return waterAmount; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/rain-terraces/__test__/bfRainTerraces.test.js
src/algorithms/uncategorized/rain-terraces/__test__/bfRainTerraces.test.js
import bfRainTerraces from '../bfRainTerraces'; describe('bfRainTerraces', () => { it('should find the amount of water collected after raining', () => { expect(bfRainTerraces([1])).toBe(0); expect(bfRainTerraces([1, 0])).toBe(0); expect(bfRainTerraces([0, 1])).toBe(0); expect(bfRainTerraces([0, 1, 0])).toBe(0); expect(bfRainTerraces([0, 1, 0, 0])).toBe(0); expect(bfRainTerraces([0, 1, 0, 0, 1, 0])).toBe(2); expect(bfRainTerraces([0, 2, 0, 0, 1, 0])).toBe(2); expect(bfRainTerraces([2, 0, 2])).toBe(2); expect(bfRainTerraces([2, 0, 5])).toBe(2); expect(bfRainTerraces([3, 0, 0, 2, 0, 4])).toBe(10); expect(bfRainTerraces([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])).toBe(6); expect(bfRainTerraces([1, 1, 1, 1, 1])).toBe(0); expect(bfRainTerraces([1, 2, 3, 4, 5])).toBe(0); expect(bfRainTerraces([4, 1, 3, 1, 2, 1, 2, 1])).toBe(4); expect(bfRainTerraces([0, 2, 4, 3, 4, 2, 4, 0, 8, 7, 0])).toBe(7); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/rain-terraces/__test__/dpRainTerraces.test.js
src/algorithms/uncategorized/rain-terraces/__test__/dpRainTerraces.test.js
import dpRainTerraces from '../dpRainTerraces'; describe('dpRainTerraces', () => { it('should find the amount of water collected after raining', () => { expect(dpRainTerraces([1])).toBe(0); expect(dpRainTerraces([1, 0])).toBe(0); expect(dpRainTerraces([0, 1])).toBe(0); expect(dpRainTerraces([0, 1, 0])).toBe(0); expect(dpRainTerraces([0, 1, 0, 0])).toBe(0); expect(dpRainTerraces([0, 1, 0, 0, 1, 0])).toBe(2); expect(dpRainTerraces([0, 2, 0, 0, 1, 0])).toBe(2); expect(dpRainTerraces([2, 0, 2])).toBe(2); expect(dpRainTerraces([2, 0, 5])).toBe(2); expect(dpRainTerraces([3, 0, 0, 2, 0, 4])).toBe(10); expect(dpRainTerraces([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])).toBe(6); expect(dpRainTerraces([1, 1, 1, 1, 1])).toBe(0); expect(dpRainTerraces([1, 2, 3, 4, 5])).toBe(0); expect(dpRainTerraces([4, 1, 3, 1, 2, 1, 2, 1])).toBe(4); expect(dpRainTerraces([0, 2, 4, 3, 4, 2, 4, 0, 8, 7, 0])).toBe(7); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/square-matrix-rotation/squareMatrixRotation.js
src/algorithms/uncategorized/square-matrix-rotation/squareMatrixRotation.js
/** * @param {*[][]} originalMatrix * @return {*[][]} */ export default function squareMatrixRotation(originalMatrix) { const matrix = originalMatrix.slice(); // Do top-right/bottom-left diagonal reflection of the matrix. for (let rowIndex = 0; rowIndex < matrix.length; rowIndex += 1) { for (let columnIndex = rowIndex + 1; columnIndex < matrix.length; columnIndex += 1) { // Swap elements. [ matrix[columnIndex][rowIndex], matrix[rowIndex][columnIndex], ] = [ matrix[rowIndex][columnIndex], matrix[columnIndex][rowIndex], ]; } } // Do horizontal reflection of the matrix. for (let rowIndex = 0; rowIndex < matrix.length; rowIndex += 1) { for (let columnIndex = 0; columnIndex < matrix.length / 2; columnIndex += 1) { // Swap elements. [ matrix[rowIndex][matrix.length - columnIndex - 1], matrix[rowIndex][columnIndex], ] = [ matrix[rowIndex][columnIndex], matrix[rowIndex][matrix.length - columnIndex - 1], ]; } } return matrix; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/square-matrix-rotation/__test__/squareMatrixRotation.test.js
src/algorithms/uncategorized/square-matrix-rotation/__test__/squareMatrixRotation.test.js
import squareMatrixRotation from '../squareMatrixRotation'; describe('squareMatrixRotation', () => { it('should rotate matrix #0 in-place', () => { const matrix = [[1]]; const rotatedMatrix = [[1]]; expect(squareMatrixRotation(matrix)).toEqual(rotatedMatrix); }); it('should rotate matrix #1 in-place', () => { const matrix = [ [1, 2], [3, 4], ]; const rotatedMatrix = [ [3, 1], [4, 2], ]; expect(squareMatrixRotation(matrix)).toEqual(rotatedMatrix); }); it('should rotate matrix #2 in-place', () => { const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; const rotatedMatrix = [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ]; expect(squareMatrixRotation(matrix)).toEqual(rotatedMatrix); }); it('should rotate matrix #3 in-place', () => { const matrix = [ [5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16], ]; const rotatedMatrix = [ [15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11], ]; expect(squareMatrixRotation(matrix)).toEqual(rotatedMatrix); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/hanoi-tower/hanoiTower.js
src/algorithms/uncategorized/hanoi-tower/hanoiTower.js
import Stack from '../../../data-structures/stack/Stack'; /** * @param {number} numberOfDiscs * @param {Stack} fromPole * @param {Stack} withPole * @param {Stack} toPole * @param {function(disc: number, fromPole: number[], toPole: number[])} moveCallback */ function hanoiTowerRecursive({ numberOfDiscs, fromPole, withPole, toPole, moveCallback, }) { if (numberOfDiscs === 1) { // Base case with just one disc. moveCallback(fromPole.peek(), fromPole.toArray(), toPole.toArray()); const disc = fromPole.pop(); toPole.push(disc); } else { // In case if there are more discs then move them recursively. // Expose the bottom disc on fromPole stack. hanoiTowerRecursive({ numberOfDiscs: numberOfDiscs - 1, fromPole, withPole: toPole, toPole: withPole, moveCallback, }); // Move the disc that was exposed to its final destination. hanoiTowerRecursive({ numberOfDiscs: 1, fromPole, withPole, toPole, moveCallback, }); // Move temporary tower from auxiliary pole to its final destination. hanoiTowerRecursive({ numberOfDiscs: numberOfDiscs - 1, fromPole: withPole, withPole: fromPole, toPole, moveCallback, }); } } /** * @param {number} numberOfDiscs * @param {function(disc: number, fromPole: number[], toPole: number[])} moveCallback * @param {Stack} [fromPole] * @param {Stack} [withPole] * @param {Stack} [toPole] */ export default function hanoiTower({ numberOfDiscs, moveCallback, fromPole = new Stack(), withPole = new Stack(), toPole = new Stack(), }) { // Each of three poles of Tower of Hanoi puzzle is represented as a stack // that might contain elements (discs). Each disc is represented as a number. // Larger discs have bigger number equivalent. // Let's create the discs and put them to the fromPole. for (let discSize = numberOfDiscs; discSize > 0; discSize -= 1) { fromPole.push(discSize); } hanoiTowerRecursive({ numberOfDiscs, fromPole, withPole, toPole, moveCallback, }); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/hanoi-tower/__test__/hanoiTower.test.js
src/algorithms/uncategorized/hanoi-tower/__test__/hanoiTower.test.js
import hanoiTower from '../hanoiTower'; import Stack from '../../../../data-structures/stack/Stack'; describe('hanoiTower', () => { it('should solve tower of hanoi puzzle with 2 discs', () => { const moveCallback = jest.fn(); const numberOfDiscs = 2; const fromPole = new Stack(); const withPole = new Stack(); const toPole = new Stack(); hanoiTower({ numberOfDiscs, moveCallback, fromPole, withPole, toPole, }); expect(moveCallback).toHaveBeenCalledTimes((2 ** numberOfDiscs) - 1); expect(fromPole.toArray()).toEqual([]); expect(toPole.toArray()).toEqual([1, 2]); expect(moveCallback.mock.calls[0][0]).toBe(1); expect(moveCallback.mock.calls[0][1]).toEqual([1, 2]); expect(moveCallback.mock.calls[0][2]).toEqual([]); expect(moveCallback.mock.calls[1][0]).toBe(2); expect(moveCallback.mock.calls[1][1]).toEqual([2]); expect(moveCallback.mock.calls[1][2]).toEqual([]); expect(moveCallback.mock.calls[2][0]).toBe(1); expect(moveCallback.mock.calls[2][1]).toEqual([1]); expect(moveCallback.mock.calls[2][2]).toEqual([2]); }); it('should solve tower of hanoi puzzle with 3 discs', () => { const moveCallback = jest.fn(); const numberOfDiscs = 3; hanoiTower({ numberOfDiscs, moveCallback, }); expect(moveCallback).toHaveBeenCalledTimes((2 ** numberOfDiscs) - 1); }); it('should solve tower of hanoi puzzle with 6 discs', () => { const moveCallback = jest.fn(); const numberOfDiscs = 6; hanoiTower({ numberOfDiscs, moveCallback, }); expect(moveCallback).toHaveBeenCalledTimes((2 ** numberOfDiscs) - 1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/knight-tour/knightTour.js
src/algorithms/uncategorized/knight-tour/knightTour.js
/** * @param {number[][]} chessboard * @param {number[]} position * @return {number[][]} */ function getPossibleMoves(chessboard, position) { // Generate all knight moves (even those that go beyond the board). const possibleMoves = [ [position[0] - 1, position[1] - 2], [position[0] - 2, position[1] - 1], [position[0] + 1, position[1] - 2], [position[0] + 2, position[1] - 1], [position[0] - 2, position[1] + 1], [position[0] - 1, position[1] + 2], [position[0] + 1, position[1] + 2], [position[0] + 2, position[1] + 1], ]; // Filter out all moves that go beyond the board. return possibleMoves.filter((move) => { const boardSize = chessboard.length; return move[0] >= 0 && move[1] >= 0 && move[0] < boardSize && move[1] < boardSize; }); } /** * @param {number[][]} chessboard * @param {number[]} move * @return {boolean} */ function isMoveAllowed(chessboard, move) { return chessboard[move[0]][move[1]] !== 1; } /** * @param {number[][]} chessboard * @param {number[][]} moves * @return {boolean} */ function isBoardCompletelyVisited(chessboard, moves) { const totalPossibleMovesCount = chessboard.length ** 2; const existingMovesCount = moves.length; return totalPossibleMovesCount === existingMovesCount; } /** * @param {number[][]} chessboard * @param {number[][]} moves * @return {boolean} */ function knightTourRecursive(chessboard, moves) { const currentChessboard = chessboard; // If board has been completely visited then we've found a solution. if (isBoardCompletelyVisited(currentChessboard, moves)) { return true; } // Get next possible knight moves. const lastMove = moves[moves.length - 1]; const possibleMoves = getPossibleMoves(currentChessboard, lastMove); // Try to do next possible moves. for (let moveIndex = 0; moveIndex < possibleMoves.length; moveIndex += 1) { const currentMove = possibleMoves[moveIndex]; // Check if current move is allowed. We aren't allowed to go to // the same cells twice. if (isMoveAllowed(currentChessboard, currentMove)) { // Actually do the move. moves.push(currentMove); currentChessboard[currentMove[0]][currentMove[1]] = 1; // If further moves starting from current are successful then // return true meaning the solution is found. if (knightTourRecursive(currentChessboard, moves)) { return true; } // BACKTRACKING. // If current move was unsuccessful then step back and try to do another move. moves.pop(); currentChessboard[currentMove[0]][currentMove[1]] = 0; } } // Return false if we haven't found solution. return false; } /** * @param {number} chessboardSize * @return {number[][]} */ export default function knightTour(chessboardSize) { // Init chessboard. const chessboard = Array(chessboardSize).fill(null).map(() => Array(chessboardSize).fill(0)); // Init moves array. const moves = []; // Do first move and place the knight to the 0x0 cell. const firstMove = [0, 0]; moves.push(firstMove); chessboard[firstMove[0]][firstMove[0]] = 1; // Recursively try to do the next move. const solutionWasFound = knightTourRecursive(chessboard, moves); return solutionWasFound ? moves : []; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/knight-tour/__test__/knightTour.test.js
src/algorithms/uncategorized/knight-tour/__test__/knightTour.test.js
import knightTour from '../knightTour'; describe('knightTour', () => { it('should not find solution on 3x3 board', () => { const moves = knightTour(3); expect(moves.length).toBe(0); }); it('should find one solution to do knight tour on 5x5 board', () => { const moves = knightTour(5); expect(moves.length).toBe(25); expect(moves).toEqual([ [0, 0], [1, 2], [2, 0], [0, 1], [1, 3], [3, 4], [2, 2], [4, 1], [3, 3], [1, 4], [0, 2], [1, 0], [3, 1], [4, 3], [2, 4], [0, 3], [1, 1], [3, 0], [4, 2], [2, 1], [4, 0], [3, 2], [4, 4], [2, 3], [0, 4], ]); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/dpBestTimeToBuySellStocks.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/dpBestTimeToBuySellStocks.js
/** * Finds the maximum profit from selling and buying the stocks. * DYNAMIC PROGRAMMING APPROACH. * * @param {number[]} prices - Array of stock prices, i.e. [7, 6, 4, 3, 1] * @param {function(): void} visit - Visiting callback to calculate the number of iterations. * @return {number} - The maximum profit */ const dpBestTimeToBuySellStocks = (prices, visit = () => {}) => { visit(); let lastBuy = -prices[0]; let lastSold = 0; for (let day = 1; day < prices.length; day += 1) { visit(); const curBuy = Math.max(lastBuy, lastSold - prices[day]); const curSold = Math.max(lastSold, lastBuy + prices[day]); lastBuy = curBuy; lastSold = curSold; } return lastSold; }; export default dpBestTimeToBuySellStocks;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/accumulatorBestTimeToBuySellStocks.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/accumulatorBestTimeToBuySellStocks.js
/** * Finds the maximum profit from selling and buying the stocks. * ACCUMULATOR APPROACH. * * @param {number[]} prices - Array of stock prices, i.e. [7, 6, 4, 3, 1] * @param {function(): void} visit - Visiting callback to calculate the number of iterations. * @return {number} - The maximum profit */ const accumulatorBestTimeToBuySellStocks = (prices, visit = () => {}) => { visit(); let profit = 0; for (let day = 1; day < prices.length; day += 1) { visit(); // Add the increase of the price from yesterday till today (if there was any) to the profit. profit += Math.max(prices[day] - prices[day - 1], 0); } return profit; }; export default accumulatorBestTimeToBuySellStocks;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/dqBestTimeToBuySellStocks.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/dqBestTimeToBuySellStocks.js
/** * Finds the maximum profit from selling and buying the stocks. * DIVIDE & CONQUER APPROACH. * * @param {number[]} prices - Array of stock prices, i.e. [7, 6, 4, 3, 1] * @param {function(): void} visit - Visiting callback to calculate the number of iterations. * @return {number} - The maximum profit */ const dqBestTimeToBuySellStocks = (prices, visit = () => {}) => { /** * Recursive implementation of the main function. It is hidden from the users. * * @param {boolean} buy - Whether we're allow to sell or to buy now * @param {number} day - Current day of trading (current index of prices array) * @returns {number} - Max profit from buying/selling */ const recursiveBuyerSeller = (buy, day) => { // Registering the recursive call visit to calculate the complexity. visit(); // Quitting the recursion if this is the last day of trading (prices array ended). if (day === prices.length) { return 0; } // If we're buying - we're loosing money (-1), if we're selling we're getting money (+1). const operationSign = buy ? -1 : +1; return Math.max( // Option 1: Don't do anything. recursiveBuyerSeller(buy, day + 1), // Option 2: Sell or Buy at the current price. operationSign * prices[day] + recursiveBuyerSeller(!buy, day + 1), ); }; const buy = true; const day = 0; return recursiveBuyerSeller(buy, day); }; export default dqBestTimeToBuySellStocks;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/peakvalleyBestTimeToBuySellStocks.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/peakvalleyBestTimeToBuySellStocks.js
/** * Finds the maximum profit from selling and buying the stocks. * PEAK VALLEY APPROACH. * * @param {number[]} prices - Array of stock prices, i.e. [7, 6, 4, 3, 1] * @param {function(): void} visit - Visiting callback to calculate the number of iterations. * @return {number} - The maximum profit */ const peakvalleyBestTimeToBuySellStocks = (prices, visit = () => {}) => { visit(); let profit = 0; let low = prices[0]; let high = prices[0]; prices.slice(1).forEach((currentPrice) => { visit(); if (currentPrice < high) { // If price went down, we need to sell. profit += high - low; low = currentPrice; high = currentPrice; } else { // If price went up, we don't need to do anything but increase a high record. high = currentPrice; } }); // In case if price went up during the last day // and we didn't have chance to sell inside the forEach loop. profit += high - low; return profit; }; export default peakvalleyBestTimeToBuySellStocks;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/accumulatorBestTimeToBuySellStocks.test.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/accumulatorBestTimeToBuySellStocks.test.js
import accumulatorBestTimeToBuySellStocks from '../accumulatorBestTimeToBuySellStocks'; describe('accumulatorBestTimeToBuySellStocks', () => { it('should find the best time to buy and sell stocks', () => { let visit; expect(accumulatorBestTimeToBuySellStocks([1, 5])).toEqual(4); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(1); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([1, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(2); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([5, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(2); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([1, 5, 10], visit)).toEqual(9); expect(visit).toHaveBeenCalledTimes(3); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([10, 1, 5, 20, 15, 21], visit)).toEqual(25); expect(visit).toHaveBeenCalledTimes(6); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([7, 1, 5, 3, 6, 4], visit)).toEqual(7); expect(visit).toHaveBeenCalledTimes(6); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([1, 2, 3, 4, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(5); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks([7, 6, 4, 3, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(5); visit = jest.fn(); expect(accumulatorBestTimeToBuySellStocks( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], visit, )).toEqual(19); expect(visit).toHaveBeenCalledTimes(20); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/dqBestTimeToBuySellStocks.test.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/dqBestTimeToBuySellStocks.test.js
import dqBestTimeToBuySellStocks from '../dqBestTimeToBuySellStocks'; describe('dqBestTimeToBuySellStocks', () => { it('should find the best time to buy and sell stocks', () => { let visit; expect(dqBestTimeToBuySellStocks([1, 5])).toEqual(4); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(3); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([1, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(7); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([5, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(7); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([1, 5, 10], visit)).toEqual(9); expect(visit).toHaveBeenCalledTimes(15); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([10, 1, 5, 20, 15, 21], visit)).toEqual(25); expect(visit).toHaveBeenCalledTimes(127); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([7, 1, 5, 3, 6, 4], visit)).toEqual(7); expect(visit).toHaveBeenCalledTimes(127); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([1, 2, 3, 4, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(63); visit = jest.fn(); expect(dqBestTimeToBuySellStocks([7, 6, 4, 3, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(63); visit = jest.fn(); expect(dqBestTimeToBuySellStocks( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], visit, )).toEqual(19); expect(visit).toHaveBeenCalledTimes(2097151); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/dpBestTimeToBuySellStocks.test.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/dpBestTimeToBuySellStocks.test.js
import dpBestTimeToBuySellStocks from '../dpBestTimeToBuySellStocks'; describe('dpBestTimeToBuySellStocks', () => { it('should find the best time to buy and sell stocks', () => { let visit; expect(dpBestTimeToBuySellStocks([1, 5])).toEqual(4); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(1); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([1, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(2); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([5, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(2); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([1, 5, 10], visit)).toEqual(9); expect(visit).toHaveBeenCalledTimes(3); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([10, 1, 5, 20, 15, 21], visit)).toEqual(25); expect(visit).toHaveBeenCalledTimes(6); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([7, 1, 5, 3, 6, 4], visit)).toEqual(7); expect(visit).toHaveBeenCalledTimes(6); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([1, 2, 3, 4, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(5); visit = jest.fn(); expect(dpBestTimeToBuySellStocks([7, 6, 4, 3, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(5); visit = jest.fn(); expect(dpBestTimeToBuySellStocks( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], visit, )).toEqual(19); expect(visit).toHaveBeenCalledTimes(20); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/peakvalleyBestTimeToBuySellStocks.test.js
src/algorithms/uncategorized/best-time-to-buy-sell-stocks/__tests__/peakvalleyBestTimeToBuySellStocks.test.js
import peakvalleyBestTimeToBuySellStocks from '../peakvalleyBestTimeToBuySellStocks'; describe('peakvalleyBestTimeToBuySellStocks', () => { it('should find the best time to buy and sell stocks', () => { let visit; expect(peakvalleyBestTimeToBuySellStocks([1, 5])).toEqual(4); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(1); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([1, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(2); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([5, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(2); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([1, 5, 10], visit)).toEqual(9); expect(visit).toHaveBeenCalledTimes(3); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([10, 1, 5, 20, 15, 21], visit)).toEqual(25); expect(visit).toHaveBeenCalledTimes(6); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([7, 1, 5, 3, 6, 4], visit)).toEqual(7); expect(visit).toHaveBeenCalledTimes(6); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([1, 2, 3, 4, 5], visit)).toEqual(4); expect(visit).toHaveBeenCalledTimes(5); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks([7, 6, 4, 3, 1], visit)).toEqual(0); expect(visit).toHaveBeenCalledTimes(5); visit = jest.fn(); expect(peakvalleyBestTimeToBuySellStocks( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], visit, )).toEqual(19); expect(visit).toHaveBeenCalledTimes(20); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseDP.js
src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseDP.js
/** * Recursive Staircase Problem (Dynamic Programming Solution). * * @param {number} stairsNum - Number of stairs to climb on. * @return {number} - Number of ways to climb a staircase. */ export default function recursiveStaircaseDP(stairsNum) { if (stairsNum < 0) { // There is no way to go down - you climb the stairs only upwards. return 0; } // Init the steps vector that will hold all possible ways to get to the corresponding step. const steps = new Array(stairsNum + 1).fill(0); // Init the number of ways to get to the 0th, 1st and 2nd steps. steps[0] = 0; steps[1] = 1; steps[2] = 2; if (stairsNum <= 2) { // Return the number of ways to get to the 0th or 1st or 2nd steps. return steps[stairsNum]; } // Calculate every next step based on two previous ones. for (let currentStep = 3; currentStep <= stairsNum; currentStep += 1) { steps[currentStep] = steps[currentStep - 1] + steps[currentStep - 2]; } // Return possible ways to get to the requested step. return steps[stairsNum]; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseMEM.js
src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseMEM.js
/** * Recursive Staircase Problem (Recursive Solution With Memoization). * * @param {number} totalStairs - Number of stairs to climb on. * @return {number} - Number of ways to climb a staircase. */ export default function recursiveStaircaseMEM(totalStairs) { // Memo table that will hold all recursively calculated results to avoid calculating them // over and over again. const memo = []; // Recursive closure. const getSteps = (stairsNum) => { if (stairsNum <= 0) { // There is no way to go down - you climb the stairs only upwards. // Also if you're standing on the ground floor that you don't need to do any further steps. return 0; } if (stairsNum === 1) { // There is only one way to go to the first step. return 1; } if (stairsNum === 2) { // There are two ways to get to the second steps: (1 + 1) or (2). return 2; } // Avoid recursion for the steps that we've calculated recently. if (memo[stairsNum]) { return memo[stairsNum]; } // Sum up how many steps we need to take after doing one step up with the number of // steps we need to take after doing two steps up. memo[stairsNum] = getSteps(stairsNum - 1) + getSteps(stairsNum - 2); return memo[stairsNum]; }; // Return possible ways to get to the requested step. return getSteps(totalStairs); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseIT.js
src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseIT.js
/** * Recursive Staircase Problem (Iterative Solution). * * @param {number} stairsNum - Number of stairs to climb on. * @return {number} - Number of ways to climb a staircase. */ export default function recursiveStaircaseIT(stairsNum) { if (stairsNum <= 0) { // There is no way to go down - you climb the stairs only upwards. // Also you don't need to do anything to stay on the 0th step. return 0; } // Init the number of ways to get to the 0th, 1st and 2nd steps. const steps = [1, 2]; if (stairsNum <= 2) { // Return the number of possible ways of how to get to the 1st or 2nd steps. return steps[stairsNum - 1]; } // Calculate the number of ways to get to the n'th step based on previous ones. // Comparing to Dynamic Programming solution we don't store info for all the steps but // rather for two previous ones only. for (let currentStep = 3; currentStep <= stairsNum; currentStep += 1) { [steps[0], steps[1]] = [steps[1], steps[0] + steps[1]]; } // Return possible ways to get to the requested step. return steps[1]; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseBF.js
src/algorithms/uncategorized/recursive-staircase/recursiveStaircaseBF.js
/** * Recursive Staircase Problem (Brute Force Solution). * * @param {number} stairsNum - Number of stairs to climb on. * @return {number} - Number of ways to climb a staircase. */ export default function recursiveStaircaseBF(stairsNum) { if (stairsNum <= 0) { // There is no way to go down - you climb the stairs only upwards. // Also if you're standing on the ground floor that you don't need to do any further steps. return 0; } if (stairsNum === 1) { // There is only one way to go to the first step. return 1; } if (stairsNum === 2) { // There are two ways to get to the second steps: (1 + 1) or (2). return 2; } // Sum up how many steps we need to take after doing one step up with the number of // steps we need to take after doing two steps up. return recursiveStaircaseBF(stairsNum - 1) + recursiveStaircaseBF(stairsNum - 2); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseBF.test.js
src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseBF.test.js
import recursiveStaircaseBF from '../recursiveStaircaseBF'; describe('recursiveStaircaseBF', () => { it('should calculate number of variants using Brute Force solution', () => { expect(recursiveStaircaseBF(-1)).toBe(0); expect(recursiveStaircaseBF(0)).toBe(0); expect(recursiveStaircaseBF(1)).toBe(1); expect(recursiveStaircaseBF(2)).toBe(2); expect(recursiveStaircaseBF(3)).toBe(3); expect(recursiveStaircaseBF(4)).toBe(5); expect(recursiveStaircaseBF(5)).toBe(8); expect(recursiveStaircaseBF(6)).toBe(13); expect(recursiveStaircaseBF(7)).toBe(21); expect(recursiveStaircaseBF(8)).toBe(34); expect(recursiveStaircaseBF(9)).toBe(55); expect(recursiveStaircaseBF(10)).toBe(89); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseMEM.test.js
src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseMEM.test.js
import recursiveStaircaseMEM from '../recursiveStaircaseMEM'; describe('recursiveStaircaseMEM', () => { it('should calculate number of variants using Brute Force with Memoization', () => { expect(recursiveStaircaseMEM(-1)).toBe(0); expect(recursiveStaircaseMEM(0)).toBe(0); expect(recursiveStaircaseMEM(1)).toBe(1); expect(recursiveStaircaseMEM(2)).toBe(2); expect(recursiveStaircaseMEM(3)).toBe(3); expect(recursiveStaircaseMEM(4)).toBe(5); expect(recursiveStaircaseMEM(5)).toBe(8); expect(recursiveStaircaseMEM(6)).toBe(13); expect(recursiveStaircaseMEM(7)).toBe(21); expect(recursiveStaircaseMEM(8)).toBe(34); expect(recursiveStaircaseMEM(9)).toBe(55); expect(recursiveStaircaseMEM(10)).toBe(89); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseIT.test.js
src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseIT.test.js
import recursiveStaircaseIT from '../recursiveStaircaseIT'; describe('recursiveStaircaseIT', () => { it('should calculate number of variants using Iterative solution', () => { expect(recursiveStaircaseIT(-1)).toBe(0); expect(recursiveStaircaseIT(0)).toBe(0); expect(recursiveStaircaseIT(1)).toBe(1); expect(recursiveStaircaseIT(2)).toBe(2); expect(recursiveStaircaseIT(3)).toBe(3); expect(recursiveStaircaseIT(4)).toBe(5); expect(recursiveStaircaseIT(5)).toBe(8); expect(recursiveStaircaseIT(6)).toBe(13); expect(recursiveStaircaseIT(7)).toBe(21); expect(recursiveStaircaseIT(8)).toBe(34); expect(recursiveStaircaseIT(9)).toBe(55); expect(recursiveStaircaseIT(10)).toBe(89); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseDP.test.js
src/algorithms/uncategorized/recursive-staircase/__test__/recursiveStaircaseDP.test.js
import recursiveStaircaseDP from '../recursiveStaircaseDP'; describe('recursiveStaircaseDP', () => { it('should calculate number of variants using Dynamic Programming solution', () => { expect(recursiveStaircaseDP(-1)).toBe(0); expect(recursiveStaircaseDP(0)).toBe(0); expect(recursiveStaircaseDP(1)).toBe(1); expect(recursiveStaircaseDP(2)).toBe(2); expect(recursiveStaircaseDP(3)).toBe(3); expect(recursiveStaircaseDP(4)).toBe(5); expect(recursiveStaircaseDP(5)).toBe(8); expect(recursiveStaircaseDP(6)).toBe(13); expect(recursiveStaircaseDP(7)).toBe(21); expect(recursiveStaircaseDP(8)).toBe(34); expect(recursiveStaircaseDP(9)).toBe(55); expect(recursiveStaircaseDP(10)).toBe(89); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/dpTopDownJumpGame.js
src/algorithms/uncategorized/jump-game/dpTopDownJumpGame.js
/** * DYNAMIC PROGRAMMING TOP-DOWN approach of solving Jump Game. * * This comes out as an optimisation of BACKTRACKING approach. * * It relies on the observation that once we determine that a certain * index is good / bad, this result will never change. This means that * we can store the result and not need to recompute it every time. * * We call a position in the array a "good" one if starting at that * position, we can reach the last index. Otherwise, that index * is called a "bad" one. * * @param {number[]} numbers - array of possible jump length. * @param {number} startIndex - index from where we start jumping. * @param {number[]} currentJumps - current jumps path. * @param {boolean[]} cellsGoodness - holds information about whether cell is "good" or "bad" * @return {boolean} */ export default function dpTopDownJumpGame( numbers, startIndex = 0, currentJumps = [], cellsGoodness = [], ) { if (startIndex === numbers.length - 1) { // We've jumped directly to last cell. This situation is a solution. return true; } // Init cell goodness table if it is empty. // This is DYNAMIC PROGRAMMING feature. const currentCellsGoodness = [...cellsGoodness]; if (!currentCellsGoodness.length) { numbers.forEach(() => currentCellsGoodness.push(undefined)); // Mark the last cell as "good" one since it is where we ultimately want to get. currentCellsGoodness[cellsGoodness.length - 1] = true; } // Check what the longest jump we could make from current position. // We don't need to jump beyond the array. const maxJumpLength = Math.min( numbers[startIndex], // Jump is within array. numbers.length - 1 - startIndex, // Jump goes beyond array. ); // Let's start jumping from startIndex and see whether any // jump is successful and has reached the end of the array. for (let jumpLength = maxJumpLength; jumpLength > 0; jumpLength -= 1) { // Try next jump. const nextIndex = startIndex + jumpLength; // Jump only into "good" or "unknown" cells. // This is top-down dynamic programming optimisation of backtracking algorithm. if (currentCellsGoodness[nextIndex] !== false) { currentJumps.push(nextIndex); const isJumpSuccessful = dpTopDownJumpGame( numbers, nextIndex, currentJumps, currentCellsGoodness, ); // Check if current jump was successful. if (isJumpSuccessful) { return true; } // BACKTRACKING. // If previous jump wasn't successful then retreat and try the next one. currentJumps.pop(); // Mark current cell as "bad" to avoid its deep visiting later. currentCellsGoodness[nextIndex] = false; } } return false; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/greedyJumpGame.js
src/algorithms/uncategorized/jump-game/greedyJumpGame.js
/** * GREEDY approach of solving Jump Game. * * This comes out as an optimisation of DYNAMIC PROGRAMMING BOTTOM_UP approach. * * Once we have our code in the bottom-up state, we can make one final, * important observation. From a given position, when we try to see if * we can jump to a GOOD position, we only ever use one - the first one. * In other words, the left-most one. If we keep track of this left-most * GOOD position as a separate variable, we can avoid searching for it * in the array. Not only that, but we can stop using the array altogether. * * We call a position in the array a "good" one if starting at that * position, we can reach the last index. Otherwise, that index * is called a "bad" one. * * @param {number[]} numbers - array of possible jump length. * @return {boolean} */ export default function greedyJumpGame(numbers) { // The "good" cell is a cell from which we may jump to the last cell of the numbers array. // The last cell in numbers array is for sure the "good" one since it is our goal to reach. let leftGoodPosition = numbers.length - 1; // Go through all numbers from right to left. for (let numberIndex = numbers.length - 2; numberIndex >= 0; numberIndex -= 1) { // If we can reach the "good" cell from the current one then for sure the current // one is also "good". Since after all we'll be able to reach the end of the array // from it. const maxCurrentJumpLength = numberIndex + numbers[numberIndex]; if (maxCurrentJumpLength >= leftGoodPosition) { leftGoodPosition = numberIndex; } } // If the most left "good" position is the zero's one then we may say that it IS // possible jump to the end of the array from the first cell; return leftGoodPosition === 0; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/dpBottomUpJumpGame.js
src/algorithms/uncategorized/jump-game/dpBottomUpJumpGame.js
/** * DYNAMIC PROGRAMMING BOTTOM-UP approach of solving Jump Game. * * This comes out as an optimisation of DYNAMIC PROGRAMMING TOP-DOWN approach. * * The observation to make here is that we only ever jump to the right. * This means that if we start from the right of the array, every time we * will query a position to our right, that position has already be * determined as being GOOD or BAD. This means we don't need to recurse * anymore, as we will always hit the memo table. * * We call a position in the array a "good" one if starting at that * position, we can reach the last index. Otherwise, that index * is called a "bad" one. * * @param {number[]} numbers - array of possible jump length. * @return {boolean} */ export default function dpBottomUpJumpGame(numbers) { // Init cells goodness table. const cellsGoodness = Array(numbers.length).fill(undefined); // Mark the last cell as "good" one since it is where we ultimately want to get. cellsGoodness[cellsGoodness.length - 1] = true; // Go throw all cells starting from the one before the last // one (since the last one is "good" already) and fill cellsGoodness table. for (let cellIndex = numbers.length - 2; cellIndex >= 0; cellIndex -= 1) { const maxJumpLength = Math.min( numbers[cellIndex], numbers.length - 1 - cellIndex, ); for (let jumpLength = maxJumpLength; jumpLength > 0; jumpLength -= 1) { const nextIndex = cellIndex + jumpLength; if (cellsGoodness[nextIndex] === true) { cellsGoodness[cellIndex] = true; // Once we detected that current cell is good one we don't need to // do further cells checking. break; } } } // Now, if the zero's cell is good one then we can jump from it to the end of the array. return cellsGoodness[0] === true; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/backtrackingJumpGame.js
src/algorithms/uncategorized/jump-game/backtrackingJumpGame.js
/** * BACKTRACKING approach of solving Jump Game. * * This is the inefficient solution where we try every single jump * pattern that takes us from the first position to the last. * We start from the first position and jump to every index that * is reachable. We repeat the process until last index is reached. * When stuck, backtrack. * * @param {number[]} numbers - array of possible jump length. * @param {number} startIndex - index from where we start jumping. * @param {number[]} currentJumps - current jumps path. * @return {boolean} */ export default function backtrackingJumpGame(numbers, startIndex = 0, currentJumps = []) { if (startIndex === numbers.length - 1) { // We've jumped directly to last cell. This situation is a solution. return true; } // Check what the longest jump we could make from current position. // We don't need to jump beyond the array. const maxJumpLength = Math.min( numbers[startIndex], // Jump is within array. numbers.length - 1 - startIndex, // Jump goes beyond array. ); // Let's start jumping from startIndex and see whether any // jump is successful and has reached the end of the array. for (let jumpLength = maxJumpLength; jumpLength > 0; jumpLength -= 1) { // Try next jump. const nextIndex = startIndex + jumpLength; currentJumps.push(nextIndex); const isJumpSuccessful = backtrackingJumpGame(numbers, nextIndex, currentJumps); // Check if current jump was successful. if (isJumpSuccessful) { return true; } // BACKTRACKING. // If previous jump wasn't successful then retreat and try the next one. currentJumps.pop(); } return false; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/__test__/dpTopDownJumpGame.test.js
src/algorithms/uncategorized/jump-game/__test__/dpTopDownJumpGame.test.js
import dpTopDownJumpGame from '../dpTopDownJumpGame'; describe('dpTopDownJumpGame', () => { it('should solve Jump Game problem in top-down dynamic programming manner', () => { expect(dpTopDownJumpGame([1, 0])).toBe(true); expect(dpTopDownJumpGame([100, 0])).toBe(true); expect(dpTopDownJumpGame([2, 3, 1, 1, 4])).toBe(true); expect(dpTopDownJumpGame([1, 1, 1, 1, 1])).toBe(true); expect(dpTopDownJumpGame([1, 1, 1, 10, 1])).toBe(true); expect(dpTopDownJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); expect(dpTopDownJumpGame([1, 0, 1])).toBe(false); expect(dpTopDownJumpGame([3, 2, 1, 0, 4])).toBe(false); expect(dpTopDownJumpGame([0, 0, 0, 0, 0])).toBe(false); expect(dpTopDownJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/__test__/dpBottomUpJumpGame.test.js
src/algorithms/uncategorized/jump-game/__test__/dpBottomUpJumpGame.test.js
import dpBottomUpJumpGame from '../dpBottomUpJumpGame'; describe('dpBottomUpJumpGame', () => { it('should solve Jump Game problem in bottom-up dynamic programming manner', () => { expect(dpBottomUpJumpGame([1, 0])).toBe(true); expect(dpBottomUpJumpGame([100, 0])).toBe(true); expect(dpBottomUpJumpGame([2, 3, 1, 1, 4])).toBe(true); expect(dpBottomUpJumpGame([1, 1, 1, 1, 1])).toBe(true); expect(dpBottomUpJumpGame([1, 1, 1, 10, 1])).toBe(true); expect(dpBottomUpJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); expect(dpBottomUpJumpGame([1, 0, 1])).toBe(false); expect(dpBottomUpJumpGame([3, 2, 1, 0, 4])).toBe(false); expect(dpBottomUpJumpGame([0, 0, 0, 0, 0])).toBe(false); expect(dpBottomUpJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/__test__/backtrackingJumpGame.test.js
src/algorithms/uncategorized/jump-game/__test__/backtrackingJumpGame.test.js
import backtrackingJumpGame from '../backtrackingJumpGame'; describe('backtrackingJumpGame', () => { it('should solve Jump Game problem in backtracking manner', () => { expect(backtrackingJumpGame([1, 0])).toBe(true); expect(backtrackingJumpGame([100, 0])).toBe(true); expect(backtrackingJumpGame([2, 3, 1, 1, 4])).toBe(true); expect(backtrackingJumpGame([1, 1, 1, 1, 1])).toBe(true); expect(backtrackingJumpGame([1, 1, 1, 10, 1])).toBe(true); expect(backtrackingJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); expect(backtrackingJumpGame([1, 0, 1])).toBe(false); expect(backtrackingJumpGame([3, 2, 1, 0, 4])).toBe(false); expect(backtrackingJumpGame([0, 0, 0, 0, 0])).toBe(false); expect(backtrackingJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/jump-game/__test__/greedyJumpGame.test.js
src/algorithms/uncategorized/jump-game/__test__/greedyJumpGame.test.js
import greedyJumpGame from '../greedyJumpGame'; describe('greedyJumpGame', () => { it('should solve Jump Game problem in greedy manner', () => { expect(greedyJumpGame([1, 0])).toBe(true); expect(greedyJumpGame([100, 0])).toBe(true); expect(greedyJumpGame([2, 3, 1, 1, 4])).toBe(true); expect(greedyJumpGame([1, 1, 1, 1, 1])).toBe(true); expect(greedyJumpGame([1, 1, 1, 10, 1])).toBe(true); expect(greedyJumpGame([1, 5, 2, 1, 0, 2, 0])).toBe(true); expect(greedyJumpGame([1, 0, 1])).toBe(false); expect(greedyJumpGame([3, 2, 1, 0, 4])).toBe(false); expect(greedyJumpGame([0, 0, 0, 0, 0])).toBe(false); expect(greedyJumpGame([5, 4, 3, 2, 1, 0, 0])).toBe(false); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/unique-paths/uniquePaths.js
src/algorithms/uncategorized/unique-paths/uniquePaths.js
import pascalTriangle from '../../math/pascal-triangle/pascalTriangle'; /** * @param {number} width * @param {number} height * @return {number} */ export default function uniquePaths(width, height) { const pascalLine = width + height - 2; const pascalLinePosition = Math.min(width, height) - 1; return pascalTriangle(pascalLine)[pascalLinePosition]; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/unique-paths/btUniquePaths.js
src/algorithms/uncategorized/unique-paths/btUniquePaths.js
/** * BACKTRACKING approach of solving Unique Paths problem. * * @param {number} width - Width of the board. * @param {number} height - Height of the board. * @param {number[][]} steps - The steps that have been already made. * @param {number} uniqueSteps - Total number of unique steps. * @return {number} - Number of unique paths. */ export default function btUniquePaths(width, height, steps = [[0, 0]], uniqueSteps = 0) { // Fetch current position on board. const currentPos = steps[steps.length - 1]; // Check if we've reached the end. if (currentPos[0] === width - 1 && currentPos[1] === height - 1) { // In case if we've reached the end let's increase total // number of unique steps. return uniqueSteps + 1; } // Let's calculate how many unique path we will have // by going right and by going down. let rightUniqueSteps = 0; let downUniqueSteps = 0; // Do right step if possible. if (currentPos[0] < width - 1) { steps.push([ currentPos[0] + 1, currentPos[1], ]); // Calculate how many unique paths we'll get by moving right. rightUniqueSteps = btUniquePaths(width, height, steps, uniqueSteps); // BACKTRACK and try another move. steps.pop(); } // Do down step if possible. if (currentPos[1] < height - 1) { steps.push([ currentPos[0], currentPos[1] + 1, ]); // Calculate how many unique paths we'll get by moving down. downUniqueSteps = btUniquePaths(width, height, steps, uniqueSteps); // BACKTRACK and try another move. steps.pop(); } // Total amount of unique steps will be equal to total amount of // unique steps by going right plus total amount of unique steps // by going down. return rightUniqueSteps + downUniqueSteps; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/unique-paths/dpUniquePaths.js
src/algorithms/uncategorized/unique-paths/dpUniquePaths.js
/** * DYNAMIC PROGRAMMING approach of solving Unique Paths problem. * * @param {number} width - Width of the board. * @param {number} height - Height of the board. * @return {number} - Number of unique paths. */ export default function dpUniquePaths(width, height) { // Init board. const board = Array(height).fill(null).map(() => { return Array(width).fill(0); }); // Base case. // There is only one way of getting to board[0][any] and // there is also only one way of getting to board[any][0]. // This is because we have a restriction of moving right // and down only. for (let rowIndex = 0; rowIndex < height; rowIndex += 1) { for (let columnIndex = 0; columnIndex < width; columnIndex += 1) { if (rowIndex === 0 || columnIndex === 0) { board[rowIndex][columnIndex] = 1; } } } // Now, since we have this restriction of moving only to the right // and down we might say that number of unique paths to the current // cell is a sum of numbers of unique paths to the cell above the // current one and to the cell to the left of current one. for (let rowIndex = 1; rowIndex < height; rowIndex += 1) { for (let columnIndex = 1; columnIndex < width; columnIndex += 1) { const uniquesFromTop = board[rowIndex - 1][columnIndex]; const uniquesFromLeft = board[rowIndex][columnIndex - 1]; board[rowIndex][columnIndex] = uniquesFromTop + uniquesFromLeft; } } return board[height - 1][width - 1]; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/unique-paths/__test__/dpUniquePaths.test.js
src/algorithms/uncategorized/unique-paths/__test__/dpUniquePaths.test.js
import dpUniquePaths from '../dpUniquePaths'; describe('dpUniquePaths', () => { it('should find the number of unique paths on board', () => { expect(dpUniquePaths(3, 2)).toBe(3); expect(dpUniquePaths(7, 3)).toBe(28); expect(dpUniquePaths(3, 7)).toBe(28); expect(dpUniquePaths(10, 10)).toBe(48620); expect(dpUniquePaths(100, 1)).toBe(1); expect(dpUniquePaths(1, 100)).toBe(1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/unique-paths/__test__/uniquePaths.test.js
src/algorithms/uncategorized/unique-paths/__test__/uniquePaths.test.js
import uniquePaths from '../uniquePaths'; describe('uniquePaths', () => { it('should find the number of unique paths on board', () => { expect(uniquePaths(3, 2)).toBe(3); expect(uniquePaths(7, 3)).toBe(28); expect(uniquePaths(3, 7)).toBe(28); expect(uniquePaths(10, 10)).toBe(48620); expect(uniquePaths(100, 1)).toBe(1); expect(uniquePaths(1, 100)).toBe(1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/uncategorized/unique-paths/__test__/btUniquePaths.test.js
src/algorithms/uncategorized/unique-paths/__test__/btUniquePaths.test.js
import btUniquePaths from '../btUniquePaths'; describe('btUniquePaths', () => { it('should find the number of unique paths on board', () => { expect(btUniquePaths(3, 2)).toBe(3); expect(btUniquePaths(7, 3)).toBe(28); expect(btUniquePaths(3, 7)).toBe(28); expect(btUniquePaths(10, 10)).toBe(48620); expect(btUniquePaths(100, 1)).toBe(1); expect(btUniquePaths(1, 100)).toBe(1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/MinHeap.js
src/data-structures/heap/MinHeap.js
import Heap from './Heap'; export default class MinHeap extends Heap { /** * Checks if pair of heap elements is in correct order. * For MinHeap the first element must be always smaller or equal. * For MaxHeap the first element must be always bigger or equal. * * @param {*} firstElement * @param {*} secondElement * @return {boolean} */ pairIsInCorrectOrder(firstElement, secondElement) { return this.compare.lessThanOrEqual(firstElement, secondElement); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/MaxHeapAdhoc.js
src/data-structures/heap/MaxHeapAdhoc.js
/** * The minimalistic (ad hoc) version of a MaxHeap data structure that doesn't have * external dependencies and that is easy to copy-paste and use during the * coding interview if allowed by the interviewer (since many data * structures in JS are missing). */ class MaxHeapAdhoc { constructor(heap = []) { this.heap = []; heap.forEach(this.add); } add(num) { this.heap.push(num); this.heapifyUp(); } peek() { return this.heap[0]; } poll() { if (this.heap.length === 0) return undefined; const top = this.heap[0]; this.heap[0] = this.heap[this.heap.length - 1]; this.heap.pop(); this.heapifyDown(); return top; } isEmpty() { return this.heap.length === 0; } toString() { return this.heap.join(','); } heapifyUp() { let nodeIndex = this.heap.length - 1; while (nodeIndex > 0) { const parentIndex = this.getParentIndex(nodeIndex); if (this.heap[parentIndex] >= this.heap[nodeIndex]) break; this.swap(parentIndex, nodeIndex); nodeIndex = parentIndex; } } heapifyDown() { let nodeIndex = 0; while ( ( this.hasLeftChild(nodeIndex) && this.heap[nodeIndex] < this.leftChild(nodeIndex) ) || ( this.hasRightChild(nodeIndex) && this.heap[nodeIndex] < this.rightChild(nodeIndex) ) ) { const leftIndex = this.getLeftChildIndex(nodeIndex); const rightIndex = this.getRightChildIndex(nodeIndex); const left = this.leftChild(nodeIndex); const right = this.rightChild(nodeIndex); if (this.hasLeftChild(nodeIndex) && this.hasRightChild(nodeIndex)) { if (left >= right) { this.swap(leftIndex, nodeIndex); nodeIndex = leftIndex; } else { this.swap(rightIndex, nodeIndex); nodeIndex = rightIndex; } } else if (this.hasLeftChild(nodeIndex)) { this.swap(leftIndex, nodeIndex); nodeIndex = leftIndex; } } } getLeftChildIndex(parentIndex) { return (2 * parentIndex) + 1; } getRightChildIndex(parentIndex) { return (2 * parentIndex) + 2; } getParentIndex(childIndex) { return Math.floor((childIndex - 1) / 2); } hasLeftChild(parentIndex) { return this.getLeftChildIndex(parentIndex) < this.heap.length; } hasRightChild(parentIndex) { return this.getRightChildIndex(parentIndex) < this.heap.length; } leftChild(parentIndex) { return this.heap[this.getLeftChildIndex(parentIndex)]; } rightChild(parentIndex) { return this.heap[this.getRightChildIndex(parentIndex)]; } swap(indexOne, indexTwo) { const tmp = this.heap[indexTwo]; this.heap[indexTwo] = this.heap[indexOne]; this.heap[indexOne] = tmp; } } export default MaxHeapAdhoc;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/MinHeapAdhoc.js
src/data-structures/heap/MinHeapAdhoc.js
/** * The minimalistic (ad hoc) version of a MinHeap data structure that doesn't have * external dependencies and that is easy to copy-paste and use during the * coding interview if allowed by the interviewer (since many data * structures in JS are missing). */ class MinHeapAdhoc { constructor(heap = []) { this.heap = []; heap.forEach(this.add); } add(num) { this.heap.push(num); this.heapifyUp(); } peek() { return this.heap[0]; } poll() { if (this.heap.length === 0) return undefined; const top = this.heap[0]; this.heap[0] = this.heap[this.heap.length - 1]; this.heap.pop(); this.heapifyDown(); return top; } isEmpty() { return this.heap.length === 0; } toString() { return this.heap.join(','); } heapifyUp() { let nodeIndex = this.heap.length - 1; while (nodeIndex > 0) { const parentIndex = this.getParentIndex(nodeIndex); if (this.heap[parentIndex] <= this.heap[nodeIndex]) break; this.swap(parentIndex, nodeIndex); nodeIndex = parentIndex; } } heapifyDown() { let nodeIndex = 0; while ( ( this.hasLeftChild(nodeIndex) && this.heap[nodeIndex] > this.leftChild(nodeIndex) ) || ( this.hasRightChild(nodeIndex) && this.heap[nodeIndex] > this.rightChild(nodeIndex) ) ) { const leftIndex = this.getLeftChildIndex(nodeIndex); const rightIndex = this.getRightChildIndex(nodeIndex); const left = this.leftChild(nodeIndex); const right = this.rightChild(nodeIndex); if (this.hasLeftChild(nodeIndex) && this.hasRightChild(nodeIndex)) { if (left <= right) { this.swap(leftIndex, nodeIndex); nodeIndex = leftIndex; } else { this.swap(rightIndex, nodeIndex); nodeIndex = rightIndex; } } else if (this.hasLeftChild(nodeIndex)) { this.swap(leftIndex, nodeIndex); nodeIndex = leftIndex; } } } getLeftChildIndex(parentIndex) { return 2 * parentIndex + 1; } getRightChildIndex(parentIndex) { return 2 * parentIndex + 2; } getParentIndex(childIndex) { return Math.floor((childIndex - 1) / 2); } hasLeftChild(parentIndex) { return this.getLeftChildIndex(parentIndex) < this.heap.length; } hasRightChild(parentIndex) { return this.getRightChildIndex(parentIndex) < this.heap.length; } leftChild(parentIndex) { return this.heap[this.getLeftChildIndex(parentIndex)]; } rightChild(parentIndex) { return this.heap[this.getRightChildIndex(parentIndex)]; } swap(indexOne, indexTwo) { const tmp = this.heap[indexTwo]; this.heap[indexTwo] = this.heap[indexOne]; this.heap[indexOne] = tmp; } } export default MinHeapAdhoc;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/MaxHeap.js
src/data-structures/heap/MaxHeap.js
import Heap from './Heap'; export default class MaxHeap extends Heap { /** * Checks if pair of heap elements is in correct order. * For MinHeap the first element must be always smaller or equal. * For MaxHeap the first element must be always bigger or equal. * * @param {*} firstElement * @param {*} secondElement * @return {boolean} */ pairIsInCorrectOrder(firstElement, secondElement) { return this.compare.greaterThanOrEqual(firstElement, secondElement); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/Heap.js
src/data-structures/heap/Heap.js
import Comparator from '../../utils/comparator/Comparator'; /** * Parent class for Min and Max Heaps. */ export default class Heap { /** * @constructs Heap * @param {Function} [comparatorFunction] */ constructor(comparatorFunction) { if (new.target === Heap) { throw new TypeError('Cannot construct Heap instance directly'); } // Array representation of the heap. this.heapContainer = []; this.compare = new Comparator(comparatorFunction); } /** * @param {number} parentIndex * @return {number} */ getLeftChildIndex(parentIndex) { return (2 * parentIndex) + 1; } /** * @param {number} parentIndex * @return {number} */ getRightChildIndex(parentIndex) { return (2 * parentIndex) + 2; } /** * @param {number} childIndex * @return {number} */ getParentIndex(childIndex) { return Math.floor((childIndex - 1) / 2); } /** * @param {number} childIndex * @return {boolean} */ hasParent(childIndex) { return this.getParentIndex(childIndex) >= 0; } /** * @param {number} parentIndex * @return {boolean} */ hasLeftChild(parentIndex) { return this.getLeftChildIndex(parentIndex) < this.heapContainer.length; } /** * @param {number} parentIndex * @return {boolean} */ hasRightChild(parentIndex) { return this.getRightChildIndex(parentIndex) < this.heapContainer.length; } /** * @param {number} parentIndex * @return {*} */ leftChild(parentIndex) { return this.heapContainer[this.getLeftChildIndex(parentIndex)]; } /** * @param {number} parentIndex * @return {*} */ rightChild(parentIndex) { return this.heapContainer[this.getRightChildIndex(parentIndex)]; } /** * @param {number} childIndex * @return {*} */ parent(childIndex) { return this.heapContainer[this.getParentIndex(childIndex)]; } /** * @param {number} indexOne * @param {number} indexTwo */ swap(indexOne, indexTwo) { const tmp = this.heapContainer[indexTwo]; this.heapContainer[indexTwo] = this.heapContainer[indexOne]; this.heapContainer[indexOne] = tmp; } /** * @return {*} */ peek() { if (this.heapContainer.length === 0) { return null; } return this.heapContainer[0]; } /** * @return {*} */ poll() { if (this.heapContainer.length === 0) { return null; } if (this.heapContainer.length === 1) { return this.heapContainer.pop(); } const item = this.heapContainer[0]; // Move the last element from the end to the head. this.heapContainer[0] = this.heapContainer.pop(); this.heapifyDown(); return item; } /** * @param {*} item * @return {Heap} */ add(item) { this.heapContainer.push(item); this.heapifyUp(); return this; } /** * @param {*} item * @param {Comparator} [comparator] * @return {Heap} */ remove(item, comparator = this.compare) { // Find number of items to remove. const numberOfItemsToRemove = this.find(item, comparator).length; for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) { // We need to find item index to remove each time after removal since // indices are being changed after each heapify process. const indexToRemove = this.find(item, comparator).pop(); // If we need to remove last child in the heap then just remove it. // There is no need to heapify the heap afterwards. if (indexToRemove === (this.heapContainer.length - 1)) { this.heapContainer.pop(); } else { // Move last element in heap to the vacant (removed) position. this.heapContainer[indexToRemove] = this.heapContainer.pop(); // Get parent. const parentItem = this.parent(indexToRemove); // If there is no parent or parent is in correct order with the node // we're going to delete then heapify down. Otherwise heapify up. if ( this.hasLeftChild(indexToRemove) && ( !parentItem || this.pairIsInCorrectOrder(parentItem, this.heapContainer[indexToRemove]) ) ) { this.heapifyDown(indexToRemove); } else { this.heapifyUp(indexToRemove); } } } return this; } /** * @param {*} item * @param {Comparator} [comparator] * @return {Number[]} */ find(item, comparator = this.compare) { const foundItemIndices = []; for (let itemIndex = 0; itemIndex < this.heapContainer.length; itemIndex += 1) { if (comparator.equal(item, this.heapContainer[itemIndex])) { foundItemIndices.push(itemIndex); } } return foundItemIndices; } /** * @return {boolean} */ isEmpty() { return !this.heapContainer.length; } /** * @return {string} */ toString() { return this.heapContainer.toString(); } /** * @param {number} [customStartIndex] */ heapifyUp(customStartIndex) { // Take the last element (last in array or the bottom left in a tree) // in the heap container and lift it up until it is in the correct // order with respect to its parent element. let currentIndex = customStartIndex || this.heapContainer.length - 1; while ( this.hasParent(currentIndex) && !this.pairIsInCorrectOrder(this.parent(currentIndex), this.heapContainer[currentIndex]) ) { this.swap(currentIndex, this.getParentIndex(currentIndex)); currentIndex = this.getParentIndex(currentIndex); } } /** * @param {number} [customStartIndex] */ heapifyDown(customStartIndex = 0) { // Compare the parent element to its children and swap parent with the appropriate // child (smallest child for MinHeap, largest child for MaxHeap). // Do the same for next children after swap. let currentIndex = customStartIndex; let nextIndex = null; while (this.hasLeftChild(currentIndex)) { if ( this.hasRightChild(currentIndex) && this.pairIsInCorrectOrder(this.rightChild(currentIndex), this.leftChild(currentIndex)) ) { nextIndex = this.getRightChildIndex(currentIndex); } else { nextIndex = this.getLeftChildIndex(currentIndex); } if (this.pairIsInCorrectOrder( this.heapContainer[currentIndex], this.heapContainer[nextIndex], )) { break; } this.swap(currentIndex, nextIndex); currentIndex = nextIndex; } } /** * Checks if pair of heap elements is in correct order. * For MinHeap the first element must be always smaller or equal. * For MaxHeap the first element must be always bigger or equal. * * @param {*} firstElement * @param {*} secondElement * @return {boolean} */ /* istanbul ignore next */ pairIsInCorrectOrder(firstElement, secondElement) { throw new Error(` You have to implement heap pair comparison method for ${firstElement} and ${secondElement} values. `); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/__test__/MinHeap.test.js
src/data-structures/heap/__test__/MinHeap.test.js
import MinHeap from '../MinHeap'; import Comparator from '../../../utils/comparator/Comparator'; describe('MinHeap', () => { it('should create an empty min heap', () => { const minHeap = new MinHeap(); expect(minHeap).toBeDefined(); expect(minHeap.peek()).toBeNull(); expect(minHeap.isEmpty()).toBe(true); }); it('should add items to the heap and heapify it up', () => { const minHeap = new MinHeap(); minHeap.add(5); expect(minHeap.isEmpty()).toBe(false); expect(minHeap.peek()).toBe(5); expect(minHeap.toString()).toBe('5'); minHeap.add(3); expect(minHeap.peek()).toBe(3); expect(minHeap.toString()).toBe('3,5'); minHeap.add(10); expect(minHeap.peek()).toBe(3); expect(minHeap.toString()).toBe('3,5,10'); minHeap.add(1); expect(minHeap.peek()).toBe(1); expect(minHeap.toString()).toBe('1,3,10,5'); minHeap.add(1); expect(minHeap.peek()).toBe(1); expect(minHeap.toString()).toBe('1,1,10,5,3'); expect(minHeap.poll()).toBe(1); expect(minHeap.toString()).toBe('1,3,10,5'); expect(minHeap.poll()).toBe(1); expect(minHeap.toString()).toBe('3,5,10'); expect(minHeap.poll()).toBe(3); expect(minHeap.toString()).toBe('5,10'); }); it('should poll items from the heap and heapify it down', () => { const minHeap = new MinHeap(); minHeap.add(5); minHeap.add(3); minHeap.add(10); minHeap.add(11); minHeap.add(1); expect(minHeap.toString()).toBe('1,3,10,11,5'); expect(minHeap.poll()).toBe(1); expect(minHeap.toString()).toBe('3,5,10,11'); expect(minHeap.poll()).toBe(3); expect(minHeap.toString()).toBe('5,11,10'); expect(minHeap.poll()).toBe(5); expect(minHeap.toString()).toBe('10,11'); expect(minHeap.poll()).toBe(10); expect(minHeap.toString()).toBe('11'); expect(minHeap.poll()).toBe(11); expect(minHeap.toString()).toBe(''); expect(minHeap.poll()).toBeNull(); expect(minHeap.toString()).toBe(''); }); it('should heapify down through the right branch as well', () => { const minHeap = new MinHeap(); minHeap.add(3); minHeap.add(12); minHeap.add(10); expect(minHeap.toString()).toBe('3,12,10'); minHeap.add(11); expect(minHeap.toString()).toBe('3,11,10,12'); expect(minHeap.poll()).toBe(3); expect(minHeap.toString()).toBe('10,11,12'); }); it('should be possible to find item indices in heap', () => { const minHeap = new MinHeap(); minHeap.add(3); minHeap.add(12); minHeap.add(10); minHeap.add(11); minHeap.add(11); expect(minHeap.toString()).toBe('3,11,10,12,11'); expect(minHeap.find(5)).toEqual([]); expect(minHeap.find(3)).toEqual([0]); expect(minHeap.find(11)).toEqual([1, 4]); }); it('should be possible to remove items from heap with heapify down', () => { const minHeap = new MinHeap(); minHeap.add(3); minHeap.add(12); minHeap.add(10); minHeap.add(11); minHeap.add(11); expect(minHeap.toString()).toBe('3,11,10,12,11'); expect(minHeap.remove(3).toString()).toEqual('10,11,11,12'); expect(minHeap.remove(3).peek()).toEqual(10); expect(minHeap.remove(11).toString()).toEqual('10,12'); expect(minHeap.remove(3).peek()).toEqual(10); }); it('should be possible to remove items from heap with heapify up', () => { const minHeap = new MinHeap(); minHeap.add(3); minHeap.add(10); minHeap.add(5); minHeap.add(6); minHeap.add(7); minHeap.add(4); minHeap.add(6); minHeap.add(8); minHeap.add(2); minHeap.add(1); expect(minHeap.toString()).toBe('1,2,4,6,3,5,6,10,8,7'); expect(minHeap.remove(8).toString()).toEqual('1,2,4,6,3,5,6,10,7'); expect(minHeap.remove(7).toString()).toEqual('1,2,4,6,3,5,6,10'); expect(minHeap.remove(1).toString()).toEqual('2,3,4,6,10,5,6'); expect(minHeap.remove(2).toString()).toEqual('3,6,4,6,10,5'); expect(minHeap.remove(6).toString()).toEqual('3,5,4,10'); expect(minHeap.remove(10).toString()).toEqual('3,5,4'); expect(minHeap.remove(5).toString()).toEqual('3,4'); expect(minHeap.remove(3).toString()).toEqual('4'); expect(minHeap.remove(4).toString()).toEqual(''); }); it('should be possible to remove items from heap with custom finding comparator', () => { const minHeap = new MinHeap(); minHeap.add('dddd'); minHeap.add('ccc'); minHeap.add('bb'); minHeap.add('a'); expect(minHeap.toString()).toBe('a,bb,ccc,dddd'); const comparator = new Comparator((a, b) => { if (a.length === b.length) { return 0; } return a.length < b.length ? -1 : 1; }); minHeap.remove('hey', comparator); expect(minHeap.toString()).toBe('a,bb,dddd'); }); it('should remove values from heap and correctly re-order the tree', () => { const minHeap = new MinHeap(); minHeap.add(1); minHeap.add(2); minHeap.add(3); minHeap.add(4); minHeap.add(5); minHeap.add(6); minHeap.add(7); minHeap.add(8); minHeap.add(9); expect(minHeap.toString()).toBe('1,2,3,4,5,6,7,8,9'); minHeap.remove(2); expect(minHeap.toString()).toBe('1,4,3,8,5,6,7,9'); minHeap.remove(4); expect(minHeap.toString()).toBe('1,5,3,8,9,6,7'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/__test__/Heap.test.js
src/data-structures/heap/__test__/Heap.test.js
import Heap from '../Heap'; describe('Heap', () => { it('should not allow to create instance of the Heap directly', () => { const instantiateHeap = () => { const heap = new Heap(); heap.add(5); }; expect(instantiateHeap).toThrow(); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/__test__/MaxHeap.test.js
src/data-structures/heap/__test__/MaxHeap.test.js
import MaxHeap from '../MaxHeap'; import Comparator from '../../../utils/comparator/Comparator'; describe('MaxHeap', () => { it('should create an empty max heap', () => { const maxHeap = new MaxHeap(); expect(maxHeap).toBeDefined(); expect(maxHeap.peek()).toBeNull(); expect(maxHeap.isEmpty()).toBe(true); }); it('should add items to the heap and heapify it up', () => { const maxHeap = new MaxHeap(); maxHeap.add(5); expect(maxHeap.isEmpty()).toBe(false); expect(maxHeap.peek()).toBe(5); expect(maxHeap.toString()).toBe('5'); maxHeap.add(3); expect(maxHeap.peek()).toBe(5); expect(maxHeap.toString()).toBe('5,3'); maxHeap.add(10); expect(maxHeap.peek()).toBe(10); expect(maxHeap.toString()).toBe('10,3,5'); maxHeap.add(1); expect(maxHeap.peek()).toBe(10); expect(maxHeap.toString()).toBe('10,3,5,1'); maxHeap.add(1); expect(maxHeap.peek()).toBe(10); expect(maxHeap.toString()).toBe('10,3,5,1,1'); expect(maxHeap.poll()).toBe(10); expect(maxHeap.toString()).toBe('5,3,1,1'); expect(maxHeap.poll()).toBe(5); expect(maxHeap.toString()).toBe('3,1,1'); expect(maxHeap.poll()).toBe(3); expect(maxHeap.toString()).toBe('1,1'); }); it('should poll items from the heap and heapify it down', () => { const maxHeap = new MaxHeap(); maxHeap.add(5); maxHeap.add(3); maxHeap.add(10); maxHeap.add(11); maxHeap.add(1); expect(maxHeap.toString()).toBe('11,10,5,3,1'); expect(maxHeap.poll()).toBe(11); expect(maxHeap.toString()).toBe('10,3,5,1'); expect(maxHeap.poll()).toBe(10); expect(maxHeap.toString()).toBe('5,3,1'); expect(maxHeap.poll()).toBe(5); expect(maxHeap.toString()).toBe('3,1'); expect(maxHeap.poll()).toBe(3); expect(maxHeap.toString()).toBe('1'); expect(maxHeap.poll()).toBe(1); expect(maxHeap.toString()).toBe(''); expect(maxHeap.poll()).toBeNull(); expect(maxHeap.toString()).toBe(''); }); it('should heapify down through the right branch as well', () => { const maxHeap = new MaxHeap(); maxHeap.add(3); maxHeap.add(12); maxHeap.add(10); expect(maxHeap.toString()).toBe('12,3,10'); maxHeap.add(11); expect(maxHeap.toString()).toBe('12,11,10,3'); expect(maxHeap.poll()).toBe(12); expect(maxHeap.toString()).toBe('11,3,10'); }); it('should be possible to find item indices in heap', () => { const maxHeap = new MaxHeap(); maxHeap.add(3); maxHeap.add(12); maxHeap.add(10); maxHeap.add(11); maxHeap.add(11); expect(maxHeap.toString()).toBe('12,11,10,3,11'); expect(maxHeap.find(5)).toEqual([]); expect(maxHeap.find(12)).toEqual([0]); expect(maxHeap.find(11)).toEqual([1, 4]); }); it('should be possible to remove items from heap with heapify down', () => { const maxHeap = new MaxHeap(); maxHeap.add(3); maxHeap.add(12); maxHeap.add(10); maxHeap.add(11); maxHeap.add(11); expect(maxHeap.toString()).toBe('12,11,10,3,11'); expect(maxHeap.remove(12).toString()).toEqual('11,11,10,3'); expect(maxHeap.remove(12).peek()).toEqual(11); expect(maxHeap.remove(11).toString()).toEqual('10,3'); expect(maxHeap.remove(10).peek()).toEqual(3); }); it('should be possible to remove items from heap with heapify up', () => { const maxHeap = new MaxHeap(); maxHeap.add(3); maxHeap.add(10); maxHeap.add(5); maxHeap.add(6); maxHeap.add(7); maxHeap.add(4); maxHeap.add(6); maxHeap.add(8); maxHeap.add(2); maxHeap.add(1); expect(maxHeap.toString()).toBe('10,8,6,7,6,4,5,3,2,1'); expect(maxHeap.remove(4).toString()).toEqual('10,8,6,7,6,1,5,3,2'); expect(maxHeap.remove(3).toString()).toEqual('10,8,6,7,6,1,5,2'); expect(maxHeap.remove(5).toString()).toEqual('10,8,6,7,6,1,2'); expect(maxHeap.remove(10).toString()).toEqual('8,7,6,2,6,1'); expect(maxHeap.remove(6).toString()).toEqual('8,7,1,2'); expect(maxHeap.remove(2).toString()).toEqual('8,7,1'); expect(maxHeap.remove(1).toString()).toEqual('8,7'); expect(maxHeap.remove(7).toString()).toEqual('8'); expect(maxHeap.remove(8).toString()).toEqual(''); }); it('should be possible to remove items from heap with custom finding comparator', () => { const maxHeap = new MaxHeap(); maxHeap.add('a'); maxHeap.add('bb'); maxHeap.add('ccc'); maxHeap.add('dddd'); expect(maxHeap.toString()).toBe('dddd,ccc,bb,a'); const comparator = new Comparator((a, b) => { if (a.length === b.length) { return 0; } return a.length < b.length ? -1 : 1; }); maxHeap.remove('hey', comparator); expect(maxHeap.toString()).toBe('dddd,a,bb'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/__test__/MinHeapAdhoc.test.js
src/data-structures/heap/__test__/MinHeapAdhoc.test.js
import MinHeapAdhoc from '../MinHeapAdhoc'; describe('MinHeapAdhoc', () => { it('should create an empty min heap', () => { const minHeap = new MinHeapAdhoc(); expect(minHeap).toBeDefined(); expect(minHeap.peek()).toBe(undefined); expect(minHeap.isEmpty()).toBe(true); }); it('should add items to the heap and heapify it up', () => { const minHeap = new MinHeapAdhoc(); minHeap.add(5); expect(minHeap.isEmpty()).toBe(false); expect(minHeap.peek()).toBe(5); expect(minHeap.toString()).toBe('5'); minHeap.add(3); expect(minHeap.peek()).toBe(3); expect(minHeap.toString()).toBe('3,5'); minHeap.add(10); expect(minHeap.peek()).toBe(3); expect(minHeap.toString()).toBe('3,5,10'); minHeap.add(1); expect(minHeap.peek()).toBe(1); expect(minHeap.toString()).toBe('1,3,10,5'); minHeap.add(1); expect(minHeap.peek()).toBe(1); expect(minHeap.toString()).toBe('1,1,10,5,3'); expect(minHeap.poll()).toBe(1); expect(minHeap.toString()).toBe('1,3,10,5'); expect(minHeap.poll()).toBe(1); expect(minHeap.toString()).toBe('3,5,10'); expect(minHeap.poll()).toBe(3); expect(minHeap.toString()).toBe('5,10'); }); it('should poll items from the heap and heapify it down', () => { const minHeap = new MinHeapAdhoc(); minHeap.add(5); minHeap.add(3); minHeap.add(10); minHeap.add(11); minHeap.add(1); expect(minHeap.toString()).toBe('1,3,10,11,5'); expect(minHeap.poll()).toBe(1); expect(minHeap.toString()).toBe('3,5,10,11'); expect(minHeap.poll()).toBe(3); expect(minHeap.toString()).toBe('5,11,10'); expect(minHeap.poll()).toBe(5); expect(minHeap.toString()).toBe('10,11'); expect(minHeap.poll()).toBe(10); expect(minHeap.toString()).toBe('11'); expect(minHeap.poll()).toBe(11); expect(minHeap.toString()).toBe(''); expect(minHeap.poll()).toBe(undefined); expect(minHeap.toString()).toBe(''); }); it('should heapify down through the right branch as well', () => { const minHeap = new MinHeapAdhoc(); minHeap.add(3); minHeap.add(12); minHeap.add(10); expect(minHeap.toString()).toBe('3,12,10'); minHeap.add(11); expect(minHeap.toString()).toBe('3,11,10,12'); expect(minHeap.poll()).toBe(3); expect(minHeap.toString()).toBe('10,11,12'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/heap/__test__/MaxHeapAdhoc.test.js
src/data-structures/heap/__test__/MaxHeapAdhoc.test.js
import MaxHeap from '../MaxHeapAdhoc'; describe('MaxHeapAdhoc', () => { it('should create an empty max heap', () => { const maxHeap = new MaxHeap(); expect(maxHeap).toBeDefined(); expect(maxHeap.peek()).toBe(undefined); expect(maxHeap.isEmpty()).toBe(true); }); it('should add items to the heap and heapify it up', () => { const maxHeap = new MaxHeap(); maxHeap.add(5); expect(maxHeap.isEmpty()).toBe(false); expect(maxHeap.peek()).toBe(5); expect(maxHeap.toString()).toBe('5'); maxHeap.add(3); expect(maxHeap.peek()).toBe(5); expect(maxHeap.toString()).toBe('5,3'); maxHeap.add(10); expect(maxHeap.peek()).toBe(10); expect(maxHeap.toString()).toBe('10,3,5'); maxHeap.add(1); expect(maxHeap.peek()).toBe(10); expect(maxHeap.toString()).toBe('10,3,5,1'); maxHeap.add(1); expect(maxHeap.peek()).toBe(10); expect(maxHeap.toString()).toBe('10,3,5,1,1'); expect(maxHeap.poll()).toBe(10); expect(maxHeap.toString()).toBe('5,3,1,1'); expect(maxHeap.poll()).toBe(5); expect(maxHeap.toString()).toBe('3,1,1'); expect(maxHeap.poll()).toBe(3); expect(maxHeap.toString()).toBe('1,1'); }); it('should poll items from the heap and heapify it down', () => { const maxHeap = new MaxHeap(); maxHeap.add(5); maxHeap.add(3); maxHeap.add(10); maxHeap.add(11); maxHeap.add(1); expect(maxHeap.toString()).toBe('11,10,5,3,1'); expect(maxHeap.poll()).toBe(11); expect(maxHeap.toString()).toBe('10,3,5,1'); expect(maxHeap.poll()).toBe(10); expect(maxHeap.toString()).toBe('5,3,1'); expect(maxHeap.poll()).toBe(5); expect(maxHeap.toString()).toBe('3,1'); expect(maxHeap.poll()).toBe(3); expect(maxHeap.toString()).toBe('1'); expect(maxHeap.poll()).toBe(1); expect(maxHeap.toString()).toBe(''); expect(maxHeap.poll()).toBe(undefined); expect(maxHeap.toString()).toBe(''); }); it('should heapify down through the right branch as well', () => { const maxHeap = new MaxHeap(); maxHeap.add(3); maxHeap.add(12); maxHeap.add(10); expect(maxHeap.toString()).toBe('12,3,10'); maxHeap.add(11); expect(maxHeap.toString()).toBe('12,11,10,3'); expect(maxHeap.poll()).toBe(12); expect(maxHeap.toString()).toBe('11,3,10'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/trie/Trie.js
src/data-structures/trie/Trie.js
import TrieNode from './TrieNode'; // Character that we will use for trie tree root. const HEAD_CHARACTER = '*'; export default class Trie { constructor() { this.head = new TrieNode(HEAD_CHARACTER); } /** * @param {string} word * @return {Trie} */ addWord(word) { const characters = Array.from(word); let currentNode = this.head; for (let charIndex = 0; charIndex < characters.length; charIndex += 1) { const isComplete = charIndex === characters.length - 1; currentNode = currentNode.addChild(characters[charIndex], isComplete); } return this; } /** * @param {string} word * @return {Trie} */ deleteWord(word) { const depthFirstDelete = (currentNode, charIndex = 0) => { if (charIndex >= word.length) { // Return if we're trying to delete the character that is out of word's scope. return; } const character = word[charIndex]; const nextNode = currentNode.getChild(character); if (nextNode == null) { // Return if we're trying to delete a word that has not been added to the Trie. return; } // Go deeper. depthFirstDelete(nextNode, charIndex + 1); // Since we're going to delete a word let's un-mark its last character isCompleteWord flag. if (charIndex === (word.length - 1)) { nextNode.isCompleteWord = false; } // childNode is deleted only if: // - childNode has NO children // - childNode.isCompleteWord === false currentNode.removeChild(character); }; // Start depth-first deletion from the head node. depthFirstDelete(this.head); return this; } /** * @param {string} word * @return {string[]} */ suggestNextCharacters(word) { const lastCharacter = this.getLastCharacterNode(word); if (!lastCharacter) { return null; } return lastCharacter.suggestChildren(); } /** * Check if complete word exists in Trie. * * @param {string} word * @return {boolean} */ doesWordExist(word) { const lastCharacter = this.getLastCharacterNode(word); return !!lastCharacter && lastCharacter.isCompleteWord; } /** * @param {string} word * @return {TrieNode} */ getLastCharacterNode(word) { const characters = Array.from(word); let currentNode = this.head; for (let charIndex = 0; charIndex < characters.length; charIndex += 1) { if (!currentNode.hasChild(characters[charIndex])) { return null; } currentNode = currentNode.getChild(characters[charIndex]); } return currentNode; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/trie/TrieNode.js
src/data-structures/trie/TrieNode.js
import HashTable from '../hash-table/HashTable'; export default class TrieNode { /** * @param {string} character * @param {boolean} isCompleteWord */ constructor(character, isCompleteWord = false) { this.character = character; this.isCompleteWord = isCompleteWord; this.children = new HashTable(); } /** * @param {string} character * @return {TrieNode} */ getChild(character) { return this.children.get(character); } /** * @param {string} character * @param {boolean} isCompleteWord * @return {TrieNode} */ addChild(character, isCompleteWord = false) { if (!this.children.has(character)) { this.children.set(character, new TrieNode(character, isCompleteWord)); } const childNode = this.children.get(character); // In cases similar to adding "car" after "carpet" we need to mark "r" character as complete. childNode.isCompleteWord = childNode.isCompleteWord || isCompleteWord; return childNode; } /** * @param {string} character * @return {TrieNode} */ removeChild(character) { const childNode = this.getChild(character); // Delete childNode only if: // - childNode has NO children, // - childNode.isCompleteWord === false. if ( childNode && !childNode.isCompleteWord && !childNode.hasChildren() ) { this.children.delete(character); } return this; } /** * @param {string} character * @return {boolean} */ hasChild(character) { return this.children.has(character); } /** * Check whether current TrieNode has children or not. * @return {boolean} */ hasChildren() { return this.children.getKeys().length !== 0; } /** * @return {string[]} */ suggestChildren() { return [...this.children.getKeys()]; } /** * @return {string} */ toString() { let childrenAsString = this.suggestChildren().toString(); childrenAsString = childrenAsString ? `:${childrenAsString}` : ''; const isCompleteString = this.isCompleteWord ? '*' : ''; return `${this.character}${isCompleteString}${childrenAsString}`; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/trie/__test__/TrieNode.test.js
src/data-structures/trie/__test__/TrieNode.test.js
import TrieNode from '../TrieNode'; describe('TrieNode', () => { it('should create trie node', () => { const trieNode = new TrieNode('c', true); expect(trieNode.character).toBe('c'); expect(trieNode.isCompleteWord).toBe(true); expect(trieNode.toString()).toBe('c*'); }); it('should add child nodes', () => { const trieNode = new TrieNode('c'); trieNode.addChild('a', true); trieNode.addChild('o'); expect(trieNode.toString()).toBe('c:a,o'); }); it('should get child nodes', () => { const trieNode = new TrieNode('c'); trieNode.addChild('a'); trieNode.addChild('o'); expect(trieNode.getChild('a').toString()).toBe('a'); expect(trieNode.getChild('a').character).toBe('a'); expect(trieNode.getChild('o').toString()).toBe('o'); expect(trieNode.getChild('b')).toBeUndefined(); }); it('should check if node has children', () => { const trieNode = new TrieNode('c'); expect(trieNode.hasChildren()).toBe(false); trieNode.addChild('a'); expect(trieNode.hasChildren()).toBe(true); }); it('should check if node has specific child', () => { const trieNode = new TrieNode('c'); trieNode.addChild('a'); trieNode.addChild('o'); expect(trieNode.hasChild('a')).toBe(true); expect(trieNode.hasChild('o')).toBe(true); expect(trieNode.hasChild('b')).toBe(false); }); it('should suggest next children', () => { const trieNode = new TrieNode('c'); trieNode.addChild('a'); trieNode.addChild('o'); expect(trieNode.suggestChildren()).toEqual(['a', 'o']); }); it('should delete child node if the child node has NO children', () => { const trieNode = new TrieNode('c'); trieNode.addChild('a'); expect(trieNode.hasChild('a')).toBe(true); trieNode.removeChild('a'); expect(trieNode.hasChild('a')).toBe(false); }); it('should NOT delete child node if the child node has children', () => { const trieNode = new TrieNode('c'); trieNode.addChild('a'); const childNode = trieNode.getChild('a'); childNode.addChild('r'); trieNode.removeChild('a'); expect(trieNode.hasChild('a')).toEqual(true); }); it('should NOT delete child node if the child node completes a word', () => { const trieNode = new TrieNode('c'); const IS_COMPLETE_WORD = true; trieNode.addChild('a', IS_COMPLETE_WORD); trieNode.removeChild('a'); expect(trieNode.hasChild('a')).toEqual(true); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/trie/__test__/Trie.test.js
src/data-structures/trie/__test__/Trie.test.js
import Trie from '../Trie'; describe('Trie', () => { it('should create trie', () => { const trie = new Trie(); expect(trie).toBeDefined(); expect(trie.head.toString()).toBe('*'); }); it('should add words to trie', () => { const trie = new Trie(); trie.addWord('cat'); expect(trie.head.toString()).toBe('*:c'); expect(trie.head.getChild('c').toString()).toBe('c:a'); trie.addWord('car'); expect(trie.head.toString()).toBe('*:c'); expect(trie.head.getChild('c').toString()).toBe('c:a'); expect(trie.head.getChild('c').getChild('a').toString()).toBe('a:t,r'); expect(trie.head.getChild('c').getChild('a').getChild('t').toString()).toBe('t*'); }); it('should delete words from trie', () => { const trie = new Trie(); trie.addWord('carpet'); trie.addWord('car'); trie.addWord('cat'); trie.addWord('cart'); expect(trie.doesWordExist('carpet')).toBe(true); expect(trie.doesWordExist('car')).toBe(true); expect(trie.doesWordExist('cart')).toBe(true); expect(trie.doesWordExist('cat')).toBe(true); // Try to delete not-existing word first. trie.deleteWord('carpool'); expect(trie.doesWordExist('carpet')).toBe(true); expect(trie.doesWordExist('car')).toBe(true); expect(trie.doesWordExist('cart')).toBe(true); expect(trie.doesWordExist('cat')).toBe(true); trie.deleteWord('carpet'); expect(trie.doesWordExist('carpet')).toEqual(false); expect(trie.doesWordExist('car')).toEqual(true); expect(trie.doesWordExist('cart')).toBe(true); expect(trie.doesWordExist('cat')).toBe(true); trie.deleteWord('cat'); expect(trie.doesWordExist('car')).toEqual(true); expect(trie.doesWordExist('cart')).toBe(true); expect(trie.doesWordExist('cat')).toBe(false); trie.deleteWord('car'); expect(trie.doesWordExist('car')).toEqual(false); expect(trie.doesWordExist('cart')).toBe(true); trie.deleteWord('cart'); expect(trie.doesWordExist('car')).toEqual(false); expect(trie.doesWordExist('cart')).toBe(false); }); it('should suggests next characters', () => { const trie = new Trie(); trie.addWord('cat'); trie.addWord('cats'); trie.addWord('car'); trie.addWord('caption'); expect(trie.suggestNextCharacters('ca')).toEqual(['t', 'r', 'p']); expect(trie.suggestNextCharacters('cat')).toEqual(['s']); expect(trie.suggestNextCharacters('cab')).toBeNull(); }); it('should check if word exists', () => { const trie = new Trie(); trie.addWord('cat'); trie.addWord('cats'); trie.addWord('carpet'); trie.addWord('car'); trie.addWord('caption'); expect(trie.doesWordExist('cat')).toBe(true); expect(trie.doesWordExist('cats')).toBe(true); expect(trie.doesWordExist('carpet')).toBe(true); expect(trie.doesWordExist('car')).toBe(true); expect(trie.doesWordExist('cap')).toBe(false); expect(trie.doesWordExist('call')).toBe(false); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/graph/GraphEdge.js
src/data-structures/graph/GraphEdge.js
export default class GraphEdge { /** * @param {GraphVertex} startVertex * @param {GraphVertex} endVertex * @param {number} [weight=0] * @param key */ constructor(startVertex, endVertex, weight = 0, key = null) { this.startVertex = startVertex; this.endVertex = endVertex; this.weight = weight; this.key = key; } getKey() { if (this.key) { return this.key; } const startVertexKey = this.startVertex.getKey(); const endVertexKey = this.endVertex.getKey(); this.key = `${startVertexKey}_${endVertexKey}`; return this.key; } /** * @return {GraphEdge} */ reverse() { const tmp = this.startVertex; this.startVertex = this.endVertex; this.endVertex = tmp; return this; } /** * @return {string} */ toString() { return this.getKey().toString(); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/graph/GraphVertex.js
src/data-structures/graph/GraphVertex.js
import LinkedList from '../linked-list/LinkedList'; export default class GraphVertex { /** * @param {*} value */ constructor(value) { if (value === undefined) { throw new Error('Graph vertex must have a value'); } /** * @param {GraphEdge} edgeA * @param {GraphEdge} edgeB */ const edgeComparator = (edgeA, edgeB) => { if (edgeA.getKey() === edgeB.getKey()) { return 0; } return edgeA.getKey() < edgeB.getKey() ? -1 : 1; }; // Normally you would store string value like vertex name. // But generally it may be any object as well this.value = value; this.edges = new LinkedList(edgeComparator); } /** * @param {GraphEdge} edge * @returns {GraphVertex} */ addEdge(edge) { this.edges.append(edge); return this; } /** * @param {GraphEdge} edge */ deleteEdge(edge) { this.edges.delete(edge); } /** * @returns {GraphVertex[]} */ getNeighbors() { const edges = this.edges.toArray(); /** @param {LinkedListNode} node */ const neighborsConverter = (node) => { return node.value.startVertex === this ? node.value.endVertex : node.value.startVertex; }; // Return either start or end vertex. // For undirected graphs it is possible that current vertex will be the end one. return edges.map(neighborsConverter); } /** * @return {GraphEdge[]} */ getEdges() { return this.edges.toArray().map((linkedListNode) => linkedListNode.value); } /** * @return {number} */ getDegree() { return this.edges.toArray().length; } /** * @param {GraphEdge} requiredEdge * @returns {boolean} */ hasEdge(requiredEdge) { const edgeNode = this.edges.find({ callback: (edge) => edge === requiredEdge, }); return !!edgeNode; } /** * @param {GraphVertex} vertex * @returns {boolean} */ hasNeighbor(vertex) { const vertexNode = this.edges.find({ callback: (edge) => edge.startVertex === vertex || edge.endVertex === vertex, }); return !!vertexNode; } /** * @param {GraphVertex} vertex * @returns {(GraphEdge|null)} */ findEdge(vertex) { const edgeFinder = (edge) => { return edge.startVertex === vertex || edge.endVertex === vertex; }; const edge = this.edges.find({ callback: edgeFinder }); return edge ? edge.value : null; } /** * @returns {string} */ getKey() { return this.value; } /** * @return {GraphVertex} */ deleteAllEdges() { this.getEdges().forEach((edge) => this.deleteEdge(edge)); return this; } /** * @param {function} [callback] * @returns {string} */ toString(callback) { return callback ? callback(this.value).toString() : this.value.toString(); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/graph/Graph.js
src/data-structures/graph/Graph.js
export default class Graph { /** * @param {boolean} isDirected */ constructor(isDirected = false) { this.vertices = {}; this.edges = {}; this.isDirected = isDirected; } /** * @param {GraphVertex} newVertex * @returns {Graph} */ addVertex(newVertex) { const key = newVertex.getKey(); if (this.vertices[key]) { throw new Error('Vertex has already been added before'); } this.vertices[key] = newVertex; return this; } /** * @param {string} vertexKey * @returns GraphVertex */ getVertexByKey(vertexKey) { return this.vertices[vertexKey]; } /** * @param {GraphVertex} vertex * @returns {GraphVertex[]} */ getNeighbors(vertex) { return vertex.getNeighbors(); } /** * @return {GraphVertex[]} */ getAllVertices() { return Object.values(this.vertices); } /** * @return {GraphEdge[]} */ getAllEdges() { return Object.values(this.edges); } /** * @param {GraphEdge} edge * @returns {Graph} */ addEdge(edge) { // Try to find and end start vertices. let startVertex = this.getVertexByKey(edge.startVertex.getKey()); let endVertex = this.getVertexByKey(edge.endVertex.getKey()); // Insert start vertex if it wasn't inserted. if (!startVertex) { this.addVertex(edge.startVertex); startVertex = this.getVertexByKey(edge.startVertex.getKey()); } // Insert end vertex if it wasn't inserted. if (!endVertex) { this.addVertex(edge.endVertex); endVertex = this.getVertexByKey(edge.endVertex.getKey()); } // Check if edge has been already added. if (this.edges[edge.getKey()]) { throw new Error('Edge has already been added before'); } else { this.edges[edge.getKey()] = edge; } // Add edge to the vertices. if (this.isDirected) { // If graph IS directed then add the edge only to start vertex. startVertex.addEdge(edge); } else { // If graph ISN'T directed then add the edge to both vertices. startVertex.addEdge(edge); endVertex.addEdge(edge); } return this; } /** * @param {GraphEdge} edge */ deleteEdge(edge) { // Delete edge from the list of edges. if (this.edges[edge.getKey()]) { delete this.edges[edge.getKey()]; } else { throw new Error('Edge not found in graph'); } // Try to find and end start vertices and delete edge from them. const startVertex = this.getVertexByKey(edge.startVertex.getKey()); const endVertex = this.getVertexByKey(edge.endVertex.getKey()); startVertex.deleteEdge(edge); endVertex.deleteEdge(edge); } /** * @param {GraphVertex} startVertex * @param {GraphVertex} endVertex * @return {(GraphEdge|null)} */ findEdge(startVertex, endVertex) { const vertex = this.getVertexByKey(startVertex.getKey()); if (!vertex) { return null; } return vertex.findEdge(endVertex); } /** * @return {number} */ getWeight() { return this.getAllEdges().reduce((weight, graphEdge) => { return weight + graphEdge.weight; }, 0); } /** * Reverse all the edges in directed graph. * @return {Graph} */ reverse() { /** @param {GraphEdge} edge */ this.getAllEdges().forEach((edge) => { // Delete straight edge from graph and from vertices. this.deleteEdge(edge); // Reverse the edge. edge.reverse(); // Add reversed edge back to the graph and its vertices. this.addEdge(edge); }); return this; } /** * @return {object} */ getVerticesIndices() { const verticesIndices = {}; this.getAllVertices().forEach((vertex, index) => { verticesIndices[vertex.getKey()] = index; }); return verticesIndices; } /** * @return {*[][]} */ getAdjacencyMatrix() { const vertices = this.getAllVertices(); const verticesIndices = this.getVerticesIndices(); // Init matrix with infinities meaning that there is no ways of // getting from one vertex to another yet. const adjacencyMatrix = Array(vertices.length).fill(null).map(() => { return Array(vertices.length).fill(Infinity); }); // Fill the columns. vertices.forEach((vertex, vertexIndex) => { vertex.getNeighbors().forEach((neighbor) => { const neighborIndex = verticesIndices[neighbor.getKey()]; adjacencyMatrix[vertexIndex][neighborIndex] = this.findEdge(vertex, neighbor).weight; }); }); return adjacencyMatrix; } /** * @return {string} */ toString() { return Object.keys(this.vertices).toString(); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/graph/__test__/GraphEdge.test.js
src/data-structures/graph/__test__/GraphEdge.test.js
import GraphEdge from '../GraphEdge'; import GraphVertex from '../GraphVertex'; describe('GraphEdge', () => { it('should create graph edge with default weight', () => { const startVertex = new GraphVertex('A'); const endVertex = new GraphVertex('B'); const edge = new GraphEdge(startVertex, endVertex); expect(edge.startVertex).toEqual(startVertex); expect(edge.endVertex).toEqual(endVertex); expect(edge.weight).toEqual(0); }); it('should create graph edge with predefined weight', () => { const startVertex = new GraphVertex('A'); const endVertex = new GraphVertex('B'); const edge = new GraphEdge(startVertex, endVertex, 10); expect(edge.startVertex).toEqual(startVertex); expect(edge.endVertex).toEqual(endVertex); expect(edge.weight).toEqual(10); }); it('should be possible to do edge reverse', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const edge = new GraphEdge(vertexA, vertexB, 10); expect(edge.startVertex).toEqual(vertexA); expect(edge.endVertex).toEqual(vertexB); expect(edge.weight).toEqual(10); edge.reverse(); expect(edge.startVertex).toEqual(vertexB); expect(edge.endVertex).toEqual(vertexA); expect(edge.weight).toEqual(10); }); it('should return edges names as key', () => { const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0); expect(edge.getKey()).toBe('A_B'); expect(edge.toString()).toBe('A_B'); }); it('should return custom key if defined', () => { const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0, 'custom_key'); expect(edge.getKey()).toEqual('custom_key'); expect(edge.toString()).toEqual('custom_key'); }); it('should execute toString on key when calling toString on edge', () => { const customKey = { toString() { return 'custom_key'; }, }; const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0, customKey); expect(edge.getKey()).toEqual(customKey); expect(edge.toString()).toEqual('custom_key'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false