📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

Overview

JavaScript Algorithms and Data Structures

CI codecov

This repository contains JavaScript based examples of many popular algorithms and data structures.

Each algorithm and data structure has its own separate README with related explanations and links for further reading (including ones to YouTube videos).

Read this in other languages: 简体中文, 繁體中文, 한국어, 日本語, Polski, Français, Español, Português, Русский, Türk, Italiana, Bahasa Indonesia, Українська, Arabic

Note that this project is meant to be used for learning and researching purposes only, and it is not meant to be used for production.

Data Structures

A data structure is a particular way of organizing and storing data in a computer so that it can be accessed and modified efficiently. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.

B - Beginner, A - Advanced

Algorithms

An algorithm is an unambiguous specification of how to solve a class of problems. It is a set of rules that precisely define a sequence of operations.

B - Beginner, A - Advanced

Algorithms by Topic

Algorithms by Paradigm

An algorithmic paradigm is a generic method or approach which underlies the design of a class of algorithms. It is an abstraction higher than the notion of an algorithm, just as an algorithm is an abstraction higher than a computer program.

How to use this repository

Install all dependencies

npm install

Run ESLint

You may want to run it to check code quality.

npm run lint

Run all tests

npm test

Run tests by name

npm test -- 'LinkedList'

Playground

You may play with data-structures and algorithms in ./src/playground/playground.js file and write tests for it in ./src/playground/__test__/playground.test.js.

Then just simply run the following command to test if your playground code works as expected:

npm test -- 'playground'

Useful Information

References

Data Structures and Algorithms on YouTube

Big O Notation

Big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows. On the chart below you may find most common orders of growth of algorithms specified in Big O notation.

Big O graphs

Source: Big O Cheat Sheet.

Below is the list of some of the most used Big O notations and their performance comparisons against different sizes of the input data.

Big O Notation Computations for 10 elements Computations for 100 elements Computations for 1000 elements
O(1) 1 1 1
O(log N) 3 6 9
O(N) 10 100 1000
O(N log N) 30 600 9000
O(N^2) 100 10000 1000000
O(2^N) 1024 1.26e+29 1.07e+301
O(N!) 3628800 9.3e+157 4.02e+2567

Data Structure Operations Complexity

Data Structure Access Search Insertion Deletion Comments
Array 1 n n n
Stack n n 1 1
Queue n n 1 1
Linked List n n 1 n
Hash Table - n n n In case of perfect hash function costs would be O(1)
Binary Search Tree n n n n In case of balanced tree costs would be O(log(n))
B-Tree log(n) log(n) log(n) log(n)
Red-Black Tree log(n) log(n) log(n) log(n)
AVL Tree log(n) log(n) log(n) log(n)
Bloom Filter - 1 1 - False positives are possible while searching

Array Sorting Algorithms Complexity

Name Best Average Worst Memory Stable Comments
Bubble sort n n2 n2 1 Yes
Insertion sort n n2 n2 1 Yes
Selection sort n2 n2 n2 1 No
Heap sort n log(n) n log(n) n log(n) 1 No
Merge sort n log(n) n log(n) n log(n) n Yes
Quick sort n log(n) n log(n) n2 log(n) No Quicksort is usually done in-place with O(log(n)) stack space
Shell sort n log(n) depends on gap sequence n (log(n))2 1 No
Counting sort n + r n + r n + r n + r Yes r - biggest number in array
Radix sort n * k n * k n * k n + k Yes k - length of longest key

Project Backers

You may support this project via ❤️ GitHub or ❤️ Patreon.

Folks who are backing this project ∑ = 0

