Self Balancing BST in JavaScript
Last Updated :
28 Mar, 2023
A self-balancing binary search tree (BST) is a type of binary search tree that automatically keeps its height balanced in order to guarantee that operations such as searching, inserting, and deleting elements in the tree take less time on average.
How do self-balancing BSTs maintain height balance?
Self-balancing binary search trees (BSTs) maintain height balance by automatically reorganising the tree after every insertion or deletion operation. To balance a BST, we can use two common operations: right rotation and left rotation. These operations adjust the positions of nodes in the tree to ensure that the tree remains balanced.
Right Rotation: Right rotation is used to balance a tree when its left subtree is longer than its right subtree.
In a right rotation, we move the left child of the unbalanced node to the position of the unbalanced node, while making the unbalanced node the right child of its former left child.
For example, let's say we have a tree where node B is the root, and its left child A is taller than its right child C. In this case, we can perform a right rotation on node B as follows:
Example of right rotation
Left Rotation: Left rotation is used to balance a tree when its right subtree is longer than its left subtree.
In a left rotation, we move the right child of the unbalanced node to the position of the unbalanced node, while making the unbalanced node the left child of its former right child.
For example, let's say we have a tree where node B is the root, and its right child C is taller than its left child A. In this case, we can perform a left rotation on node B as follows:
Example of left rotationSome examples of self-balancing BST:
Some examples of self-balancing BSTs are:
Below we will check their implementation in Javascript language.
Implementation of AVL Tree in Javascript:
This implementation includes methods for inserting, searching, and deleting nodes from the AVL tree.
- The `height` method calculates the height of a given node, and
- the `balanceFactor` method calculates the difference in height between the left and right subtrees of a given node.
- The `rotateRight` and `rotateLeft` methods perform right and left rotations, respectively, to balance the tree.
- The `insertNode` method inserts a new node into the tree, and
- The `deleteNode` method removes a node from the tree.
- The `findMinNode` method finds the minimum node in a given subtree,
- The `searchNode` method searches for a node with a given value in the tree.
Below is the implementation of AVL Tree in Javascript.
JavaScript
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
this.height = 1;
}
}
class AVLTree {
constructor() {
this.root = null;
}
// get the height of a node
height(node) {
if (!node) return 0;
return node.height;
}
// get the balance factor of a node
balanceFactor(node) {
if (!node) return 0;
return this.height(node.left) - this.height(node.right);
}
// perform a right rotation
rotateRight(node) {
const leftNode = node.left;
const rightOfLeftNode = leftNode.right;
leftNode.right = node;
node.left = rightOfLeftNode;
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
leftNode.height =
Math.max(this.height(leftNode.left), this.height(leftNode.right)) + 1;
return leftNode;
}
// perform a left rotation
rotateLeft(node) {
const rightNode = node.right;
const leftOfRightNode = rightNode.left;
rightNode.left = node;
node.right = leftOfRightNode;
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
rightNode.height =
Math.max(this.height(rightNode.left), this.height(rightNode.right)) + 1;
return rightNode;
}
// insert a new node
insert(value) {
this.root = this.insertNode(this.root, value);
}
insertNode(node, value) {
if (!node) {
return new Node(value);
}
if (value < node.value) {
node.left = this.insertNode(node.left, value);
} else if (value > node.value) {
node.right = this.insertNode(node.right, value);
} else {
return node; // duplicate values are not allowed
}
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
const balance = this.balanceFactor(node);
if (balance > 1 && value < node.left.value) {
return this.rotateRight(node);
}
if (balance > 1 && value > node.left.value) {
node.left = this.rotateLeft(node.left);
return this.rotateRight(node);
}
if (balance < -1 && value > node.right.value) {
return this.rotateLeft(node);
}
if (balance < -1 && value < node.right.value) {
node.right = this.rotateRight(node.right);
return this.rotateLeft(node);
}
return node;
}
// search for a node
search(value) {
return this.searchNode(this.root, value);
}
searchNode(node, value) {
if (!node) return null;
if (value < node.value) {
return this.searchNode(node.left, value);
} else if (value > node.value) {
return this.searchNode(node.right, value);
} else {
return node;
}
}
// delete a node
delete(value) {
this.root = this.deleteNode(this.root, value);
}
deleteNode(node, value) {
if (!node) {
return null;
}
if (value < node.value) {
node.left = this.deleteNode(node.left, value);
} else if (value > node.value) {
node.right = this.deleteNode(node.right, value);
} else {
// node to be deleted has no children
if (!node.left && !node.right) {
node = null;
}
// node to be deleted has one child
else if (!node.left) {
node = node.right;
} else if (!node.right) {
node = node.left;
}
// node to be deleted has two children
else {
const minNode = this.findMinNode(node.right);
node.value = minNode.value;
node.right = this.deleteNode(node.right, minNode.value);
}
}
if (!node) return null;
node.height = Math.max(this.height(node.left), this.height(node.right)) + 1;
const balance = this.balanceFactor(node);
if (balance > 1 && this.balanceFactor(node.left) >= 0) {
return this.rotateRight(node);
}
if (balance > 1 && this.balanceFactor(node.left) < 0) {
node.left = this.rotateLeft(node.left);
return this.rotateRight(node);
}
if (balance < -1 && this.balanceFactor(node.right) <= 0) {
return this.rotateLeft(node);
}
if (balance < -1 && this.balanceFactor(node.right) > 0) {
node.right = this.rotateRight(node.right);
return this.rotateLeft(node);
}
return node;
}
// find the minimum node in a subtree
findMinNode(node) {
while (node && node.left) {
node = node.left;
}
return node;
}
}
// example usage
const tree = new AVLTree();
tree.insert(4);
tree.insert(2);
tree.insert(7);
tree.insert(1);
tree.insert(3);
tree.insert(5);
tree.insert(8);
tree.insert(6);
console.log(tree.search(5));
tree.delete(7);
console.log(tree.search(7));
Output:
Output of the above codeImplementation of Red-Black Tree in Javascript:
- The `insert()` method first inserts a new node using the `insertNode()` method (which is the same as in a regular binary search tree).
- Ihe `fixupInsert()` method fix any violations of the red-black properties that may have been introduced by the insertion.
- The `fixupInsert()` method checks three cases to determine how to fix the violation. In each case, it performs a rotation (either left or right) to re-balance the tree.
- The `rotateLeft()` and `rotateRight()` methods perform the actual rotations, and
- The `search()` method searches for a value in the tree.
- Finally, the `inOrderTraversal()` method traverses the tree in order and calls a callback function on each node.
Below is the implementation of Red-Black Tree.
JavaScript
// Define the color constants
const RED = "red";
const BLACK = "black";
class RBNode {
constructor(value) {
this.value = value;
this.color = RED;
this.left = null;
this.right = null;
this.parent = null;
}
isRed() {
return this.color === RED;
}
}
class RBTree {
constructor() {
this.root = null;
}
insert(value) {
const node = new RBNode(value);
// insert node like in a regular BST
this.root = this.insertNode(this.root, node);
// fix any violations of the red-black properties
this.fixupInsert(node);
}
insertNode(root, node) {
if (!root) {
return node;
}
if (node.value < root.value) {
root.left = this.insertNode(root.left, node);
root.left.parent = root;
} else {
root.right = this.insertNode(root.right, node);
root.right.parent = root;
}
return root;
}
fixupInsert(node) {
while (node.parent && node.parent.isRed()) {
if (node.parent === node.parent.parent.left) {
const uncle = node.parent.parent.right;
if (uncle && uncle.isRed()) {
// case 1: uncle is red
node.parent.color = BLACK;
uncle.color = BLACK;
node.parent.parent.color = RED;
node = node.parent.parent;
} else {
if (node === node.parent.right) {
// case 2: uncle is black and node is a right child
node = node.parent;
this.rotateLeft(node);
}
// case 3: uncle is black and node is a left child
node.parent.color = BLACK;
node.parent.parent.color = RED;
this.rotateRight(node.parent.parent);
}
} else {
const uncle = node.parent.parent.left;
if (uncle && uncle.isRed()) {
// case 1: uncle is red
node.parent.color = BLACK;
uncle.color = BLACK;
node.parent.parent.color = RED;
node = node.parent.parent;
} else {
if (node === node.parent.left) {
// case 2: uncle is black and node is a left child
node = node.parent;
this.rotateRight(node);
}
// case 3: uncle is black and node is a right child
node.parent.color = BLACK;
node.parent.parent.color = RED;
this.rotateLeft(node.parent.parent);
}
}
}
this.root.color = BLACK;
}
rotateLeft(node) {
const right = node.right;
node.right = right.left;
if (right.left) {
right.left.parent = node;
}
right.parent = node.parent;
if (!node.parent) {
this.root = right;
} else if (node === node.parent.left) {
node.parent.left = right;
} else {
node.parent.right = right;
}
right.left = node;
node.parent = right;
}
rotateRight(node) {
const left = node.left;
node.left = left.right;
if (left.right) {
left.right.parent = node;
}
left.parent = node.parent;
if (!node.parent) {
this.root = left;
} else if (node === node.parent.left) {
node.parent.left = left;
} else {
node.parent.right = left;
}
left.right = node;
node.parent = left;
}
// search for a value in the tree
search(value) {
let current = this.root;
while (current) {
if (value === current.value) {
return current;
} else if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return null;
}
// traverse the tree in order
inOrderTraversal(callback) {
this.inOrderTraversalNode(this.root, callback);
}
inOrderTraversalNode(node, callback) {
if (node) {
this.inOrderTraversalNode(node.left, callback);
callback(node);
this.inOrderTraversalNode(node.right, callback);
}
}
}
const tree = new RBTree();
tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(15);
tree.insert(5);
console.log("Inorder Traversal of the Red Black Tree: ");
tree.inOrderTraversal((node) => console.log(node.value));
OutputInorder Traversal of the Red Black Tree:
5
10
15
20
30
Implementation of Splay Tree in Javascript:
The splay tree is constructed in the same way as a binary search tree, but it is different in the way it is manipulated. Whenever an element is accessed, it is moved to the root of the tree by performing a series of rotations. This process is called splaying, and it helps to ensure that frequently accessed elements are located near the root of the tree, making them easier to access in future operations.
Here are the steps to implement a splay tree:
- Define a Node class to represent nodes in the tree. Each node should have a key, a value, a left child, and a right child.
- Define a SplayTree class to represent the tree itself. The tree should have a root property that points to the root node.
- Implement the basic operations of a binary search tree, such as insert, delete, and search. These operations should follow the standard algorithms for binary search trees, with the additional step of performing a splaying operation after the insertion, deletion, or search.
- Implement the splaying operation. The splaying operation should take a key as input and move the corresponding node to the root of the tree using a series of rotations. The rotations should be performed in a way that balances the tree and reduces its height.
Below is the implementation of the Splay Tree.
JavaScript
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
}
class SplayTree {
constructor() {
this.root = null;
}
splay(key) {
if (this.root == null) {
return;
}
let dummy = new Node(null, null);
let left = dummy;
let right = dummy;
let current = this.root;
while (true) {
if (key < current.key) {
if (current.left == null) {
break;
}
if (key < current.left.key) {
let temp = current.left;
current.left = temp.right;
temp.right = current;
current = temp;
if (current.left == null) {
break;
}
}
right.left = current;
right = current;
current = current.left;
} else if (key > current.key) {
if (current.right == null) {
break;
}
if (key > current.right.key) {
let temp = current.right;
current.right = temp.left;
temp.left = current;
current = temp;
if (current.right == null) {
break;
}
}
left.right = current;
left = current;
current = current.right;
} else {
break;
}
}
left.right = current.left;
right.left = current.right;
current.left = dummy.right;
current.right = dummy.left;
this.root = current;
}
insert(key, value) {
if (this.root == null) {
this.root = new Node(key, value);
return;
}
this.splay(key);
if (key < this.root.key) {
let node = new Node(key, value);
node.left = this.root.left;
node.right = this.root;
this.root.left = null;
this.root = node;
} else if (key > this.root.key) {
let node = new Node(key, value);
node.right = this.root.right;
node.left = this.root;
this.root.right = null;
this.root = node;
} else {
this.root.value = value;
}
}
search(key) {
if (this.root == null) {
return null;
}
this.splay(key);
if (this.root.key == key) {
return this.root.value;
} else {
return null;
}
}
delete(key) {
if (this.root == null) {
return;
}
this.splay(key);
if (this.root.key != key) {
return;
}
if (this.root.left == null) {
this.root = this.root.right;
} else {
let right = this.root.right;
this.root = this.root.left;
this.splay(key);
this.root.right = right;
}
}
}
const tree = new SplayTree();
// Insert some nodes
tree.insert(10, 'A');
tree.insert(20, 'B');
tree.insert(30, 'C');
tree.insert(15, 'D');
tree.insert(25, 'E');
// Search for a node
// Output: "B"
console.log(tree.search(20));
// Delete a node
tree.delete(15);
// Search for a deleted node
// Output: null
console.log(tree.search(15));
Output:
Output of the above code
Similar Reads
Learn Data Structures with Javascript | DSA using JavaScript Tutorial JavaScript (JS) is the most popular lightweight, interpreted programming language, and might be your first preference for Client-side as well as Server-side developments. But have you thought about using JavaScript for DSA? Learning Data Structures and Algorithms can be difficult when combined with
7 min read
Learn Algorithms with Javascript | DSA using JavaScript Tutorial This Algorithms with Javascript tutorial is designed to help you understand and implement fundamental algorithms using the versatile JavaScript programming language. Whether you are a beginner in programming or looking to enhance your algorithmic skills, this guide will walk you through essential co
15+ min read
Mathematical
JavaScript Program to Check for Palindrome NumberWe are going to learn about Palindrome Numbers in JavaScript. A palindrome number is a numerical sequence that reads the same forwards and backward, It remains unchanged even when reversed, retaining its original identity. Example: Input : Number = 121Output : PalindromeInput : Number = 1331Output :
4 min read
JavaScript - Factorial of a Number in JS The factorial of a non-negative integer is the product of all positive integers less than or equal to that number. Itâs denoted by ân!â where n is the integer. Here are the various methods to find the factorial of a number in JavaScript.Logicx!= 1*(x-3)*(x-2)*(x-1).......xNote:Â Factorials of negativ
3 min read
JavaScript Program to Find GCD or HCF of Two NumbersGCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both numbers without leaving a remainder. GCD ( a, b ) = [ |a.b| ] / [ lcm(a, b) ]or,HCF of factors = Product of the Numbers/ LCM of numbersExample: Input: a = 20, b = 28Output: 4
3 min read
JavaScript Program to Find LCM of Two NumbersIn this article, we are going to learn about finding the LCM of two numbers by using JavaScript. LCM (Least Common Multiple) of two numbers is the smallest positive integer that is divisible by both numbers without leaving a remainder. It's a common multiple of the numbers. LCM of two numbers = Prod
4 min read
Check a Number is Prime or Not Using JavaScriptA prime number is a whole number greater than 1, which has no positive divisors other than 1 and itself. In other words, prime numbers cannot be formed by multiplying two smaller natural numbers. For example:2, 3, 5, 7, 11, and 13 are prime numbers.4, 6, 8, 9, and 12 are not prime numbers because th
5 min read
JavaScript Program to Find Prime FactorsIn this article, we will see all the methods to find the prime factors of a number using JavaScript. Methods to Find Prime Factors: Table of Content Using loops and Math.pow() MethodRecursive Approach with Spread OperatorSieve of Eratosthenes AlgorithmMethod 1: Using loops and Math.pow() MethodIn th
3 min read
JavaScript Program for Sieve of EratosthenesIn this article, we will be demonstrating a JavaScript program for the Sieve of Eratosthenes algorithm. The Sieve of Eratosthenes algorithm is an efficient way of getting all the prime numbers that exist in the given range e.g., Input: n =10Output: 2 3 5 7 Input: n = 20 Output: 2 3 5 7 11 13 17 19Ap
2 min read
JavaScript Program to Compute Power of a NumberIn this article, we will demonstrate different approaches for computing the Power of a Number using JavaScript. The Power of a Number can be computed by raising a number to a certain exponent. It can be denoted using a^b, where the 'a' represents the base number & the 'b' represents the number t
3 min read
Recursion
Recursion Guide in JavaScriptRecursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems.Syntax:JavaScriptfunction re
4 min read
Applications of Recursion in JavaScriptRecursion is a programming technique in which a function calls itself directly or indirectly.  Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. Recursion is a
7 min read
JavaScript Program to Print N to 1 using RecursionIn this article, we will see how to print N to 1 using Recursion in JavaScript. What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base
1 min read
JavaScript Program to Print 1 to N using RecursionIn this article, we will see how to print 1 to N using Recursion in JavaScript. What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base
2 min read
JavaScript Program to Check for Palindrome String using RecursionGiven a string, write a recursive function that checks if the given string is a palindrome, else, not a palindrome. A string is called a palindrome if the reverse of the string is the same as the original one. For example - âmadamâ, âracecarâ, etc.What is Recursion?The process in which a function ca
3 min read
JavaScript Program for Sum of Digits of a Number using RecursionWe are given a number as input and we have to find the sum of all the digits contained by it. We will split the digits of the number and add them together using recursion in JavaScript. Table of Content Recursively Summing DigitsUsing string manipulation with recursionRecursively Summing DigitsIn th
2 min read
Array
Create an Array of Given Size in JavaScriptThe basic method to create an array is by using the Array constructor. We can initialize an array of certain length just by passing a single integer argument to the JavaScript array constructor. This will create an array of the given size with undefined values.Syntaxconst arr = new Array( length );J
3 min read
JavaScript - Access Elements in JS ArrayThese are the following ways to Access Elements in an Array:1. Using Square Bracket NotationWe can access elements in an array by using their index, where the index starts from 0 for the first element. We can access using the bracket notation.JavaScriptconst a = [10, 20, 30, 40, 50]; const v = a[3];
2 min read
JavaScript - Max Element in an ArrayThese are the following ways to find the largest element in JS array: Note: You must add a conditional check for checking whether the given array is empty or not, if the array is not empty then you can use the given below approaches to find out the largest element among them. 1. Using the Spread Ope
4 min read
JavaScript Program to Check an Array is Sorted or NotIn this article, we will learn how to check if the array is sorted in JavaScript. JavaScript Array is a single variable that is used to store elements of different data types. Now, we have to find whether the array is sorted or not.Examples:Input : const arr = [1, 2, 3, 4, 5]; Output : trueInput : c
4 min read
Reverse an Array in JavaScriptHere are the different methods to reverse an array in JavaScript1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array.JavaScriptlet a = [1, 2, 3
3 min read
Javascript Program to Move all zeroes to end of arrayGiven an array of random numbers, Push all the zero's of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity i
3 min read
JavaScript Program for Left Rotate by One in an ArrayIn this article, we are going to learn about left Rotation by One in an Array by using JavaScript, Left rotation by one in an array means shifting all elements from one position to the left, with the last element moving to the first position. The order of elements is cyclically rotated while maintai
5 min read
Searching
Binary Search In JavaScriptBinary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexityExamples: Input : arr
3 min read
JavaScript Program to Find Index of First Occurrence of Target Element in Sorted ArrayIn this article, we will see the JavaScript program to get the first occurrence of a number in a sorted array. We have the following methods to get the first occurrence of a given number in the sorted array.Methods to Find the Index of the First Occurrence of the element in the sorted arrayTable of
6 min read
JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted ArrayIn this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted ArrayUsin
4 min read
Count number of occurrences (or frequency) in a sorted arrayGiven a sorted array arr[] and an integer target, the task is to find the number of occurrences of target in given array.Examples:Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2Output: 4Explanation: 2 occurs 4 times in the given array.Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4Output: 0Explana
9 min read
JavaScript Program to Find the Square RootGiven a number N, the task is to calculate the square root of a given number using JavaScript. There are the approaches to calculate the square root of the given number, these are: Approaches to Find the Square Root of Given Number in JavaScript: Table of Content Using Math.sqrt() MethodUsing JavaSc
5 min read
Sorting
Sorting Algorithms in JavaScriptSorting is an important operation in computer science that arranges elements of an array or list in a certain order (either ascending or descending).Example:Input: [64, 34, 25, 12, 22, 11, 90]Output: [11, 12, 22, 25, 34, 64, 90] Input: [1, 2, -3, 3, 4, 5]Output: [-3, 1, 2, 3, 4, 5] Table of ContentB
5 min read
Bubble Sort algorithm using JavaScriptBubble sort algorithm is an algorithm that sorts an array by comparing two adjacent elements and swapping them if they are not in the intended order. Here order can be anything like increasing or decreasing. How Bubble-sort works?We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ], and the task is
4 min read
JavaScript Program for Selection SortWhat is Selection Sort in JavaScript?Selection sort is a simple and efficient algorithm that works on selecting either the smallest or the largest element of the list or array and moving it to the correct position. Working of Selection SortConsider the following arrayarr = [ 64, 25, 12, 22, 11]This
3 min read
JavaScript Program for Insertion SortWhat is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program for Merge SortWhat is Merge Sort Algorithm?Merge sort is one of the sorting techniques that work on the divide and conquer approach. The Given array is divided in half again and again and those parts are arranged in sorted order and merged back to form the complete sorted array. Working of Merge SortTo Understand
3 min read
JavaScript Program to Merge two Sorted Arrays into a Single Sorted ArrayIn this article, we will cover how to merge two sorted arrays into a single sorted array in JavaScript. Given there are two sorted arrays, we need to merge them into a single sorted array in JavaScript. We will see the code for each approach along with the output. Below are the possible approaches t
3 min read
Javascript Program For Counting Inversions In An Array - Set 1 (Using Merge Sort)Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an invers
5 min read
JavaScript - Union of ArraysIn JavaScript, finding the union of multiple arrays means combining their elements into a single array with only unique values. Here are several methods to compute the union of JavaScript ArraysUsing Spread Operator with Set - Most PopularWe can use the Set object along with the spread operator to f
3 min read
Quick Sort(Lomuto Partition) Visualization using JavaScriptGUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned using Lomuto Partition and then how we get the final sorted array. We will also visualize the time complexity o
4 min read
How to Create an Array using Intersection of two Arrays in JavaScript ?In this article, we will try to understand how to create an array using the intersection values of two arrays in JavaScript using some coding examples. For Example: arr1 = [1, 3, 5, 7, 9, 10, 14, 15]arr2 = [1, 2, 3, 7, 10, 11, 13, 14]result_arr = [1, 3, 7, 10, 14]Approach 1: We will see the native a
3 min read
JavaScript Program for Quick SortWhat is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
Hashing
String
JavaScript StringsA JavaScript String is a sequence of characters, typically used to represent text. In JavaScript, there is no character type (Similar to Python and different from C, C++ and Java), so a single character string is used when we need a character.Like Java and Python, strings in JavaScript are immutable
6 min read
Palindrome in JavaScriptA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, words like "madam" and "racecar" are palindromes. How to Check if a String is a Palindrome in JavaScript?To check if a str
4 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each OtherWrite a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other.Method 1 (Use Sorting):Sort bot
6 min read
Javascript Program To Reverse Words In A Given StringExample: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples:Â Input: s = "geeks quiz practice code"Â Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice"Â Output: s = "pra
4 min read
How to Get Character of Specific Position using JavaScript ?Get the Character of a Specific Position Using JavaScript We have different approaches, In this article we are going to learn how to Get the Character of a Specific Position using JavaScript Below are the methods to get the character at a specific position using JavaScript: Table of Content Method 1
4 min read
How to generate all combinations of a string in JavaScript ?We are going to see if we can generate all the possible combinations of a given string using JavaScript methods or concepts. You are given a string, containing different characters, you need to generate all combinations of a string by selecting a character at once and then re-arranging that characte
4 min read
Linked List
Implementation of LinkedList in JavascriptIn this article, we will be implementing the LinkedList data structure in Javascript.A linked list is a linear data structure where elements are stored in nodes, each containing a value and a reference (or pointer) to the next node. It allows for efficient insertion and deletion operations.Each node
5 min read
Javascript Program For Searching An Element In A Linked ListWrite a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise.bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functio
3 min read
Javascript Program For Inserting A Node In A Linked ListWe have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. JavaScript// Linked List Class // Head of list let head; // Node
7 min read
Javascript Program For Inserting Node In The Middle Of The Linked ListGiven a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.Examples: Input : list: 1->2->4->5 x = 3Output : 1->2->3-
4 min read
Javascript Program For Writing A Function To Delete A Linked ListA linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. This article focuses on writing a function to delete a linked list.Implementation: JavaScript// Javascript program to delete // a li
1 min read
Javascript Program For Deleting A Linked List Node At A Given PositionGiven a singly linked list and a position, delete a linked list node at the given position.Example: Input: position = 1, Linked List = 8->2->3->1->7Output: Linked List = 8->3->1->7Input: position = 0, Linked List = 8->2->3->1->7Output: Linked List = 2->3->1-
3 min read
Javascript Program For Finding Length Of A Linked ListWrite a function to count the number of nodes in a given singly linked list.For example, the function should return 5 for linked list 1->3->1->2->1.Iterative Solution: 1) Initialize count as 0 2) Initialize a node pointer, current = head.3) Do following while current is not NULL a) curre
3 min read
Javascript Program For Rotating A Linked ListGiven a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smal
5 min read
Javascript Program For Finding The Middle Element Of A Given Linked ListGiven a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
JavaScript Program to Reverse a Linked ListA linked list is a data structure where elements are stored in nodes, and each node points to the next node in the sequence. Reversing a linked list involves changing the direction of the pointers, making the last node the new head and the head the new tail. Below are the approaches to reverse a lin
3 min read