Comments
  • German translation

    German translation

    hey hey, great project! I would like to make a german translation. So I have a reason to look deeper into the texts. I'll collect the information about the translation process from the other issues, but if I have questions I can ask them here, right?

    opened by denizbinay 14
  • quick sort problem

    quick sort problem

    i am writing quick sort algorthm, and when i testing my code, the result makes me confused.

    RangeError: Maximum call stack size exceeded at Array.push ()

    let arr = [0,-1,1,0,1,-1,100,23,17,56,39,47,23,-34,-56];

    export default function quickSort(array){
        let len = array.length;
        if(len <= 1) return array;
    
        let piviot = array.pop();
    
        let left = [], right = [];
        for (let i = 0; i < len; i++) {
            if(array[i] < piviot){
                left.push(array[i]);
            }
            else{
                right.push(array[i])
            }
        }
        return quickSort(left).concat(piviot,quickSort(right));
    }
    

    when i change for loop to forEach, problem is disappeared, but i don't know why.

    
    export default function quickSort(array){
        let len = array.length;
        if(len <= 1) return array;
    
        let piviot = array.pop();
    
        let left = [], right = [];
        array.forEach(item => {
            if(item < piviot){
                left.push(item)
            }
            else{
                right.push(item);
            }
        });
        return quickSort(left).concat(piviot,quickSort(right));
    }
    
    opened by Facefall 6
  • Add in-place sort to QuickSort.js

    Add in-place sort to QuickSort.js

    I've always been a big fan of the in-place variation of the Quicksort algorithm. Not sure if you were looking for variations on existing implementations, but I thought it was different enough to warrant a pull request if you are interested.

    It was also more performant when testing on arrays of 10,000 elements for integers between 0-10,000:

    /*
    const testTime = (callback) => {
    	let time1 = performance.now();
    	callback();
    	let time2 = performance.now();
    	return time2 - time1;
    };
    
    const arrOne = new Array(10000).fill(null).map(el => Math.floor(Math.random() * 10000));
    const arrTwo = new Array(10000).fill(null).map(el => Math.floor(Math.random() * 10000));
    
    const inPlace = testTime(() => QuickSort.sortInPlace(arrOne));
    const nonInPlace= testTime(() => QuickSort.sort(arrTwo));
    
    console.log(inPlace);
    //=>9.799999999813735
    
    console.log(nonInPlace);
    //=>50.00000004656613
    */
    
    opened by robtaussig 6
  • issue while running program

    issue while running program

    Hi i dont know why but i am not able to run your program , i am new to js please help me

    Error
    > [email protected] test ......\javascript-algorithms
    > jest "-t" "playground"
    
    'jest' is not recognized as an internal or external command,
    operable program or batch file.
    npm ERR! Test failed.  See above for more details.
    

    image

    opened by Krish-bhardwaj 5
  • Opening for Full Stack JS Developer

    Opening for Full Stack JS Developer

    Hello, Igor! I`ve checked your profile and I can see you work with Javascript. Our company has very interesting opportynity, please send me a message vie indicated email to discuss it. Have a great day!

    Sergiy, e-mail: [email protected]

    opened by SergB38 5
  • rabinKarp seems to miss some matches

    rabinKarp seems to miss some matches

    Hello,

    I recently tried to run some property based tests on the algorithms provided in javascript-algorithms. I discovered the following failing case with rabinKarp algorithm:

    expect(rabinKarp("^ !/'#'pp", " !/'#'pp")).toBe(2); // output: -1
    

    In order to find it, I used fast-check framework with the property:

    // for any strings a, b and c
    // rabinKarp(a + b + c, b) should be different from -1 (indeed b is a substring of a+b+c)
    fc.assert(
      fc.property(
        fc.string(), fc.string(), fc.string(),
        (a, b, c) => rabinKarp(a + b + c, b) !== -1
      )
    );
    

    I was not able to have a smaller example for this precise case :/

    bug 
    opened by dubzzz 5
  • AVL tree does not rebalance after removal

    AVL tree does not rebalance after removal

    Hi! Thanks for your project. I can't seem to find the removal algorithm in AVL tree: if it simply borrows the binary tree removal, it's incomplete. I was particularly interested in that, cause I have been looking for a removal procedure that doesn't mutate the nodes.

    Cheers.

    bug 
    opened by w8r 5
  • Getting every possible shortest path between two nodes

    Getting every possible shortest path between two nodes

    Getting every possible shortest path between two nodes using dijkstra algorithm ( ranked by best path ). Any one getting javascript code that would be awesome.

    opened by anand-010 4
  • Adds Portuguese (pt-BR) translation

    Adds Portuguese (pt-BR) translation

    Summary

    So I translated most of the content, with exception of the algorithms for now, to Portuguese, specifically to Brazilian Portuguese.

    If anythings needs to be change, just point out :)

    opened by themgoncalves 4
  • Added a useful resource

    Added a useful resource

    Adding a helpful link that discusses data structure in detail, I hope you will like this as it will add value to your repository and readers. Thank you.

    opened by Smith1161 0
  • Help =)

    Help =)

    Hello, I've been programming for about 7 years now, I stopped but now I want to go back more than 0 and learn everything again more on the SQL side, where should I start?

    opened by Dogzeca 0
  • Eu realmente não entendi

    Eu realmente não entendi

    Sou iniciante nessa área de programação e recentemente estou pesquisando/aprendendo sobre JavaScript/CSS/HTML, porém recentemente estou tendo um grande problema em um cod que era parar ser uma calculadora (bem básico, eu sei), porém o resultado simplesmente não sai e eu não encontro onde errei. CODIGO: test.txt

    opened by Hirasawa-San 1
Owner
Oleksii Trekhleb
Software Engineer at @uber
Oleksii Trekhleb
Create explorable explanations and interactive essays.

Tutorials | Examples | Docs | Chatroom | Mailing list | Twitter What is Idyll? For an introduction to Idyll, API reference, examples, and tutorials, p

Idyll 1.9k Dec 27, 2022
A lightweight jQuery plugin for collapsing and expanding long blocks of text with "Read more" and "Close" links.

Readmore.js V3 alpha I am deprecating the 2.x version of Readmore.js. A new version is coming soon! Check it out and help me test it! Readmore.js A sm

Jed Foster 1.5k Nov 30, 2022
Gmail-like client-side drafts and bit more. Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters.

Sisyphus Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters. Descriptio

Alexander Kaupanin 2k Dec 8, 2022
Free, open-source crypto trading bot, automated bitcoin / cryptocurrency trading software, algorithmic trading bots. Visually design your crypto trading bot, leveraging an integrated charting system, data-mining, backtesting, paper trading, and multi-server crypto bot deployments.

Free, open-source crypto trading bot, automated bitcoin / cryptocurrency trading software, algorithmic trading bots. Visually design your crypto trading bot, leveraging an integrated charting system, data-mining, backtesting, paper trading, and multi-server crypto bot deployments.

Superalgos 3.1k Jan 1, 2023
Lazy-loading images with data-* attributes

Echo.js Echo is a standalone JavaScript lazy-loading image micro-library. Echo is fast, 2KB, and uses HTML5 data-* attributes for simple. Check out a

Todd Motto 3.7k Dec 30, 2022
API routes are great for APIs, but for small projects where you have to access server data or hide application logic, you can just call a server function from the client.

API routes are great for APIs, but for small projects where you have to access server data or hide application logic, you can just call a server function from the client.

null 3 Mar 6, 2022
This web application retrieves real live data from the SpaceX API

This web application retrieves real live data from the SpaceX API. It provides commercial and scientific space travel services, by allowing users to book rockets and join selected space missions.

Sahar Abdel Samad 12 Aug 9, 2022
JavaScript Survey and Form Library

SurveyJS is a JavaScript Survey and Form Library. SurveyJS is a modern way to add surveys and forms to your website. It has versions for Angular, jQue

SurveyJS 3.5k Jan 1, 2023
Extensive math expression evaluator library for JavaScript and Node.js

?? Homepage Fcaljs is an extensive math expression evaluator library for JavaScript and Node.js. Using fcal, you can perform basic arithmetic, percent

Santhosh Kumar 93 Dec 19, 2022
An easy to use, yet advanced and fully customizable javascript/jQuery paginator plugin

anyPaginator An easy to use, yet advanced and fully customizable Javascript/jQuery paginator plugin. anyPaginator is a spinoff of the anyList project

Arne Morken 2 Feb 17, 2022
An arbitrary size Bit-Vector implementation in JavaScript

BitSet.js BitSet.js is an infinite Bit-Array (aka bit vector, bit string, bit set) implementation in JavaScript. That means that if you invert a bit v

Robert Eisele 207 Dec 9, 2022
SPOILER ALERT! A happy little bit of javascript to hide spoilers on your site.

SPOILER ALERT! Don't spoil it! Hide copy and images with a bit of SVG blur. Taste on mouseover. Eat on click. Do you publish spoilers? Do you wish you

Joshua Hull 473 Sep 27, 2022
⚡️ A resource to help figure out what JavaScript array method would be best to use at any given time

JavaScript Array Explorer When I was first learning array methods, I spent a lot of time digging through the docs to find the appropriate one, and I h

Sarah Drasner 2.6k Jan 2, 2023
🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API

Huge thanks to for sponsoring me! Ky is a tiny and elegant HTTP client based on the browser Fetch API Ky targets modern browsers and Deno. For older b

Sindre Sorhus 8.5k Jan 2, 2023
Vanilla JavaScript emoji picker component

Vanilla JavaScript emoji picker ?? Screenshot Demo and Documentation https://emoji-button.js.org Features ?? Vanilla JS, use with any framework ?? Use

Joe Attardi 1.1k Dec 31, 2022
This is my To-do-list project for my Javascript module at Microverse.

To do List This is a To do list project built for learning purposes. Built With HTML Bootstrap Javascript CSS HTML Webpack How to use it Clone the rep

Jonathas Tavares 4 Oct 8, 2021
A JavaScript, zero-dependency, super small version of IP2Location LITE country lookups.

A JavaScript, zero-dependency, super small version of IP2Location LITE country lookups.

Statsig 34 Dec 14, 2022
Shikimori.ts - JavaScript & TypeScript wrapper for shikimori.one

shikimori.ts shikimori.ts - JavaScript & TypeScript wrapper for shikimori.one Features Full TypeScript support Support all platforms Easy to use Table

null 5 Sep 15, 2022
This library was designed to be used in SPA framework wrappers for the FingerprintJS Pro Javascript Agent

Framework-agnostic SPA service wrapper. Use it to build a FingerprintJS Pro wrapper for your favorite framework.

FingerprintJS 12 Sep 3, 2022