JavaScript Data Structures and Algorithms (DSA) – Complete Guide with Arrays, Linked Lists, Stacks, Queues, Trees, Graphs, Searching, Sorting, Dynamic Programming, and Practical Coding Problems (2026)
Introduction
Data Structures and Algorithms (DSA) form the backbone of computer science and software development. Every modern application, from search engines and social media platforms to banking systems and operating systems, relies on efficient data structures and algorithms to process data quickly and effectively.
Whether you are preparing for coding interviews, improving your problem-solving skills, or building scalable JavaScript applications, learning DSA is an essential step toward becoming a proficient developer.
JavaScript provides built-in data structures such as arrays, objects, maps, and sets. However, understanding how these structures work internally and implementing advanced data structures such as linked lists, stacks, queues, trees, and graphs helps developers write more efficient and maintainable programs.
In this comprehensive guide, you will learn fundamental and advanced data structures, algorithm analysis, searching and sorting techniques, recursion, dynamic programming, and practical coding problems using modern JavaScript (ES6+). Every topic includes detailed explanations, working examples, complexity analysis, interview questions, and real-world applications.
By the end of this guide, you will have a strong foundation in Data Structures and Algorithms that will prepare you for technical interviews, competitive programming, and professional software development.
What is a Data Structure?
A Data Structure is a specialized way of organizing, storing, and managing data so that it can be accessed, modified, and processed efficiently.
Instead of storing information randomly, data structures organize it in a systematic way, allowing operations such as searching, insertion, deletion, updating, and sorting to be performed efficiently.
In simple terms,
A Data Structure is a method of organizing data to make operations on that data faster and more efficient.
For example, consider a library. Books are not placed randomly on shelves. They are arranged according to categories, authors, or ISBN numbers, making it easy to locate a specific book. Similarly, data structures organize data so computers can retrieve and manipulate it efficiently.
Real-World Analogy
Imagine a wardrobe.
Wardrobe
│
├── Shirts
├── Pants
├── Jackets
└── Shoes
If clothes were thrown randomly into a pile, finding a specific shirt would take much longer.
Organizing clothes into separate sections makes retrieval faster and easier.
Data structures work in exactly the same way.
Definition
A Data Structure is a method of organizing data in memory to perform operations efficiently while minimizing time and memory usage.
Why Are Data Structures Important?
Data structures play a vital role in software development because they determine how efficiently data can be processed.
Without appropriate data structures, applications may become slow, consume excessive memory, and be difficult to maintain.
Benefits include:
- Faster data retrieval
- Efficient memory usage
- Improved application performance
- Better scalability
- Easier code maintenance
- Optimized searching and sorting
Everyday Examples of Data Structures
| Real-Life Example | Data Structure |
|---|---|
| Shopping List | Array |
| Browser Back Button | Stack |
| Printer Queue | Queue |
| Family Tree | Tree |
| Road Network | Graph |
| Dictionary | Hash Table |
| Music Playlist | Linked List |
Applications of Data Structures
Data structures are used in almost every software system.
Some common applications include:
- Search Engines
- Banking Applications
- Social Media Platforms
- Online Shopping Websites
- Operating Systems
- Databases
- Artificial Intelligence
- Computer Networks
- GPS Navigation Systems
- Compilers
What is an Algorithm?
An Algorithm is a finite sequence of well-defined instructions designed to solve a specific problem or perform a particular task.
An algorithm accepts input, processes it through a series of logical steps, and produces the desired output.
In simple terms,
An Algorithm is a step-by-step procedure for solving a problem.
Real-World Analogy
Making a cup of tea follows an algorithm.

Each step must be followed in the correct order to achieve the desired result.
Characteristics of a Good Algorithm
A good algorithm should have the following characteristics:
- Clearly defined inputs
- Clearly defined outputs
- Unambiguous steps
- Finite number of operations
- Correctness
- Efficiency
- Scalability
Why Learn Data Structures and Algorithms?
Learning DSA offers numerous advantages for developers.
1. Improves Problem-Solving Skills
DSA teaches logical thinking and structured problem solving.
2. Essential for Coding Interviews
Most software companies assess DSA knowledge during technical interviews.
Common interview topics include:
- Arrays
- Strings
- Linked Lists
- Trees
- Graphs
- Dynamic Programming
3. Improves Application Performance
Selecting the right data structure reduces execution time and memory consumption.
4. Builds Scalable Software
Efficient algorithms ensure applications continue to perform well as data grows.
5. Strengthens Programming Fundamentals
Understanding DSA helps developers write cleaner, more optimized code.
Data Structure vs Data Type
Many beginners confuse Data Structures with Data Types.
| Data Type | Data Structure |
|---|---|
| Defines the type of data | Organizes data |
| Examples: Number, String, Boolean | Examples: Array, Stack, Queue |
| Built into programming languages | Implemented using data types |
| Represents a single value | Represents a collection of values |
Example
let age = 21;
Numberis a data type.
let marks = [85, 90, 78, 95];
Arrayis a data structure.
Types of Data Structures
Data structures can be broadly classified into two categories.

Linear Data Structures
In a linear data structure, elements are arranged sequentially.
Each element has a predecessor and a successor (except the first and last elements).
Examples include:
- Arrays
- Linked Lists
- Stacks
- Queues
Visualization:
10 → 20 → 30 → 40 → 50
Non-Linear Data Structures
In non-linear data structures, elements are organized hierarchically or as interconnected nodes.
Examples include:
- Trees
- Graphs
- Heaps
- Tries
Visualization:
A
/ \
B C
/ \ / \
D E F G
Static vs Dynamic Data Structures
Static Data Structures
The size is fixed during creation.
Example:
- Arrays (in many programming languages)
Advantages:
- Simple implementation
- Faster random access
Disadvantages:
- Fixed size
- Memory wastage if overallocated
Dynamic Data Structures
The size changes during program execution.
Examples:
- Linked Lists
- Trees
- Graphs
Advantages:
- Flexible size
- Efficient memory utilization
Disadvantages:
- More complex implementation
- Slight memory overhead due to pointers or references
Linear vs Non-Linear Data Structures
| Linear Data Structure | Non-Linear Data Structure |
|---|---|
| Sequential organization | Hierarchical or network organization |
| One-to-one relationship | One-to-many or many-to-many relationships |
| Easier traversal | More complex traversal |
| Simpler implementation | More advanced implementation |
| Examples: Array, Stack, Queue | Examples: Tree, Graph |
How Data Structures and Algorithms Work Together
Data Structures and Algorithms complement each other.
A data structure determines how data is stored, while an algorithm determines how that data is processed.

Example:

Without an efficient data structure, even the best algorithm may perform poorly.
Similarly, using an inefficient algorithm with a suitable data structure can still result in slow performance.
Real-World Applications of DSA
| Application | Data Structure / Algorithm Used |
|---|---|
| Google Search | Graphs, Hash Tables |
| Facebook Friends | Graphs |
| GPS Navigation | Graphs, Shortest Path Algorithms |
| Browser History | Stack |
| Printer Management | Queue |
| Music Playlist | Linked List |
| Database Indexing | Trees (B-Trees, B+ Trees) |
| Spell Checker | Trie |
| Operating System Scheduling | Queue, Priority Queue |
| AI and Machine Learning | Graphs, Trees, Dynamic Programming |
Time and Space Complexity (Big O Notation)
What is Algorithm Analysis?
When multiple algorithms solve the same problem, an important question arises:
Which algorithm is better?
The answer depends on how efficiently an algorithm uses:
- Time
- Memory
Algorithm Analysis is the process of evaluating an algorithm based on the resources it consumes.
The two primary measures are:
- Time Complexity – How long an algorithm takes to execute.
- Space Complexity – How much memory an algorithm requires.
Rather than measuring actual execution time in seconds (which depends on hardware and programming language), computer scientists use mathematical analysis to compare algorithms.
Why is Algorithm Analysis Important?
Imagine two programs that search for a student’s roll number.
Program A takes:
- 2 milliseconds for 100 records.
- 20 seconds for 10 million records.
Program B takes:
- 5 milliseconds for 100 records.
- 2 seconds for 10 million records.
Although Program A is initially faster, Program B performs much better for large datasets.
Algorithm analysis helps developers predict performance as input size increases.
Real-World Analogy
Imagine searching for a book in a library.
Method 1
Check every shelf one by one.
Shelf 1
↓
Shelf 2
↓
Shelf 3
↓
Shelf 4
↓
Book Found
This approach may require checking every shelf.
Method 2
The books are arranged alphabetically.
Open the catalogue.
Go directly to the correct section.
Find the book immediately.
This method is much faster.
The first method resembles Linear Search, while the second resembles Binary Search.
What is Time Complexity?
Time Complexity measures how the execution time of an algorithm changes as the input size increases.
It does not represent the actual running time.
Instead, it describes the growth rate of the algorithm.
Example
Consider this JavaScript code.
let numbers = [10,20,30,40];
console.log(numbers[2]);
Whether the array has:
- 10 elements
- 100 elements
- 1,000,000 elements
The operation remains constant.
Therefore,
Time Complexity:
O(1)
What is Space Complexity?
Space Complexity measures the amount of additional memory required by an algorithm during execution.
It includes:
- Variables
- Arrays
- Objects
- Function call stack
- Temporary memory
Example
let number = 10;
Space Complexity:
O(1)
What is Big O Notation?
Big O Notation is a mathematical notation used to describe the worst-case growth rate of an algorithm.
It focuses on how performance changes as the input size becomes very large.
Instead of measuring exact execution time, Big O expresses the relationship between input size (n) and the number of operations performed.
Why Use Big O?
Big O allows developers to:
- Compare algorithms.
- Predict scalability.
- Optimize applications.
- Choose better solutions.
- Analyze performance independent of hardware.
Types of Complexity Analysis
Algorithm performance can be analyzed in three different cases.

Best Case
The minimum time required.
Example:
Searching for the first element.
Average Case
The expected time required for a typical input.
Worst Case
The maximum time required.
Most interview questions focus on the Worst Case, which is represented by Big O Notation.
Big O Growth Chart
As the input size grows, the number of operations increases at different rates.
Best Performance
O(1)
↓
O(log n)
↓
O(n)
↓
O(n log n)
↓
O(n²)
↓
O(n³)
↓
O(2ⁿ)
↓
O(n!)
Worst Performance
Algorithms near the top scale much better than those near the bottom.
Common Time Complexities
1. Constant Time – O(1)
An operation always takes the same amount of time regardless of input size.
Example
const numbers = [5,10,15,20];
console.log(numbers[0]);
5
Explanation
Accessing an array element by index always requires one operation.
Complexity
- Time: O(1)
- Space: O(1)
Real-World Examples
- Accessing an array element.
- Accessing an object property.
- Stack
peek(). - Queue
front().
2. Logarithmic Time – O(log n)
The input is repeatedly divided into smaller parts.
Example
Binary Search.
100 Elements
↓
50
↓
25
↓
12
↓
6
↓
3
↓
1
Each step halves the search space.
JavaScript Example
function binarySearch(arr, target){
let left = 0;
let right = arr.length - 1;
while(left <= right){
let mid = Math.floor((left + right)/2);
if(arr[mid] === target){
return mid;
}
if(arr[mid] < target){
left = mid + 1;
}else{
right = mid - 1;
}
}
return -1;
}
console.log(binarySearch([10,20,30,40,50],40));
Output
3
Complexity
- Time: O(log n)
- Space: O(1)
3. Linear Time – O(n)
The algorithm processes every element exactly once.
Example
const numbers = [10,20,30,40,50];
for(let number of numbers){
console.log(number);
}
Output
10
20
30
40
50
- Time: O(n)
- Space: O(1)
Real-World Examples
- Linear Search
- Printing an array
- Calculating total marks
4. Linearithmic Time – O(n log n)
This complexity appears in efficient sorting algorithms.
Examples:
- Merge Sort
- Heap Sort
- Quick Sort (average case)
Visualization
100 Elements
↓
Divide
↓
Sort
↓
Merge
Complexity
- Time: O(n log n)
- Space: Depends on the algorithm
5. Quadratic Time – O(n²)
Every element is compared with every other element.
Example
const numbers = [1,2,3];
for(let i=0;i<numbers.length;i++){
for(let j=0;j<numbers.length;j++){
console.log(numbers[i],numbers[j]);
}
}
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
- Time: O(n²)
- Space: O(1)
Real-World Examples
- Bubble Sort
- Selection Sort
- Comparing every student with every other student
6. Cubic Time – O(n³)
Three nested loops.
Example
for(let i=0;i<n;i++){
for(let j=0;j<n;j++){
for(let k=0;k<n;k++){
// Work
}
}
}
- Time: O(n³)
Used less frequently because of poor performance.
7. Exponential Time – O(2ⁿ)
Each recursive call generates two additional recursive calls.
Example
Naive Fibonacci recursion.
Fib(5)
├── Fib(4)
│ ├── Fib(3)
│ └── Fib(2)
└── Fib(3)
- Time: O(2ⁿ)
Very inefficient for large inputs.
8. Factorial Time – O(n!)
This is one of the slowest complexity classes.
Appears in problems that generate every possible arrangement.
Example:
- Traveling Salesman
- Permutations
Time Complexity Comparison Table
| Complexity | Name | Performance | Example |
|---|---|---|---|
| O(1) | Constant | Excellent | Array Access |
| O(log n) | Logarithmic | Excellent | Binary Search |
| O(n) | Linear | Good | Linear Search |
| O(n log n) | Linearithmic | Very Good | Merge Sort |
| O(n²) | Quadratic | Slow | Bubble Sort |
| O(n³) | Cubic | Very Slow | Matrix Multiplication |
| O(2ⁿ) | Exponential | Poor | Recursive Fibonacci |
| O(n!) | Factorial | Worst | Permutations |
Space Complexity Example
O(1)
let total = 0;
Only one variable.
O(n)
const squares = [];
for(let i=1;i<=5;i++){
squares.push(i*i);
}
console.log(squares);
Output
[1,4,9,16,25]
Memory increases as the input size grows.
Space Complexity:
O(n)
Best Practices for Writing Efficient Algorithms
- Prefer O(log n) or O(n) solutions whenever possible.
- Avoid unnecessary nested loops.
- Choose the right data structure before optimizing the algorithm.
- Eliminate repeated computations.
- Use memoization or dynamic programming when solving overlapping subproblems.
- Measure performance after correctness.
Common Mistakes
- Assuming fewer lines of code mean better performance.
- Ignoring space complexity.
- Optimizing before identifying bottlenecks.
- Using inefficient algorithms for large datasets.
- Comparing execution time on different hardware instead of analyzing complexity.
Arrays in JavaScript
What is an Array?
An Array is a linear data structure used to store multiple values in a single variable. Each value is stored at a specific position called an index.
Arrays allow efficient storage and manipulation of collections of related data.
Instead of creating multiple variables,
let student1 = "Akshay";
let student2 = "Rahul";
let student3 = "Priya";
let student4 = "Sneha";
let students = ["Akshay", "Rahul", "Priya", "Sneha"];
In simple words,
An Array is an ordered collection of elements stored using index positions starting from 0.
Definition
An array is a linear data structure in which elements are stored sequentially in contiguous logical order and accessed using their index.
Real-World Analogy
Imagine a row of lockers in a school.
Locker Number
┌────┬────┬────┬────┬────┐
│ 0 │ 1 │ 2 │ 3 │ 4 │
├────┼────┼────┼────┼────┤
│Amit│Raj │Neha│John│Sara│
└────┴────┴────┴────┴────┘
- A unique number (index)
- A stored value
Arrays work exactly the same way.
Characteristics of Arrays
Arrays have the following characteristics:
- Ordered collection of elements
- Zero-based indexing
- Can store different data types
- Dynamic size in JavaScript
- Fast random access
- Easy traversal
Why Use Arrays?
Arrays help developers:
- Store multiple values
- Reduce duplicate variables
- Process collections efficiently
- Sort data
- Search data
- Perform mathematical operations
- Build complex data structures
Array Declaration
Method 1: Array Literal (Recommended)
let numbers = [10,20,30,40,50];
Method 2: Array Constructor
let numbers = new Array(10,20,30,40,50);
Output
[10,20,30,40,50]
Memory Representation
Although JavaScript arrays are dynamic and internally optimized by the engine, conceptually an array can be represented as follows.
Index
0 1 2 3 4
┌────┬────┬────┬────┬────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴────┴────┴────┴────┘
Each element occupies an indexed position.
Indexing
Array indexing starts from 0.
let colors = ["Red","Blue","Green","Yellow"];
Index
0 1 2 3
Red Blue Green Yellow
console.log(colors[0]);
console.log(colors[2]);
console.log(colors[3]);
Red
Green
Yellow
Accessing Elements
let cities = ["Mumbai","Pune","Delhi","Bengaluru"];
console.log(cities[1]);
console.log(cities[3]);
Output
Pune
Bengaluru
Updating Elements
Arrays are mutable.
let fruits = ["Apple","Banana","Mango"];
fruits[1] = "Orange";
console.log(fruits);
["Apple","Orange","Mango"]
Array Length
The length property returns the number of elements.
let marks = [90,85,76,88,95];
console.log(marks.length);
5
Traversing an Array
Traversal means visiting every element.
Method 1: Traditional for Loop
let numbers = [10,20,30,40,50];
for(let i=0;i<numbers.length;i++){
console.log(numbers[i]);
}
10
20
30
40
50
Complexity
Time Complexity:
O(n)
Space Complexity:
O(1)
Method 2: for…of Loop
let languages = ["HTML","CSS","JavaScript","PHP"];
for(const language of languages){
console.log(language);
}
HTML
CSS
JavaScript
PHP
Method 3: forEach()
const numbers = [10,20,30,40];
numbers.forEach(function(number){
console.log(number);
});
10
20
30
40
Method 4: map()
const prices = [100,200,300];
const doubled = prices.map(function(price){
return price*2;
});
console.log(doubled);
[200,400,600]
Types of Arrays
JavaScript supports multiple forms of arrays.
Numeric Array
let numbers = [10,20,30];
String Array
let names = ["Akshay","Rahul","Neha"];
Boolean Array
let status = [true,false,true];
Mixed Array
let data = ["Akshay",25,true,95.5];
Nested Array (2D Array)
let matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(matrix[1][2]);
Static vs Dynamic Arrays
Static Arrays
Characteristics:
- Fixed size
- Cannot grow after creation
- Used in languages like C
Dynamic Arrays
JavaScript arrays are dynamic.
let numbers = [10,20];
numbers.push(30);
numbers.push(40);
console.log(numbers);
[10,20,30,40]
Advantages of Arrays
- Simple to use
- Fast indexing
- Memory efficient for sequential data
- Easy traversal
- Built-in methods
- Suitable for sorting and searching
Disadvantages of Arrays
- Inserting elements in the middle requires shifting.
- Deleting elements may require shifting.
- Searching in an unsorted array is slow.
- Large arrays may consume significant memory.
Time Complexity of Common Array Operations
| Operation | Time Complexity |
|---|---|
| Access by Index | O(1) |
| Update | O(1) |
| Traverse | O(n) |
| Search (Linear) | O(n) |
Insert at End (push) |
O(1) (amortized) |
Remove from End (pop) |
O(1) |
Insert at Beginning (unshift) |
O(n) |
Remove from Beginning (shift) |
O(n) |
| Insert in Middle | O(n) |
| Delete from Middle | O(n) |
Common Array Methods
| Method | Purpose |
|---|---|
push() |
Add element to the end |
pop() |
Remove last element |
shift() |
Remove first element |
unshift() |
Add element at the beginning |
splice() |
Insert, remove, or replace elements |
slice() |
Extract a portion of an array |
concat() |
Merge arrays |
includes() |
Check if an element exists |
indexOf() |
Find the index of an element |
find() |
Find the first matching element |
filter() |
Return matching elements |
map() |
Transform each element |
reduce() |
Reduce array to a single value |
sort() |
Sort elements |
reverse() |
Reverse the array |
Real-World Applications
Arrays are widely used in:
- Student record management
- Employee lists
- Product catalogs
- Shopping carts
- Image galleries
- Sensor data
- Weather reports
- Financial transactions
- Leaderboards
- E-commerce inventories
Array Operations in JavaScript
Arrays become useful because they support various operations for storing, retrieving, updating, and manipulating data. Understanding these operations is essential for solving real-world programming problems and technical interview questions.
The most common array operations are:
- Traversing
- Insertion
- Deletion
- Updating
- Searching
- Sorting
- Reversing
- Merging
- Splitting
- Removing Duplicates
- Frequency Counting
Array Operations Overview

1. Array Traversal
What is Traversal?
Traversal means visiting every element of an array exactly once.
It is one of the most frequently performed operations.
Real-World Example
Suppose a teacher wants to display marks of every student.
Student Marks
↓
85
↓
92
↓
76
↓
89
↓
95
Every mark is visited once.
JavaScript Example
const marks = [85, 92, 76, 89, 95];
for(let i = 0; i < marks.length; i++){
console.log("Student " + (i + 1) + ": " + marks[i]);
}
Student 1: 85
Student 2: 92
Student 3: 76
Student 4: 89
Student 5: 95
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
2. Insertion
Insertion means adding new elements into an array.
Elements can be inserted:
- At the beginning
- At the end
- At any position
Insert at the End
The easiest insertion operation.
Example
let fruits = ["Apple","Banana","Mango"];
fruits.push("Orange");
console.log(fruits);
Output
["Apple","Banana","Mango","Orange"]
Visualization
Before
Apple → Banana → Mango
↓
After
Apple → Banana → Mango → Orange
Complexity
| Operation | Complexity |
|---|---|
| Time | O(1) (Amortized) |
| Space | O(1) |
Insert at the Beginning
let fruits = ["Banana","Mango"];
fruits.unshift("Apple");
console.log(fruits);
Output
["Apple","Banana","Mango"]
Visualization
Before
Banana → Mango
↓
After
Apple → Banana → Mango
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
Reason:
All existing elements must shift one position to the right.
Insert at a Specific Position
Using splice().
let colors = ["Red","Blue","Yellow"];
colors.splice(2,0,"Green");
console.log(colors);
["Red","Blue","Green","Yellow"]
Before
Red → Blue → Yellow
↓
After
Red → Blue → Green → Yellow
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
3. Deletion
Deletion removes elements from an array.
Deletion can occur:
- From the beginning
- From the end
- From any position
Delete Last Element
let numbers = [10,20,30,40];
numbers.pop();
console.log(numbers);
[10,20,30]
Complexity
| Operation | Complexity |
|---|---|
| Time | O(1) |
| Space | O(1) |
Delete First Element
let numbers = [10,20,30,40];
numbers.shift();
console.log(numbers);
[20,30,40]
Before
10 → 20 → 30 → 40
↓
After
20 → 30 → 40
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
Delete Specific Element
let cities = ["Mumbai","Pune","Delhi","Goa"];
cities.splice(2,1);
console.log(cities);
["Mumbai","Pune","Goa"]
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
4. Updating Elements
Updating changes an existing value.
let students = ["Akshay","Rahul","Priya"];
students[1] = "Sneha";
console.log(students);
["Akshay","Sneha","Priya"]
| Operation | Complexity |
|---|---|
| Time | O(1) |
5. Searching
Searching means locating an element.
There are multiple searching methods.
Using includes()
const languages = ["HTML","CSS","JavaScript"];
console.log(languages.includes("CSS"));
Output
true
Using indexOf()
const marks = [50,60,70,80];
console.log(marks.indexOf(70));
Output
2
Using find()
const employees = [{ id:1,name:"Akshay" },{ id:2,name:"Rahul" },{ id:3,name:"Sneha" }];
const employee = employees.find(emp=>emp.id===2);
console.log(employee);
{ id:2, name:"Rahul" }
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
6. Sorting Arrays
Sorting arranges elements in ascending or descending order.
Ascending Order
const numbers = [9,2,7,1,5];
numbers.sort((a,b)=>a-b);
console.log(numbers);
[1,2,5,7,9]
Descending Order
numbers.sort((a,b)=>b-a);
console.log(numbers);
[9,7,5,2,1]
Complexity
JavaScript engines typically implement optimized sorting algorithms.
Average Complexity:
O(n log n)
7. Reversing an Array
const numbers = [10,20,30,40];
numbers.reverse();
console.log(numbers);
[40,30,20,10]
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
8. Merging Arrays
const frontend = ["HTML","CSS"];
const backend = ["Node.js","MongoDB"];
const fullStack = frontend.concat(backend);
console.log(fullStack);
["HTML","CSS","Node.js","MongoDB"]
Using the Spread Operator:
const fullStack = [...frontend,...backend];
console.log(fullStack);
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n + m) |
9. Removing Duplicate Elements
const numbers = [1,2,2,3,4,4,5];
const unique = [...new Set(numbers)];
console.log(unique);
[1,2,3,4,5]
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) |
10. Frequency Counting
Counting occurrences of each element.
const fruits = ["Apple","Banana","Apple","Mango","Banana","Apple"];
const frequency = {};
for(const fruit of fruits){
frequency[fruit] = (frequency[fruit] || 0) + 1;
}
console.log(frequency);
{Apple:3,Banana:2,Mango:1}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) |
Summary of Array Operations
| Operation | Method | Time Complexity |
|---|---|---|
| Traverse | for, forEach |
O(n) |
| Access | array[index] |
O(1) |
| Update | array[index] = value |
O(1) |
| Insert End | push() |
O(1) (amortized) |
| Remove End | pop() |
O(1) |
| Insert Beginning | unshift() |
O(n) |
| Remove Beginning | shift() |
O(n) |
| Insert Middle | splice() |
O(n) |
| Delete Middle | splice() |
O(n) |
| Search | includes(), find(), indexOf() |
O(n) |
| Sort | sort() |
O(n log n) |
| Reverse | reverse() |
O(n) |
| Merge | concat(), Spread |
O(n + m) |
| Remove Duplicates | Set |
O(n) |
| Frequency Count | Object | O(n) |
Real-World Applications
Array operations are commonly used in:
- Student record systems
- Shopping carts
- Product filtering
- Banking transactions
- Attendance management
- Payroll processing
- Data analytics
- Inventory management
- E-commerce applications
- Dashboard reports
Advanced Array Methods in JavaScript
JavaScript provides many built-in array methods that simplify data processing and reduce the amount of code developers need to write.
Instead of writing lengthy loops, these methods allow developers to perform operations such as transformation, filtering, searching, aggregation, flattening, and copying with concise and readable code.
These methods are heavily used in:
- React.js
- Node.js
- Express.js
- Data Analytics
- REST APIs
- Functional Programming
Overview of Advanced Array Methods

1. map()
What is map()?
The map() method creates a new array by applying a function to every element of the original array.
It does not modify the original array.
Syntax
array.map(function(element,index,array){
return transformedValue;
});
Example 1: Square Numbers
const numbers = [1,2,3,4,5];
const squares = numbers.map(function(number){
return number * number;
});
console.log(squares);
[1,4,9,16,25]
Example 2: Convert Names to Uppercase
const names = ["Akshay","Rahul","Sneha"];
const upper = names.map(function(name){
return name.toUpperCase();
});
console.log(upper);
["AKSHAY","RAHUL","SNEHA"]
Complexity
| Time | Space |
|---|---|
| O(n) | O(n) |
Real-World Applications
- Price calculations
- Student grade conversion
- API response transformation
- Data formatting
2. filter()
What is filter()?
The filter() method creates a new array containing only elements that satisfy a given condition.
Example 1: Even Numbers
const numbers = [1,2,3,4,5,6];
const even = numbers.filter(function(number){
return number % 2 === 0;
});
console.log(even);
[2,4,6]
Example 2: Students with Marks Above 80
const marks = [75,92,64,88,95];
const topper = marks.filter(function(mark){
return mark > 80;
});
console.log(topper);
[92,88,95]
Complexity
| Time | Space |
|---|---|
| O(n) | O(n) |
Applications
- Product filtering
- Search functionality
- Student result filtering
- Employee records
3. reduce()
What is reduce()?
The reduce() method combines all elements into a single value.
It is useful for:
- Sum
- Average
- Maximum
- Minimum
- Frequency Count
Syntax
array.reduce(function(total,current){
return total;
},initialValue);
Example 1: Sum of Numbers
const numbers = [10,20,30,40];
const total = numbers.reduce(function(sum,number){
return sum + number;
},0);
console.log(total);
100
Example 2: Find Maximum
const marks = [72,91,68,95,84];
const highest = marks.reduce(function(max,value){
return value > max ? value : max;
});
console.log(highest);
95
Complexity
| Time | Space |
|---|---|
| O(n) | O(1) |
Applications
- Shopping cart total
- Sales reports
- Financial calculations
- Dashboard statistics
4. find()
What is find()?
Returns the first element that satisfies a condition.
Example
const employees = [{id:1,name:"Akshay"},{id:2,name:"Rahul"},{id:3,name:"Sneha"}];
const employee = employees.find(function(emp){
return emp.id === 2;
});
console.log(employee);
{ id:2, name:"Rahul" }
Complexity
| Time | Space |
|---|---|
| O(n) | O(1) |
5. findIndex()
Returns the index of the first matching element.
const numbers = [10,20,30,40];
const index = numbers.findIndex(function(value){
return value === 30;
});
console.log(index);
2
6. some()
Checks whether at least one element satisfies the condition.
Example
const marks = [55,62,91,70];
const hasTopper = marks.some(function(mark){
return mark > 90;
});
console.log(hasTopper);
true
Applications
- Validation
- Permission checking
- User roles
- Product availability
7. every()
Checks whether all elements satisfy a condition.
Example
const ages = [18,21,25,30];
const adults = ages.every(function(age){
return age >= 18;
});
console.log(adults);
true
Applications
- Form validation
- Eligibility checks
- Data verification
8. flat()
Flattens nested arrays.
Example
const matrix = [[1,2],[3,4],[5,6]];
console.log(matrix.flat());
[1,2,3,4,5,6]
Multi-Level Flattening
const values = [1,[2,[3,4]]];
console.log(values.flat(2));
[1,2,3,4]
9. flatMap()
Maps and flattens simultaneously.
Example
const words = ["HTML CSS","JavaScript PHP"];
const output = words.flatMap(function(word){
return word.split(" ");
});
console.log(output);
["HTML","CSS","JavaScript","PHP"]
10. fill()
Replaces elements with a specified value.
Example
const numbers = [1,2,3,4,5];
numbers.fill(0);
console.log(numbers);
Output
[0,0,0,0,0]
Partial Fill
const values = [1,2,3,4,5];
values.fill(9,1,4);
console.log(values);
[1,9,9,9,5]
11. copyWithin()
Copies elements to another location in the same array.
Example
const numbers = [1,2,3,4,5];
numbers.copyWithin(0,3);
console.log(numbers);
[4,5,3,4,5]
12. Array.from()
Creates an array from iterable objects.
Example 1
const word = "JavaScript";
const letters = Array.from(word);
console.log(letters);
["J","a","v","a","S","c","r","i","p","t"]
Example 2
const numbers = Array.from({length:5},(_,index)=>index+1);
console.log(numbers);
[1,2,3,4,5]
13. Array.of()
Creates a new array from arguments.
const numbers = Array.of(10,20,30);
console.log(numbers);
[10,20,30]
Comparison of Advanced Array Methods
| Method | Returns New Array | Purpose |
|---|---|---|
| map() | Yes | Transform elements |
| filter() | Yes | Filter elements |
| reduce() | No | Reduce to one value |
| find() | No | First matching element |
| findIndex() | No | First matching index |
| some() | No | Check if any match |
| every() | No | Check if all match |
| flat() | Yes | Flatten arrays |
| flatMap() | Yes | Map + Flatten |
| fill() | No | Replace values |
| copyWithin() | No | Copy within array |
| Array.from() | Yes | Create array |
| Array.of() | Yes | Create array from arguments |
Real-World Applications
These methods are widely used in:
- React component rendering
- REST API response processing
- Product search
- Shopping cart calculations
- Attendance reports
- Dashboard analytics
- Financial reports
- Data visualization
- Student management systems
- Inventory systems
Strings in JavaScript
What is a String?
A String is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or backticks (` `).
Strings are used to store and manipulate textual data such as names, addresses, email IDs, passwords, messages, URLs, and JSON data.
In JavaScript, strings are primitive data types and are immutable, which means their individual characters cannot be modified after creation.
In simple words,
A String is an ordered collection of characters used to represent text.
Definition
A String is a sequence of Unicode characters stored in a specific order that represents textual information.
Real-World Analogy
Imagine a word written on paper.
J A V A
0 1 2 3
Every character occupies a position called an index.
Strings work in the same way.
Characteristics of Strings
Strings have the following characteristics:
- Ordered sequence of characters
- Zero-based indexing
- Immutable
- Dynamic length
- Unicode support
- Can be traversed like arrays
Why Use Strings?
Strings are used for:
- User Names
- Passwords
- Email Addresses
- Search Queries
- File Names
- URLs
- JSON Data
- Log Messages
- Chat Applications
- Source Code
Creating Strings
Method 1: Double Quotes
let language = "JavaScript";
Method 2: Single Quotes
let language = 'JavaScript';
Method 3: Template Literals
let language = `JavaScript`;
Method 4: String Constructor
let language = new String("JavaScript");
Although possible, using the String constructor is generally discouraged because it creates a String object rather than a primitive string.
String Memory Representation
Index
0 1 2 3 4 5 6 7 8 9
J a v a S c r i p t
Every character has an index.
Accessing Characters
let language = "JavaScript";
console.log(language[0]);
console.log(language[4]);
console.log(language[9]);
J
S
t
String Length
The length property returns the number of characters.
let language = "JavaScript";
console.log(language.length);
10
Traversing a String
Using for Loop
let language = "JavaScript";
for(let i=0;i<language.length;i++){
console.log(language[i]);
}
Output
J
a
v
a
S
c
r
i
p
t
Complexity
| Time | Space |
|---|---|
| O(n) | O(1) |
Using for…of
let language = "JavaScript";
for(const character of language){
console.log(character);
}
String Immutability
Strings cannot be modified directly.
let language = "JavaScript";
language[0] = "P";
console.log(language);
Output
JavaScript
The string remains unchanged.
Instead,
let language = "JavaScript";
language = "TypeScript";
console.log(language);
Output
TypeScript
Common String Methods
toUpperCase()
let name = "akshay";
console.log(name.toUpperCase());
AKSHAY
toLowerCase()
let name = "AKSHAY";
console.log(name.toLowerCase());
Output
akshay
trim()
Removes leading and trailing spaces.
let text = " JavaScript ";
console.log(text.trim());
JavaScript
includes()
Checks whether a substring exists.
let language = "JavaScript";
console.log(language.includes("Script"));
Output
true
startsWith()
let language = "JavaScript";
console.log(language.startsWith("Java"));
Output
true
endsWith()
let language = "JavaScript";
console.log(language.endsWith("Script"));
Output
true
indexOf()
let language = "JavaScript";
console.log(language.indexOf("S"));
Output
4
lastIndexOf()
let text = "banana";
console.log(text.lastIndexOf("a"));
Output
5
slice()
Extracts a portion of the string.
let language = "JavaScript";
console.log(language.slice(4,10));
Output
Script
substring()
let language = "JavaScript";
console.log(language.substring(0,4));
Output
Java
replace()
let sentence = "I like Java";
console.log(
sentence.replace("Java","JavaScript")
);
Output
I like JavaScript
replaceAll()
let text = "PHP PHP PHP";
console.log(
text.replaceAll("PHP","JavaScript")
);
Output
JavaScript JavaScript JavaScript
split()
Converts a string into an array.
let skills ="HTML,CSS,JavaScript";
console.log(skills.split(","));
["HTML","CSS","JavaScript"]
repeat()
console.log("JS ".repeat(3));
Output
JS JS JS
Character Frequency Counter
Finding the frequency of each character is a common interview problem.
Example
const text = "javascript";
const frequency = {};
for(const character of text){
frequency[character] =
(frequency[character] || 0) + 1;
}
console.log(frequency);
{
j:1,
a:2,
v:1,
s:1,
c:1,
r:1,
i:1,
p:1,
t:1
}
| Time | Space |
|---|---|
| O(n) | O(n) |
Reverse a String
Method 1: Using Built-in Methods
const text = "JavaScript";
const reverse = text.split("").reverse().join("");
console.log(reverse);
tpircSavaJ
Method 2: Using Loop
const text = "JavaScript";
let reverse = "";
for(let i=text.length-1;i>=0;i--){
reverse += text[i];
}
console.log(reverse);
tpircSavaJ
Palindrome Check
A palindrome reads the same forwards and backwards.
Examples:
- madam
- level
- radar
Example
const word = "madam";
const reverse =word.split("").reverse().join("");
if(word === reverse){
console.log("Palindrome");
}else{
console.log("Not Palindrome");
}
Palindrome
| Time | Space |
|---|---|
| O(n) | O(n) |
Anagram Check
Two strings are anagrams if they contain the same characters in a different order.
Examples:
listen
silent
Example
function isAnagram(first, second){
const a = first.split("").sort().join("");
const b = second.split("").sort().join("");
return a === b;
}
console.log(isAnagram("listen","silent"));
true
Count Vowels
const text = "JavaScript";
let count = 0;
for(const character of text.toLowerCase()){
if("aeiou".includes(character)){
count++;
}
}
console.log(count);
Output
3
Count Words
const sentence = "JavaScript is awesome";
const words = sentence.trim().split(" ");
console.log(words.length);
Output
3
String Comparison
console.log("Apple" === "Apple");
console.log("Apple" === "apple");
Output
true
false
Time Complexity of Common String Operations
| Operation | Time Complexity |
|---|---|
| Access Character | O(1) |
| Traverse | O(n) |
Search (includes) |
O(n) |
| Concatenation | O(n) |
| Reverse | O(n) |
| Split | O(n) |
| Replace | O(n) |
| Palindrome | O(n) |
| Anagram | O(n log n) |
Real-World Applications
Strings are widely used in:
- Login systems
- Email validation
- Password validation
- Search engines
- Chat applications
- Text editors
- Compilers
- Natural Language Processing
- URL processing
- Data parsing
Best Practices
- Use template literals for readable string interpolation.
- Avoid repeated string concatenation inside large loops.
- Use appropriate built-in methods instead of writing unnecessary custom logic.
- Normalize case when performing case-insensitive comparisons.
- Trim user input before validation.
Linked Lists in JavaScript
What is a Linked List?
A Linked List is a linear dynamic data structure in which elements are stored as separate objects called nodes. Unlike arrays, linked list elements are not stored in contiguous memory locations. Instead, each node contains the data and a reference (link) to the next node.
In JavaScript, references are implemented using object references rather than memory pointers.
In simple words,
A Linked List is a collection of nodes where each node stores data and a reference to the next node in the sequence.
Definition
A Linked List is a dynamic linear data structure consisting of nodes, where each node contains data and a reference to the next node.
Why Do We Need Linked Lists?
Suppose you have an array:
const students = ["Akshay", "Rahul", "Sneha", "Priya"];
If you insert a new element in the middle,
Akshay Rahul Sneha Priya
↓
Insert "Neha"
↓
Akshay Rahul Neha Sneha Priya
For large datasets, this becomes inefficient.
A linked list simply changes references.
Akshay → Rahul → Sneha → Priya
↓
Akshay → Rahul → Neha → Sneha → Priya
Real-World Analogy
Imagine a treasure hunt.
Each clue points to the next clue.
Clue 1
↓
Clue 2
↓
Clue 3
↓
Treasure
Each clue knows only where the next clue is located.
Linked Lists work in exactly the same way.
Memory Representation
Unlike arrays,
Array
┌────┬────┬────┬────┐
│10 │20 │30 │40 │
└────┴────┴────┴────┘
Head
│
▼
┌─────────┐
│10│ ●───┼────►
└─────────┘
│
▼
┌─────────┐
│20│ ●───┼────►
└─────────┘
│
▼
┌─────────┐
│30│ ●───┼────►
└─────────┘
│
▼
┌─────────┐
│40│ Null │
└─────────┘
Each node stores:
- Data
- Reference to the next node
Components of a Linked List
Every Linked List consists of:
Node
Stores:
- Data
- Next reference
Head
The first node.
Head
↓
10 → 20 → 30 → Null
Tail
The last node.
10 → 20 → 30
↑
Tail
null.Characteristics of Linked Lists
- Dynamic size
- Sequential access
- Efficient insertion
- Efficient deletion
- No contiguous memory required
- Uses extra memory for references
Types of Linked Lists

Singly Linked List
A Singly Linked List contains one reference.
10 → 20 → 30 → 40 → Null
Each node points only to the next node.
Doubly Linked List
Each node has two references.
Null ← 10 ⇄ 20 ⇄ 30 ⇄ 40 → Null
- Forward traversal
- Backward traversal
Circular Linked List
The last node points back to the first node.
┌───────────────┐
│ ▼
10 → 20 → 30 → 40
▲ │
└───────────────┘
Useful in:
- Music players
- CPU scheduling
- Round-robin algorithms
Creating a Node
Every linked list starts with a node.
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
Creating the First Node
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
const firstNode = new Node(10);
console.log(firstNode);
Output
Node {
data:10,
next:null
}
Creating a Linked List
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
const first = new Node(10);
const second = new Node(20);
const third = new Node(30);
first.next = second;
second.next = third;
console.log(first);
Visualization
Head
↓
10 → 20 → 30 → Null
Traversing a Linked List
Traversal means visiting every node.
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
const first = new Node(10);
const second = new Node(20);
const third = new Node(30);
first.next = second;
second.next = third;
let current = first;
while(current != null){
console.log(current.data);
current = current.next;
}
Output
10
20
30
Complexity
| Time | Space |
|---|---|
| O(n) | O(1) |
Searching in a Linked List
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
const first = new Node(10);
const second = new Node(20);
const third = new Node(30);
first.next = second;
second.next = third;
let current = first;
let target = 20;
let found = false;
while(current){
if(current.data === target){
found = true;
break;
}
current = current.next;
}
console.log(found);
Output
true
Complexity
| Time | Space |
|---|---|
| O(n) | O(1) |
Advantages of Linked Lists
- Dynamic size
- Fast insertion at the beginning
- Fast deletion when the node is known
- Efficient memory allocation
- No shifting of elements
Disadvantages of Linked Lists
- Sequential access only
- Extra memory for references
- Slower searching compared to arrays
- More complex implementation
Arrays vs Linked Lists
| Array | Linked List |
|---|---|
| Contiguous storage | Non-contiguous storage |
| Fast indexing (O(1)) | Sequential access (O(n)) |
| Fixed-size concept (dynamic in JavaScript) | Naturally dynamic |
| Slow middle insertion | Fast insertion after a known node |
| Less memory overhead | Extra memory for references |
Time Complexity
| Operation | Array | Linked List |
|---|---|---|
| Access | O(1) | O(n) |
| Search | O(n) | O(n) |
| Insert at Beginning | O(n) | O(1) |
| Insert at End* | O(1) amortized | O(n) (O(1) with a tail pointer) |
| Delete at Beginning | O(n) | O(1) |
| Delete at End | O(1) | O(n) |
Real-World Applications
Linked Lists are used in:
- Music playlists
- Browser history
- Undo and redo functionality
- Image viewers
- Memory management
- File systems
- Hash tables (separate chaining)
- Graph adjacency lists
Best Practices
- Keep a reference to the head node.
- Use a tail pointer when frequent insertions at the end are required.
- Always check for
nullbefore accessingnext. - Encapsulate linked list logic inside a dedicated class.
- Handle edge cases such as empty lists and single-node lists.
Linked List Operations in JavaScript
A Linked List becomes useful because it supports efficient insertion and deletion without shifting elements. In this section, you will implement all common Linked List operations from scratch using JavaScript classes.
We will build a reusable LinkedList class and gradually add new functionality.
Complete Node Class
Every linked list begins with a node.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
Creating the LinkedList Class
The LinkedList class stores the reference to the first node.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
}
Head
↓
Null
The list is empty.
1. Insert at the Beginning
Theory
A new node becomes the first node.
Steps:
- Create a new node.
- Point the new node to the current head.
- Update the head.
Visualization
Before
Head
↓
10 → 20 → 30 → Null
After inserting 5
Head
↓
5 → 10 → 20 → 30 → Null
JavaScript Code
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
insertAtBeginning(data) {
const newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
}
display() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}
const list = new LinkedList();
list.insertAtBeginning(30);
list.insertAtBeginning(20);
list.insertAtBeginning(10);
list.display();
10
20
30
Complexity
| Operation | Complexity |
|---|---|
| Time | O(1) |
| Space | O(1) |
2. Insert at the End
Theory
Traverse to the last node and connect the new node.
Visualization
Before
10 → 20 → 30 → Null
After
10 → 20 → 30 → 40 → Null
JavaScript Code
insertAtEnd(data){
const newNode = new Node(data);
if(this.head === null){
this.head = newNode;
return;
}
let current = this.head;
while(current.next){
current = current.next;
}
current.next = newNode;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
3. Insert at a Specific Position
Example
Insert 25 at position 3.
Before
10 → 20 → 30 → 40
10 → 20 → 25 → 30 → 40
JavaScript Code
insertAtPosition(data, position){
if(position === 1){
this.insertAtBeginning(data);
return;
}
const newNode = new Node(data);
let current = this.head;
let previous = null;
let count = 1;
while(current && count < position){
previous = current;
current = current.next;
count++;
}
previous.next = newNode;
newNode.next = current;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
4. Delete from the Beginning
Theory
Simply move the head to the next node.
Visualization
Before
Head
↓
10 → 20 → 30
Head
↓
20 → 30
JavaScript Code
deleteFromBeginning(){
if(this.head === null){
return;
}
this.head = this.head.next;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(1) |
| Space | O(1) |
5. Delete from the End
JavaScript Code
deleteFromEnd(){
if(this.head === null){
return;
}
if(this.head.next === null){
this.head = null;
return;
}
let current = this.head;
while(current.next.next){
current = current.next;
}
current.next = null;
}
Visualization
Before
10 → 20 → 30 → 40
10 → 20 → 30
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
6. Delete by Value
JavaScript Code
deleteByValue(value){
if(this.head === null){
return;
}
if(this.head.data === value){
this.head = this.head.next;
return;
}
let current = this.head;
while(current.next && current.next.data !== value){
current = current.next;
}
if(current.next){
current.next = current.next.next;
}
}
Example
Before
10 → 20 → 30 → 40
After
10 → 20 → 40
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
7. Search an Element
JavaScript Code
search(value){
let current = this.head;
while(current){
if(current.data === value){
return true;
}
current = current.next;
}
return false;
}
Example
console.log(list.search(20));
true
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
8. Update a Node
JavaScript Code
update(oldValue,newValue){
let current = this.head;
while(current){
if(current.data === oldValue){
current.data = newValue;
return;
}
current = current.next;
}
}
Example
Before
10 → 20 → 30
20 → 25
After
10 → 25 → 30
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
9. Count Nodes
JavaScript Code
countNodes(){
let count = 0;
let current = this.head;
while(current){
count++;
current = current.next;
}
return count;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
10. Reverse a Linked List
Theory
Reverse the direction of every link.
Before
10 → 20 → 30 → 40 → Null
40 → 30 → 20 → 10 → Null
Algorithm
- Keep three pointers:
-
Previous
- Current
- Next
-
- Reverse the link.
- Move forward.
- Repeat until the end.
- Update the head.
Visualization
Previous Current Next
Null ← 10 → 20
↓
Null ← 10
↓
10 ← 20 → 30
↓
20 ← 30 → 40
↓
40 → 30 → 20 → 10
JavaScript Code
reverse(){
let previous = null;
let current = this.head;
while(current){
let next = current.next;
current.next = previous;
previous = current;
current = next;
}
this.head = previous;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
11. Find the Middle Node
Finding the middle element efficiently is a popular interview problem.
Fast and Slow Pointer Technique
- Slow pointer moves one node.
- Fast pointer moves two nodes.
When the fast pointer reaches the end, the slow pointer points to the middle node.
Visualization
10 → 20 → 30 → 40 → 50
S
F
↓
10 → 20 → 30 → 40 → 50
S
F
↓
10 → 20 → 30 → 40 → 50
S
F
Middle = 30
JavaScript Code
findMiddle(){
let slow = this.head;
let fast = this.head;
while(fast && fast.next){
slow = slow.next;
fast = fast.next.next;
}
return slow.data;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
12. Display the Linked List
display(){
let current = this.head;
while(current){
process.stdout.write(current.data + " → ");
current = current.next;
}
console.log("Null");
}
10 → 20 → 30 → 40 → Null
Note: If readers are running this code in a browser instead of Node.js, replace
process.stdout.write()with string concatenation and output the final string usingconsole.log().
Complete Complexity Table
| Operation | Time | Space |
|---|---|---|
| Insert Beginning | O(1) | O(1) |
| Insert End | O(n) | O(1) |
| Insert Position | O(n) | O(1) |
| Delete Beginning | O(1) | O(1) |
| Delete End | O(n) | O(1) |
| Delete by Value | O(n) | O(1) |
| Search | O(n) | O(1) |
| Update | O(n) | O(1) |
| Reverse | O(n) | O(1) |
| Find Middle | O(n) | O(1) |
| Count Nodes | O(n) | O(1) |
Real-World Applications
Linked List operations are used in:
- Browser history management
- Music playlist navigation
- Undo and redo systems
- Image gallery navigation
- Memory allocation
- Hash table chaining
- Graph adjacency lists
- Task scheduling
Doubly Linked Lists in JavaScript
What is a Doubly Linked List?
A Doubly Linked List (DLL) is a linear data structure where each node stores:
- Data
- Reference to the previous node
- Reference to the next node
Unlike a Singly Linked List, a Doubly Linked List allows traversal in both forward and backward directions.
In simple words,
A Doubly Linked List stores two references in every node—one pointing to the previous node and another pointing to the next node.
Structure of a Doubly Linked List
Each node consists of three parts.
┌──────────┬─────────┬──────────┐
│ Previous │ Data │ Next │
└──────────┴─────────┴──────────┘
Memory Representation
Null ← 10 ⇄ 20 ⇄ 30 ⇄ 40 → Null
Why Use a Doubly Linked List?
Suppose you are browsing images in a gallery.
You can:
- Go to the next image.
- Return to the previous image.
A Singly Linked List cannot move backward efficiently, whereas a Doubly Linked List can.
Real-World Applications
Doubly Linked Lists are commonly used in:
- Browser history
- Music players
- Image viewers
- Undo and redo functionality
- Text editors
- LRU Cache implementation
Node Class
class Node{
constructor(data){
this.data = data;
this.prev = null;
this.next = null;
}
}
Doubly Linked List Class
class DoublyLinkedList{
constructor(){
this.head = null;
this.tail = null;
}
}
Insert at the Beginning
Visualization
Before
Null ← 20 ⇄ 30 → Null
After
Null ← 10 ⇄ 20 ⇄ 30 → Null
JavaScript Code
insertAtBeginning(data){
const newNode = new Node(data);
if(this.head === null){
this.head = this.tail = newNode;
return;
}
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
}
Complexity
| Time | Space |
|---|---|
| O(1) | O(1) |
Insert at the End
insertAtEnd(data){
const newNode = new Node(data);
if(this.head === null){
this.head = this.tail = newNode;
return;
}
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
10 ⇄ 20 ⇄ 30
↓
10 ⇄ 20 ⇄ 30 ⇄ 40
| Time | Space |
|---|---|
| O(1) | O(1) |
Forward Traversal
displayForward(){
let current = this.head;
while(current){
console.log(current.data);
current = current.next;
}
}
10
20
30
40
Backward Traversal
displayBackward(){
let current = this.tail;
while(current){
console.log(current.data);
current = current.prev;
}
}
Output
40
30
20
10
Delete from Beginning
deleteFromBeginning(){
if(this.head === null){
return;
}
if(this.head === this.tail){
this.head = this.tail = null;
return;
}
this.head = this.head.next;
this.head.prev = null;
}
Delete from End
deleteFromEnd(){
if(this.head === null){
return;
}
if(this.head === this.tail){
this.head = this.tail = null;
return;
}
this.tail = this.tail.prev;
this.tail.next = null;
}
Advantages of Doubly Linked Lists
- Forward traversal
- Backward traversal
- Faster deletion when the node is known
- Easy implementation of navigation features
- Efficient for undo and redo systems
Disadvantages
- Extra memory required for the previous reference
- Slightly more complex implementation
- More pointer (reference) updates
Time Complexity
| Operation | Complexity |
|---|---|
| Insert Beginning | O(1) |
| Insert End | O(1) |
| Delete Beginning | O(1) |
| Delete End | O(1) |
| Search | O(n) |
| Traverse | O(n) |
Circular Linked Lists
What is a Circular Linked List?
A Circular Linked List (CLL) is a linked list in which the last node points back to the first node instead of pointing to null.
This creates a continuous loop.
Visualization
┌───────────────┐
│ ▼
10 → 20 → 30 → 40
▲ │
└───────────────┘
Why Use Circular Linked Lists?
Circular Linked Lists are useful when data needs to be processed repeatedly in a cycle without restarting from the beginning.
Real-World Applications
- Round Robin CPU Scheduling
- Multiplayer Games
- Music Playlists (Repeat Mode)
- Traffic Signal Controllers
- Circular Menus
- Token Ring Networks
Node Class
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
Circular Linked List Class
class CircularLinkedList{
constructor(){
this.head = null;
}
}
Insert First Node
insert(data){
const newNode = new Node(data);
if(this.head === null){
this.head = newNode;
newNode.next = this.head;
return;
}
let current = this.head;
while(current.next !== this.head){
current = current.next;
}
current.next = newNode;
newNode.next = this.head;
}
Traversing a Circular Linked List
Unlike a Singly Linked List, traversal stops when we reach the head node again.
display(){
if(this.head === null){
return;
}
let current = this.head;
do{
console.log(current.data);
current = current.next;
}
while(current !== this.head);
}
10
20
30
40
Advantages of Circular Linked Lists
- Continuous traversal
- Efficient cyclic scheduling
- No
nullreference at the end - Suitable for repeated processing
Disadvantages
- More difficult to debug
- Infinite loops if traversal conditions are incorrect
- More complex insertion and deletion logic
Singly vs Doubly vs Circular Linked List
| Feature | Singly | Doubly | Circular |
|---|---|---|---|
| Previous Reference | No | Yes | No |
| Next Reference | Yes | Yes | Yes |
| Backward Traversal | No | Yes | No |
| Circular Structure | No | No | Yes |
| Memory Usage | Low | High | Low |
| Insert at Beginning | O(1) | O(1) | O(1) |
| Insert at End | O(n)* | O(1)** | O(n)* |
| Delete End | O(n) | O(1)** | O(n) |
* O(1) if a tail reference is maintained.
** Assuming both head and tail references are maintained.
Real-World Comparison
| Linked List Type | Typical Applications |
|---|---|
| Singly Linked List | Music playlists, hash table chaining |
| Doubly Linked List | Browser history, image viewers, undo/redo |
| Circular Linked List | CPU scheduling, multiplayer games, repeating playlists |
Stacks in JavaScript
What is a Stack?
A Stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
This means the element that is inserted last is the first one to be removed.
In simple words,
A Stack is a collection of elements where insertion and deletion take place only at one end, called the Top of the Stack.
Definition
A Stack is a linear data structure that allows insertion (push) and deletion (pop) operations only from one end called the top.
Real-World Analogy
Imagine a stack of plates in a cafeteria.
When new plates arrive, they are placed on the top.
When someone needs a plate, they remove the top plate.
Top
┌─────┐
│Plate│
├─────┤
│Plate│
├─────┤
│Plate│
├─────┤
│Plate│
└─────┘
The last plate placed on the stack is the first one removed.
LIFO Principle

Stack Representation
Top
↓
┌─────┐
│ 40 │
├─────┤
│ 30 │
├─────┤
│ 20 │
├─────┤
│ 10 │
└─────┘
Why Use Stacks?
Stacks are useful whenever the most recently added item should be processed first.
Examples include:
- Browser history
- Undo and redo operations
- Function calls
- Expression evaluation
- Syntax parsing
- Backtracking algorithms
- Depth First Search (DFS)
Basic Stack Operations

1. Push Operation
What is Push?
The push operation inserts a new element at the top of the stack.
Visualization
Before
Top
↓
30
20
10
Push 40
After
Top
↓
40
30
20
10
Stack Implementation Using Array
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
}
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.items);
Output
[10,20,30]
Complexity
| Operation | Complexity |
|---|---|
| Push | O(1) |
2. Pop Operation
What is Pop?
Removes and returns the top element.
Visualization
Before
Top
↓
40
30
20
10
After Pop
Top
↓
30
20
10
Removed Element
40
JavaScript Code
pop() {
if(this.items.length === 0){
return "Stack Underflow";
}
return this.items.pop();
}
Example
console.log(stack.pop());
Output
30
Complexity
| Operation | Complexity |
|---|---|
| Pop | O(1) |
3. Peek Operation
Peek returns the top element without removing it.
peek(){
if(this.items.length===0){
return null;
}
return this.items[this.items.length-1];
}
Example
console.log(stack.peek());
Output
20
Complexity
| Operation | Complexity |
|---|---|
| Peek | O(1) |
4. isEmpty()
Checks whether the stack contains any elements.
isEmpty(){
return this.items.length===0;
}
Example
console.log(stack.isEmpty());
Output
false
Complexity
| Operation | Complexity |
|---|---|
| isEmpty | O(1) |
5. Size
Returns the number of elements.
size(){
return this.items.length;
}
Example
console.log(stack.size());
2
Complexity
| Operation | Complexity |
|---|---|
| Size | O(1) |
Complete Stack Class
class Stack{
constructor(){
this.items=[];
}
push(element){
this.items.push(element);
}
pop(){
if(this.items.length===0){
return "Stack Underflow";
}
return this.items.pop();
}
peek(){
if(this.items.length===0){
return null;
}
return this.items[this.items.length-1];
}
isEmpty(){
return this.items.length===0;
}
size(){
return this.items.length;
}
display(){
console.log(this.items);
}
}
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.display();
console.log(stack.peek());
console.log(stack.pop());
stack.display();
console.log(stack.size());
console.log(stack.isEmpty());
Output
[10,20,30]
30
30
[10,20]
2
false
Stack Operations Flow
Push(10)
↓
[10]
↓
Push(20)
↓
[10,20]
↓
Push(30)
↓
[10,20,30]
↓
Peek()
↓
30
↓
Pop()
↓
[10,20]
Stack Using Linked List
Stacks can also be implemented using Linked Lists.
Advantages include:
- Dynamic size
- No resizing required
- Efficient insertion and deletion
Implementation:
Top
↓
30 → 20 → 10 → Null
Push
40 → 30 → 20 → 10
Pop
30 → 20 → 10
Insertion and deletion occur at the head node.
Advantages of Stacks
- Simple implementation
- Fast insertion
- Fast deletion
- Efficient memory usage
- Ideal for recursive problems
Disadvantages
- Limited access
- No random indexing
- Overflow in fixed-size implementations
- Underflow when removing from an empty stack
Time Complexity
| Operation | Array Stack | Linked List Stack |
|---|---|---|
| Push | O(1) | O(1) |
| Pop | O(1) | O(1) |
| Peek | O(1) | O(1) |
| Search | O(n) | O(n) |
| Display | O(n) | O(n) |
Real-World Applications
Stacks are widely used in:
- Browser Back button
- Undo and Redo operations
- Function Call Stack
- Recursive algorithms
- Expression evaluation
- Parentheses matching
- Syntax parsing
- Compiler design
- Depth First Search (DFS)
- Backtracking algorithms
Advanced Stack Applications in JavaScript
A stack is much more than a collection of elements. It is a fundamental data structure used in browsers, operating systems, compilers, text editors, and programming language runtimes.
In this section, you will learn how stacks solve real-world problems through practical examples.
Overview of Stack Applications

1. Parentheses Balancing
What is Parentheses Balancing?
Parentheses balancing checks whether every opening bracket has a corresponding closing bracket in the correct order.
Examples of balanced expressions:
()
{}
[]
({[]})
((A+B)*C)
((
{]
([)]
Why Use a Stack?
Whenever an opening bracket is encountered, it is pushed onto the stack.
When a closing bracket is found:
- Compare it with the top element.
- If they match, remove the opening bracket.
- Otherwise, the expression is invalid.
Visualization
Expression
{[()]}
Read {
Stack
{
↓
Read [
{
[
↓
Read (
{
[
(
↓
Read )
Pop (
↓
Read ]
Pop [
↓
Read }
Pop {
↓
Stack Empty
Balanced
JavaScript Implementation
function isBalanced(expression){
const stack = [];
const pairs = {
")" : "(",
"]" : "[",
"}" : "{"
};
for(const character of expression){
if(character==="(" ||
character==="[" ||
character==="{"){
stack.push(character);
}
else if(character===")" ||
character==="]" ||
character==="}"){
if(stack.pop() !== pairs[character]){
return false;
}
}
}
return stack.length===0;
}
console.log(isBalanced("{[()]}"));
true
Complexity
| Time | Space |
|---|---|
| O(n) | O(n) |
Applications
- Code editors
- Compilers
- HTML validation
- JSON validation
- XML parsers
2. Browser History
Browsers maintain history using stacks.
Pressing:
- Back
- Forward
internally uses stack operations.
Visualization
Visit Google
↓
Visit GitHub
↓
Visit Stack Overflow
↓
Back
↓
Stack Overflow Removed
↓
GitHub
Example
const history = [];
history.push("google.com");
history.push("github.com");
history.push("stackoverflow.com");
console.log(history.pop());
console.log(history);
stackoverflow.com
["google.com","github.com"]
3. Undo and Redo
Every action performed by the user is pushed onto a stack.
When Undo is clicked,
the latest action is removed.
Example
Type H
↓
Type E
↓
Type L
↓
Undo
↓
L Removed
JavaScript Example
const undoStack = [];
undoStack.push("Draw Circle");
undoStack.push("Insert Image");
undoStack.push("Write Text");
console.log(undoStack.pop());
console.log(undoStack);
Write Text
["Draw Circle","Insert Image"]
4. Function Call Stack
JavaScript itself uses a stack to execute functions.
Example:
function first(){
second();
}
function second(){
third();
}
function third(){
console.log("Inside Third");
}
first();
Execution Flow
Call first()
↓
Call second()
↓
Call third()
↓
Return third()
↓
Return second()
↓
Return first()
Call Stack
Top
third()
↓
second()
↓
first()
5. Expression Evaluation
Stacks are widely used for evaluating mathematical expressions.
Expression
5 + 3 × 2
Internally,
operators and operands are managed using stacks.
Applications include:
- Scientific calculators
- Spreadsheet software
- Programming language interpreters
Infix Expression
Normal mathematical notation.
Example
A+B*C
Prefix Expression
Operator appears first.
+A*BC
Postfix Expression
Operator appears last.
ABC*+
Comparison
| Type | Example |
|---|---|
| Infix | A+B |
| Prefix | +AB |
| Postfix | AB+ |
Why Use Prefix and Postfix?
They eliminate ambiguity.
Example
A+B*C
Needs precedence rules.
Whereas
ABC*+
can be evaluated directly.
6. Postfix Evaluation
Example
23+5*
Equivalent to
(2+3)*5
Evaluation
Read 2
↓
Push
↓
Read 3
↓
Push
↓
Read +
↓
Pop
↓
2+3
↓
Push 5
↓
Read *
↓
5×5
↓
25
JavaScript Example
function evaluatePostfix(){
const stack=[];
stack.push(2);
stack.push(3);
stack.push(stack.pop()+stack.pop());
stack.push(5);
stack.push(stack.pop()*stack.pop());
return stack.pop();
}
console.log(evaluatePostfix());
25
7. Depth First Search (DFS)
DFS uses a stack to traverse graphs and trees.
Visualization
A
│
├── B
│
├── D
│
└── E
│
└── C
│
└── F
Traversal
A
↓
B
↓
D
↓
E
↓
C
↓
F
Applications
- Maze solving
- File systems
- AI search
- Social networks
- Path finding
8. Next Greater Element
Given
2 1 5 3 6
5
5
6
6
-1
Complexity
O(n)
9. String Reversal
Stacks naturally reverse data.
Example
JAVA
↓
Push
J
A
V
A
↓
Pop
A
V
A
J
JavaScript Example
function reverseString(text){
const stack=[];
for(const character of text){
stack.push(character);
}
let reverse="";
while(stack.length){
reverse+=stack.pop();
}
return reverse;
}
console.log(reverseString("STACK"));
KCATS
10. Recursion
Every recursive function internally uses the call stack.
Example
function factorial(n){
if(n===1){
return 1;
}
return n*factorial(n-1);
}
console.log(factorial(5));
Call Stack
factorial(5)
↓
factorial(4)
↓
factorial(3)
↓
factorial(2)
↓
factorial(1)
↓
Return
↓
24
↓
120
Summary of Stack Applications
| Application | Stack Usage |
|---|---|
| Parentheses Matching | Store opening brackets |
| Browser History | Back navigation |
| Undo/Redo | Store user actions |
| Function Calls | JavaScript call stack |
| Expression Evaluation | Store operators and operands |
| DFS | Graph traversal |
| Next Greater Element | Monotonic stack |
| String Reversal | Reverse characters |
| Recursion | Manage recursive calls |
| Compilers | Syntax analysis |
Best Practices
- Check for stack underflow before calling
pop(). - Keep stack operations encapsulated in a dedicated class or utility.
- Prefer stack-based solutions when the problem involves reversing order or tracking the most recent element.
- Use descriptive variable names such as
stack,top, andcurrent.
Queues in JavaScript
What is a Queue?
A Queue is a linear data structure that follows the First In, First Out (FIFO) principle.
This means the first element inserted into the queue is the first element removed.
In simple words,
A Queue is a collection of elements where insertion takes place at the rear and deletion takes place at the front.
Definition
A Queue is a linear data structure in which elements are inserted at the rear and removed from the front, following the FIFO principle.
Real-World Analogy
Imagine people waiting in a ticket counter queue.
Front
↓
Person A
↓
Person B
↓
Person C
↓
Person D
↓
Rear
The first person who joins the queue gets served first.
FIFO Principle

Queue Representation
Front Rear
↓
┌────┬────┬────┬────┐
│ 10 │ 20 │ 30 │ 40 │
└────┴────┴────┴────┘
Why Use Queues?
Queues are useful whenever tasks must be processed in the same order in which they arrive.
Examples include:
- Printer queues
- CPU scheduling
- Ticket booking
- Customer service systems
- Task scheduling
- Network packet processing
- Background jobs
Queue Operations

Queue Implementation Using Arrays
class Queue {
constructor(){
this.items = [];
}
}
1. Enqueue Operation
What is Enqueue?
Enqueue inserts a new element at the rear of the queue.
Visualization
Before
Front
↓
10 → 20 → 30
Enqueue 40
After
Front
↓
10 → 20 → 30 → 40
↑
Rear
JavaScript Code
enqueue(element){
this.items.push(element);
}
Example
const queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
console.log(queue.items);
[10,20,30]
Complexity
| Operation | Complexity |
|---|---|
| Enqueue | O(1) |
2. Dequeue Operation
What is Dequeue?
Removes the element from the front.
Visualization
Before
Front
↓
10 → 20 → 30 → 40
After
Front
↓
20 → 30 → 40
Removed
10
JavaScript Code
dequeue(){
if(this.items.length===0){
return "Queue Underflow";
}
return this.items.shift();
}
Example
console.log(queue.dequeue());
Output
10
Complexity
| Operation | Complexity |
|---|---|
| Dequeue | O(n) |
Note: When a queue is implemented using a JavaScript array with shift(), removing the first element requires shifting all remaining elements, making the operation O(n). More efficient implementations using linked lists or front/rear indices achieve O(1) dequeue.
3. Front Operation
Returns the first element without removing it.
front(){
if(this.items.length===0){
return null;
}
return this.items[0];
}
Example
console.log(queue.front());
Output
20
Complexity
| Operation | Complexity |
|---|---|
| Front | O(1) |
4. Rear Operation
Returns the last element.
rear(){
if(this.items.length===0){
return null;
}
return this.items[this.items.length-1];
}
Example
console.log(queue.rear());
Output
30
Complexity
| Operation | Complexity |
|---|---|
| Rear | O(1) |
5. isEmpty()
Checks whether the queue contains elements.
isEmpty(){
return this.items.length===0;
}
Output
console.log(queue.isEmpty());
false
6. Size
Returns the total number of elements.
size(){
return this.items.length;
}
Output
console.log(queue.size());
2
Complete Queue Class
class Queue{
constructor(){
this.items=[];
}
enqueue(element){
this.items.push(element);
}
dequeue(){
if(this.items.length===0){
return "Queue Underflow";
}
return this.items.shift();
}
front(){
return this.items[0];
}
rear(){
return this.items[this.items.length-1];
}
isEmpty(){
return this.items.length===0;
}
size(){
return this.items.length;
}
display(){
console.log(this.items);
}
}
const queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.display();
console.log(queue.front());
console.log(queue.dequeue());
queue.display();
console.log(queue.rear());
console.log(queue.size());
console.log(queue.isEmpty());
Output
[10,20,30]
10
10
[20,30]
30
2
false
Queue Operations Flow
Enqueue(10)
↓
[10]
↓
Enqueue(20)
↓
[10,20]
↓
Enqueue(30)
↓
[10,20,30]
↓
Front()
↓
10
↓
Dequeue()
↓
[20,30]
Queue Using Linked List
Queues can also be implemented using a Linked List.
Front
↓
10 → 20 → 30 → 40
↑
Rear
Enqueue
10 → 20 → 30 → 40 → 50
Dequeue
20 → 30 → 40 → 50
By maintaining both front and rear references, both enqueue and dequeue operations can be performed in O(1) time.
Advantages of Queues
- Fair processing order
- Efficient scheduling
- Simple implementation
- Suitable for asynchronous task management
- Prevents starvation in many scheduling scenarios
Disadvantages
- No random access
- Array implementation using
shift()is inefficient for large queues - Only front and rear elements are directly accessible
Time Complexity
| Operation | Array Queue (shift) |
Linked List Queue |
|---|---|---|
| Enqueue | O(1) | O(1) |
| Dequeue | O(n) | O(1) |
| Front | O(1) | O(1) |
| Rear | O(1) | O(1) |
| Search | O(n) | O(n) |
| Display | O(n) | O(n) |
Real-World Applications
Queues are widely used in:
- Printer spoolers
- CPU scheduling
- Web server request handling
- Customer support systems
- Ticket reservation systems
- Background job processing
- Network packet routing
- Call centers
- BFS (Breadth-First Search)
- Message queues
Queue vs Stack
| Stack | Queue |
|---|---|
| LIFO | FIFO |
| Insert and delete from top | Insert at rear, delete from front |
push() / pop() |
enqueue() / dequeue() |
| Browser Undo | Printer Queue |
| DFS | BFS |
Advanced Queue Types in JavaScript
A standard queue follows the First In, First Out (FIFO) principle. However, many real-world applications require more specialized queue behavior.
For example:
- Operating systems need Priority Queues to schedule processes.
- Network routers use Circular Queues to efficiently manage packet buffers.
- Browsers and editors often use Double-Ended Queues (Deque).
- Graph algorithms such as Breadth-First Search (BFS) rely on queues for traversal.
In this section, we will explore these advanced queue types, understand their working principles, implement them in JavaScript, and examine their real-world applications.
Types of Advanced Queues
1. Circular Queue
What is a Circular Queue?
A Circular Queue is a queue where the last position is connected back to the first position, forming a circle.
Instead of wasting space after several dequeue operations, a circular queue reuses empty positions.
Why Do We Need a Circular Queue?
Consider a queue of size 5.
Initially
Front
↓
10 20 30 40 50
↑ ↑
Front Rear
After removing three elements
_ _ _ 40 50
↑ ↑
Front Rear
Although there are three empty positions, a normal queue cannot use them efficiently.
A Circular Queue wraps around.
60 70 _ 40 50
↑ ↑
Rear Front
Memory is utilized efficiently.
Real-World Applications
- CPU Scheduling
- Printer Buffer
- Keyboard Buffer
- Network Packet Buffer
- Streaming Applications
Circular Queue Visualization
Front
│
┌───────────┐
10 20
│ │
50 30
└────40─────┘
│
Rear
JavaScript Implementation
class CircularQueue{
constructor(size){
this.queue = new Array(size);
this.size = size;
this.front = -1;
this.rear = -1;
}
}
Enqueue Operation
enqueue(value){
if((this.rear+1)%this.size===this.front){
console.log("Queue Overflow");
return;
}
if(this.front===-1){
this.front=0;
}
this.rear=(this.rear+1)%this.size;
this.queue[this.rear]=value;
}
Dequeue Operation
dequeue(){
if(this.front===-1){
return null;
}
const value=this.queue[this.front];
if(this.front===this.rear){
this.front=this.rear=-1;
}else{
this.front=(this.front+1)%this.size;
}
return value;
}
Complexity
| Operation | Complexity |
|---|---|
| Enqueue | O(1) |
| Dequeue | O(1) |
Advantages
- Better memory utilization
- No unnecessary shifting
- Constant-time operations
- Ideal for fixed-size buffers
Disadvantages
- Fixed capacity
- Slightly more complex implementation
2. Priority Queue
What is a Priority Queue?
A Priority Queue stores elements along with a priority.
Elements with higher priority are processed before lower-priority elements, regardless of insertion order.
Example
Hospital Emergency Room
Patient A
Priority 2
↓
Patient B
Priority 5
↓
Patient C
Priority 1
Treatment Order
Patient B
↓
Patient A
↓
Patient C
Real-World Applications
- CPU Scheduling
- Emergency Services
- Dijkstra’s Algorithm
- AI Search Algorithms
- Task Scheduling
JavaScript Implementation
class PriorityQueue{
constructor(){
this.items=[];
}
enqueue(element,priority){
this.items.push({
element,
priority
});
this.items.sort(
(a,b)=>b.priority-a.priority
);
}
dequeue(){
return this.items.shift();
}
}
Example
const queue = new PriorityQueue();
queue.enqueue("Normal User",1);
queue.enqueue("Premium User",5);
queue.enqueue("VIP User",10);
console.log(queue.dequeue());
{ element: 'VIP User', priority: 10 }
Complexity
| Operation | Complexity |
|---|---|
| Insert | O(n log n)* |
| Delete | O(n)* |
*This simple implementation uses array sorting. A binary heap implementation improves insertion and removal to O(log n).
Advantages
- Fast access to highest-priority elements
- Efficient scheduling
- Better resource allocation
Disadvantages
- More complex implementation
- Additional memory overhead
3. Double-Ended Queue (Deque)
What is a Deque?
A Deque (Double-Ended Queue) allows insertion and deletion from both the front and rear.
Visualization
Front
↓
10 20 30 40
↑ ↑
Insert Insert
Delete Delete
Rear
Operations
- insertFront()
- insertRear()
- deleteFront()
- deleteRear()
JavaScript Implementation
class Deque{
constructor(){
this.items=[];
}
addFront(value){
this.items.unshift(value);
}
addRear(value){
this.items.push(value);
}
removeFront(){
return this.items.shift();
}
removeRear(){
return this.items.pop();
}
}
Example
const deque = new Deque();
deque.addFront(20);
deque.addFront(10);
deque.addRear(30);
deque.addRear(40);
console.log(deque.items);
Output
[10,20,30,40]
Complexity
| Operation | Complexity |
|---|---|
| Add Front | O(n)* |
| Add Rear | O(1) |
| Remove Front | O(n)* |
| Remove Rear | O(1) |
*For this array-based implementation. A dedicated deque data structure can provide O(1) operations at both ends.
Real-World Applications
- Browser history
- Sliding Window Algorithm
- Undo/Redo
- Task Scheduling
- Cache Management
Queue Using Linked List
Queues can also be implemented using a Linked List.
Maintain two pointers.
Front
↓
10 → 20 → 30 → 40
↑
Rear
Both enqueue and dequeue become O(1) operations.
Breadth-First Search (BFS)
Queues are heavily used in graph traversal.
Example Tree
A
/ \
B C
/ \ / \
D E F G
Traversal
A
↓
B
↓
C
↓
D
↓
E
↓
F
↓
G
Unlike DFS,
BFS visits nodes level by level.
BFS JavaScript Example
const queue=[];
queue.push("A");
while(queue.length){
const node=queue.shift();
console.log(node);
}
Circular Queue vs Normal Queue
| Feature | Normal Queue | Circular Queue |
|---|---|---|
| Memory Usage | Less Efficient | Efficient |
| Wrap Around | No | Yes |
| Fixed Size | Yes | Yes |
| Buffer Utilization | Poor | Excellent |
Queue Comparison
| Queue Type | Best Use Case |
|---|---|
| Simple Queue | Ticket booking |
| Circular Queue | CPU scheduling |
| Priority Queue | Operating systems |
| Deque | Browser history |
| Linked List Queue | Dynamic queues |
Real-World Applications
| Queue Type | Applications |
|---|---|
| Queue | Printer management |
| Circular Queue | Network routers |
| Priority Queue | Hospital emergency systems |
| Deque | Sliding window algorithms |
| BFS Queue | Graph traversal |
Best Practices
- Use a Circular Queue for fixed-size buffers.
- Use a Priority Queue when processing order depends on importance rather than arrival time.
- Use a Deque when insertion and deletion are required at both ends.
- Use a Linked List implementation when the queue size changes frequently.
- Choose the implementation that best matches the application’s performance requirements.
Hash Tables (Hash Maps) in JavaScript
What is a Hash Table?
A Hash Table is a non-linear data structure that stores data as key-value pairs. It uses a hash function to convert a key into an array index, allowing data to be stored and retrieved efficiently.
Unlike arrays, which use numeric indexes, hash tables allow meaningful keys such as strings or objects.
In simple words,
A Hash Table stores data using keys and values, enabling very fast insertion, deletion, and lookup operations.
Definition
A Hash Table is a data structure that maps keys to values using a hash function, enabling average O(1) time complexity for search, insertion, and deletion.
Real-World Analogy
Imagine a library locker system.
Each locker has a locker number.
Locker Number
101
↓
Books
----------------
Locker Number
102
↓
Magazines
----------------
Locker Number
103
↓
Newspapers
Instead of searching every locker, you directly open the locker with the correct number.
Hash Tables work in the same way.
Why Use Hash Tables?
Suppose a college stores student records.
Without a Hash Table:
Student Records
↓
Rahul
↓
Sneha
↓
Akshay
↓
Neha
Searching for Akshay requires checking multiple records.
Using a Hash Table:
Key
↓
"Akshay"
↓
Hash Function
↓
Index
↓
Student Record
The record is found almost instantly.
Key Components
Every Hash Table has three important components.
Key
The unique identifier.
Examples
Roll Number
Email
Username
Product ID
Employee ID
Value
The actual information associated with the key.
Example
Key
↓
101
↓
Value
↓
Akshay Homkar
Hash Function
A Hash Function converts a key into an array index.
Example
Key
↓
"Apple"
↓
Hash Function
↓
Index 4
The value is stored at index 4.
Internal Representation
Index
0
↓
Null
1
↓
Rahul
2
↓
Null
3
↓
Sneha
4
↓
Akshay
5
↓
Neha
Hash Function Example
Suppose
APPLE
ASCII values
A = 65
P = 80
P = 80
L = 76
E = 69
Sum
65 + 80 + 80 + 76 + 69 = 370
If the table size is 10
370 % 10 = 0
The data is stored at index 0.
JavaScript Objects as Hash Tables
JavaScript objects naturally behave like hash tables.
const student = {
rollNumber:101,
name:"Akshay",
department:"Computer Science"
};
console.log(student.name);
Output
Akshay
Using Map
JavaScript also provides the Map object.
const students = new Map();
students.set(101,"Akshay");
students.set(102,"Rahul");
students.set(103,"Sneha");
console.log(students.get(102));
Output
Rahul
Common Hash Table Operations
Insert Operation
const users = new Map();
users.set("admin","Akshay");
users.set("guest","Rahul");
console.log(users);
Complexity
| Operation | Complexity |
|---|---|
| Insert | O(1) Average |
Search Operation
console.log(users.get("admin"));
Output
Akshay
Complexity
| Operation | Complexity |
|---|---|
| Search | O(1) Average |
Update Operation
users.set("guest","Sneha");
console.log(users.get("guest"));
Output
Sneha
Delete Operation
users.delete("admin");
console.log(users);
Complexity
| Operation | Complexity |
|---|---|
| Delete | O(1) Average |
Checking Key Existence
console.log(users.has("guest"));
Output
true
Iterating Through a Hash Table
for(const [key,value] of users){
console.log(
key,
value
);
}
Output
guest Sneha
Collision in Hash Tables
What is a Collision?
A collision occurs when two different keys generate the same array index.
Example
Key A
↓
Index 3
Key B
↓
Index 3
Both keys want to occupy the same position.
Collision Visualization
Index
3
↓
Apple
↓
Orange
↓
Mango
Multiple values compete for the same index.
Why Do Collisions Occur?
Because:
- Table size is limited.
- Different keys may produce the same hash value.
- No hash function is perfect.
Collision Resolution Techniques
There are two major approaches.
Collision
│
┌─────────┴─────────┐
│ │
Chaining Open Addressing
│
┌────────────┼────────────┐
│ │ │
Linear Probing Quadratic Double Hashing
Method 1: Separate Chaining
Each array position stores a linked list (or another collection) of entries.
Visualization
Index
3
↓
Apple
↓
Orange
↓
Mango
All entries remain accessible through the chain.
JavaScript Example
const table = [];
table[3] = ["Apple","Orange","Mango"];
console.log(table[3]);
Output
["Apple","Orange","Mango"]
Advantages
- Easy implementation
- Handles many collisions
- Flexible storage
Disadvantages
- Extra memory required
- Slower lookup when chains become long
Method 2: Linear Probing
Instead of creating a chain, the algorithm searches for the next available position.
Visualization
Original Index
↓
3
↓
Occupied
↓
Check 4
↓
Occupied
↓
Check 5
↓
Store Here
Advantages
- No linked list required
- Better cache locality
Disadvantages
- Clustering
- Performance decreases as the table fills
Hash Table vs Array
| Feature | Array | Hash Table |
|---|---|---|
| Access by Index | O(1) | O(1) Average |
| Search by Value | O(n) | O(1) Average (using key) |
| Uses Keys | No | Yes |
| Stores Key-Value Pairs | No | Yes |
| Collision Handling | Not Required | Required |
Object vs Map in JavaScript
| Feature | Object | Map |
|---|---|---|
| Key Types | Strings and Symbols | Any Data Type |
| Maintains Insertion Order | Generally for string keys (with specific rules) | Yes |
| Built-in Size Property | No | Yes (size) |
| Iteration | Less convenient | Easy |
| Performance for Frequent Updates | Good | Often better for dynamic collections |
Time Complexity
| Operation | Average | Worst Case |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
The worst case occurs when many keys collide and end up in the same bucket or probe sequence.
Real-World Applications
Hash Tables are used in:
- User authentication
- DNS lookup
- Database indexing
- Compiler symbol tables
- Caching systems
- Session management
- Search engines
- Shopping carts
- Routing tables
- Blockchain wallets
Best Practices
- Choose unique and meaningful keys.
- Use
Mapwhen keys are not limited to strings or symbols. - Design good hash functions to reduce collisions.
- Resize the table when the load factor becomes high.
- Avoid excessive collisions by selecting an appropriate table size.
Trees in JavaScript
What is a Tree?
A Tree is a non-linear hierarchical data structure consisting of nodes connected by edges. Unlike arrays, linked lists, stacks, and queues, which store data linearly, trees organize data in parent-child relationships.
A tree starts with a single node called the Root, and every other node is connected through branches.
In simple words,
A Tree is a hierarchical collection of nodes where one node acts as the root and every other node is connected through parent-child relationships.
Definition
A Tree is a hierarchical non-linear data structure consisting of nodes connected by edges, where one node is designated as the root and every node (except the root) has exactly one parent.
Real-World Analogy
Consider a company’s organizational hierarchy.
CEO
┌──────┴──────┐
Manager A Manager B
┌────┴────┐ │
Employee1 Employee2 Employee3
Each employee reports to exactly one manager, forming a tree-like structure.
Why Do We Need Trees?
Suppose a university stores its departments.
Using an array:
Computer Science
Information Technology
Mechanical
Civil
Electronics
Finding relationships between departments is difficult.
Using a tree:
University
│
├── Engineering
│ ├── Computer Science
│ ├── Information Technology
│ └── Mechanical
│
└── Management
Relationships become easy to understand and manage.
Components of a Tree
A tree consists of several important components.
Tree Terminology
Understanding tree terminology is essential before implementing tree algorithms.
Root Node
The topmost node of the tree.
A
/ \
B C
Here,
A is the Root.
Parent Node
A node that has one or more child nodes.
A
/
B
A is the parent of B.
Child Node
A node connected below a parent.
A
/
B
B is the child of A.
Leaf Node
Nodes that have no children.
A
/ \
B C
/ \
D E
Leaf Nodes:
B
D
E
Edge
The connection between two nodes.
A
│
B
There is one edge between A and B.
Sibling Nodes
Nodes having the same parent.
A
/ \
B C
B and C are siblings.
Ancestor
Any node above the current node.
A
↓
B
↓
C
Ancestors of C
A
B
Descendant
Any node below the current node.
A
↓
B
↓
C
Descendants of A
B
C
Degree of a Node
The number of children a node has.
Example
A
/ | \
B C D
Degree of A = 3
Level
The distance of a node from the root.
Level 0
A
Level 1
B C
Level 2
D E
Height of a Tree
The number of edges on the longest path from the root to a leaf.
A
/
B
/
C
/
D
Height = 3
Depth of a Node
The number of edges from the root to a particular node.
Example
A
↓
B
↓
C
Depth of C = 2
Tree Representation
A
/ \
B C
/ \ / \
D E F G
Binary Tree
What is a Binary Tree?
A Binary Tree is a tree in which each node has at most two children.
These children are called:
- Left Child
- Right Child
Representation
A
/ \
B C
/ \ / \
D E F G
JavaScript Node Class
class TreeNode{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
Creating a Binary Tree
const root = new TreeNode("A");
root.left = new TreeNode("B");
root.right = new TreeNode("C");
root.left.left = new TreeNode("D");
root.left.right = new TreeNode("E");
console.log(root);
Visualization
A
/ \
B C
/ \
D E
Types of Binary Trees
Full Binary Tree
Every node has either:
- 0 children
- 2 children
Example
A
/ \
B C
/ \
D E
Complete Binary Tree
Every level is completely filled except possibly the last.
Nodes in the last level are filled from left to right.
A
/ \
B C
/ \ /
D E F
Perfect Binary Tree
All internal nodes have exactly two children.
All leaf nodes are at the same level.
A
/ \
B C
/ \ / \
D E F G
Balanced Binary Tree
The height difference between the left and right subtrees of every node is small (commonly at most one in AVL trees).
A
/ \
B C
/ \
D E
Balanced trees improve search efficiency.
Degenerate Tree
Every node has only one child.
A
↓
B
↓
C
↓
D
It behaves similarly to a linked list.
Advantages of Trees
- Represent hierarchical relationships naturally
- Efficient searching and sorting (with Binary Search Trees)
- Dynamic size
- Used in indexing and file systems
- Foundation for many advanced algorithms
Disadvantages of Trees
- More complex implementation than linear data structures
- Extra memory for references
- Unbalanced trees may reduce performance
- Traversal algorithms are more involved than arrays or linked lists
Time Complexity (General Binary Tree)
| Operation | Complexity |
|---|---|
| Traversal | O(n) |
| Search | O(n) |
| Insert | O(n) |
| Delete | O(n) |
Note: These complexities apply to a general binary tree. Binary Search Trees (BSTs) provide better average-case performance, which is covered in the next section.
Real-World Applications
Trees are widely used in:
- File systems
- Database indexing
- XML and HTML document parsing
- Domain Name System (DNS)
- Organization charts
- Decision trees in Machine Learning
- Expression trees
- Artificial Intelligence
- Compiler syntax trees
- Search engines
Binary Search Trees (BST) in JavaScript
What is a Binary Search Tree (BST)?
A Binary Search Tree (BST) is a special type of Binary Tree in which every node follows a specific ordering rule.
For every node:
- All values in the left subtree are smaller than the node.
- All values in the right subtree are greater than the node.
This property allows searching, insertion, and deletion to be performed much more efficiently than in a normal binary tree.
In simple words,
A Binary Search Tree stores data in sorted order by placing smaller values on the left and larger values on the right.
Definition
A Binary Search Tree is a binary tree in which every node satisfies the Binary Search Property:
- Left Child < Parent
- Right Child > Parent
Why Do We Need BST?
Suppose we store numbers in a normal binary tree.
40
/ \
60 20
/ \
10 50
Searching for 50 requires checking multiple nodes because there is no ordering.
Now consider a BST.
40
/ \
20 60
/ \ / \
10 30 50 70
Searching becomes much faster because each comparison eliminates half of the remaining tree.
Binary Search Property
Every node follows this rule.
Parent
/ \
Smaller Larger
Example
50
/ \
30 70
/ \ / \
20 40 60 80
Every node satisfies the BST property.
Real-World Analogy
Imagine a dictionary.
Words are arranged alphabetically.
Searching for Computer:
- Ignore half the pages after each comparison.
- Quickly reach the desired word.
BST works similarly.
Characteristics of BST
- Binary Tree
- Ordered structure
- No duplicate values (in the basic implementation)
- Efficient searching
- Efficient insertion
- Efficient deletion
- Recursive structure
Node Structure
class TreeNode{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
Creating the BST Class
class BinarySearchTree{
constructor(){
this.root = null;
}
}
Initially,
Root
↓
Null
Building a BST
Suppose we insert:
50
30
70
20
40
60
80
Final Tree
50
/ \
30 70
/ \ / \
20 40 60 80
BST Insertion
Algorithm
- If the tree is empty, create the root.
- Compare the new value with the current node.
- If smaller, move left.
- If larger, move right.
- Repeat until an empty position is found.
Visualization
Insert 35
Before
50
/
30
/ \
20 40
After
50
/
30
/ \
20 40
/
35
JavaScript Implementation
class TreeNode{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
const node = new TreeNode(data);
if(this.root===null){
this.root=node;
return;
}
this.insertNode(this.root,node);
}
insertNode(current,newNode){
if(newNode.data<current.data){
if(current.left===null){
current.left=newNode;
}else{
this.insertNode(current.left,newNode);
}
}
else{
if(current.right===null){
current.right=newNode;
}else{
this.insertNode(current.right,newNode);
}
}
}
}
Example
const bst = new BinarySearchTree();
bst.insert(50);
bst.insert(30);
bst.insert(70);
bst.insert(20);
bst.insert(40);
bst.insert(60);
bst.insert(80);
console.log(bst.root);
Complexity
| Operation | Average | Worst |
|---|---|---|
| Insert | O(log n) | O(n) |
Searching in BST
Algorithm
- Start from the root.
- Compare the target value.
- If equal → Found.
- If smaller → Move left.
- If larger → Move right.
- Continue until found or
null.
Visualization
Search 60
50
↓
70
↓
60
Found
JavaScript Implementation
search(node,value){
if(node===null){
return false;
}
if(value===node.data){
return true;
}
if(value<node.data){
return this.search(node.left,value);
}
return this.search(node.right,value);
}
Example
console.log(bst.search(bst.root,60));
Output
true
Complexity
| Operation | Average | Worst |
|---|---|---|
| Search | O(log n) | O(n) |
Finding Minimum Value
The minimum value is the leftmost node.
Visualization
50
/
30
/
20
↓
Minimum
JavaScript
findMin(node){
while(node.left){
node=node.left;
}
return node.data;
}
Output
console.log(
bst.findMin(bst.root)
);
20
Finding Maximum Value
The maximum value is the rightmost node.
findMax(node){
while(node.right){
node=node.right;
}
return node.data;
}
Output
console.log(bst.findMax(bst.root));
80
BST Search Visualization
Searching 25
50
/
30
/
20
↓
25 > 20
↓
Right Child
↓
Null
↓
Not Found
Advantages of BST
- Fast searching
- Efficient insertion
- Efficient deletion
- Data remains sorted
- Easy range queries
- Foundation for self-balancing trees
Disadvantages
- Can become unbalanced
- Worst-case performance becomes O(n)
- More memory than arrays
- Recursive implementation may increase stack usage
Binary Tree vs Binary Search Tree
| Binary Tree | Binary Search Tree |
|---|---|
| No ordering | Ordered |
| Search O(n) | Average O(log n) |
| Any structure | Must follow BST property |
| Suitable for hierarchy | Suitable for searching |
Time Complexity
| Operation | Average | Worst Case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Find Minimum | O(log n) | O(n) |
| Find Maximum | O(log n) | O(n) |
Worst-case performance occurs when the BST becomes skewed (for example, inserting sorted data into an unbalanced BST).
Real-World Applications
Binary Search Trees are used in:
- Database indexing
- Dictionary implementations
- Contact management systems
- Student record systems
- Product catalogs
- Search engines
- Compiler symbol tables
- Leaderboards
- Memory allocation systems
- File indexing
Best Practices
- Keep the tree balanced whenever possible.
- Avoid inserting already sorted data into a simple BST.
- Use self-balancing trees (such as AVL or Red-Black Trees) when frequent insertions and deletions occur.
- Validate the BST property after complex operations.
Binary Search Tree Operations and Tree Traversals
A Binary Search Tree becomes powerful because it supports efficient searching, insertion, deletion, and multiple traversal techniques.
In this section, we will learn:
- BST Deletion
- Tree Traversals
- Recursive Traversals
- Level Order Traversal (Breadth-First Search)
- Tree Height
- Leaf Node Counting
- Balanced Tree Checking
Overview of BST Operations

BST Deletion
Deletion is the most challenging BST operation because it has three different cases.
Case 1: Delete a Leaf Node
A leaf node has no children.
Example
Before
50
/ \
30 70
/ \
20 40
Delete 20
After
50
/ \
30 70
\
40
Simply remove the node.
Case 2: Delete a Node with One Child
Example
Before
50
/
30
\
40
Delete 30
After
50
/
40
The child replaces the deleted node.
Case 3: Delete a Node with Two Children
This is the most important interview question.
Example
50
/ \
30 70
/ \ / \
20 40 60 80
Delete 50
Step 1
Find the Inorder Successor
The Inorder Successor is the smallest value in the right subtree.
Right Subtree
70
/
60
↓
Successor = 60
Step 2
Replace 50 with 60.
60
/ \
30 70
/ \ \
20 40 80
Finally, delete the original node containing 60 from the right subtree.
JavaScript Implementation
delete(node, value){
if(node === null){
return null;
}
if(value < node.data){
node.left = this.delete(node.left, value);
}
else if(value > node.data){
node.right = this.delete(node.right, value);
}
else{
// Case 1: No child
if(node.left === null && node.right === null){
return null;
}
// Case 2: One child
if(node.left === null){
return node.right;
}
if(node.right === null){
return node.left;
}
// Case 3: Two children
let successor = this.findMinNode(node.right);
node.data = successor.data;
node.right = this.delete(node.right, successor.data);
}
return node;
}
Helper Function
findMinNode(node){
while(node.left){
node = node.left;
}
return node;
}
Complexity
| Operation | Average | Worst |
|---|---|---|
| Delete | O(log n) | O(n) |
Tree Traversals
Traversal means visiting every node exactly once.
There are four major traversal techniques.
Tree Traversals
│
┌─────────────┼─────────────┐
│ │ │
Inorder Preorder Postorder
│
Level Order
Sample Tree
We will use the following tree for every traversal.
50
/ \
30 70
/ \ / \
20 40 60 80
1. Inorder Traversal
Rule
Left
↓
Root
↓
Right
Visualization
20
↓
30
↓
40
↓
50
↓
60
↓
70
↓
80
Notice that the output is in sorted order.
JavaScript Implementation
inorder(node){
if(node !== null){
this.inorder(node.left);
console.log(node.data);
this.inorder(node.right);
}
}
Output
20
30
40
50
60
70
80
Applications
- Display sorted data
- Database indexing
- Binary Search Tree validation
2. Preorder Traversal
Rule
Root
↓
Left
↓
Right
Visualization
50
↓
30
↓
20
↓
40
↓
70
↓
60
↓
80
JavaScript
preorder(node){
if(node){
console.log(node.data);
this.preorder(node.left);
this.preorder(node.right);
}
}
Output
50
30
20
40
70
60
80
Applications
- Copying trees
- Expression trees
- Directory structure creation
3. Postorder Traversal
Rule
Left
↓
Right
↓
Root
Visualization
20
↓
40
↓
30
↓
60
↓
80
↓
70
↓
50
JavaScript
postorder(node){
if(node){
this.postorder(node.left);
this.postorder(node.right);
console.log(node.data);
}
}
Output
20
40
30
60
80
70
50
Applications
- Deleting trees
- Memory cleanup
- Expression evaluation
Traversal Comparison
| Traversal | Order |
|---|---|
| Inorder | Left → Root → Right |
| Preorder | Root → Left → Right |
| Postorder | Left → Right → Root |
4. Level Order Traversal (Breadth-First Search)
Level Order Traversal visits nodes level by level.
Visualization
Level 0
50
↓
Level 1
30
70
↓
Level 2
20
40
60
80
Output
50
30
70
20
40
60
80
JavaScript Implementation
levelOrder(root){
if(root===null){
return;
}
const queue=[];
queue.push(root);
while(queue.length){
const current=queue.shift();
console.log(current.data);
if(current.left){
queue.push(current.left);
}
if(current.right){
queue.push(current.right);
}
}
}
Complexity
| Time | Space |
|---|---|
| O(n) | O(n) |
Applications
- Breadth-First Search (BFS)
- Network routing
- Shortest path in unweighted graphs
- Level-wise processing
Calculating Tree Height
What is Height?
Height is the number of edges on the longest path from the root to a leaf.
Example
50
/
30
/
20
/
10
Height = 3
JavaScript
height(node){
if(node===null){
return -1;
}
return Math.max(
this.height(node.left),
this.height(node.right)
)+1;
}
Complexity
| Time | Space |
|---|---|
| O(n) | O(h) |
Where h is the height of the recursion stack.
Counting Leaf Nodes
Leaf nodes have no children.
Example
50
/ \
30 70
/ \
20 40
Leaf Nodes
20
40
70
Count = 3
JavaScript
countLeaves(node){
if(node===null){
return 0;
}
if(node.left===null && node.right===null){
return 1;
}
return this.countLeaves(node.left)
+ this.countLeaves(node.right);
}
Complexity
| Time | Space |
|---|---|
| O(n) | O(h) |
Checking Whether a Tree is Balanced
A balanced tree maintains a small height difference between the left and right subtrees of every node.
Balanced
50
/ \
30 70
Unbalanced
50
↓
40
↓
30
↓
20
Balanced trees provide much better performance for searching and insertion.
Summary of Traversals
| Traversal | Order | Uses |
|---|---|---|
| Inorder | Left → Root → Right | Sorted output in BST |
| Preorder | Root → Left → Right | Copy tree, serialization |
| Postorder | Left → Right → Root | Delete tree, evaluate expressions |
| Level Order | Level by Level | BFS, shortest paths |
Time Complexity
| Operation | Complexity |
|---|---|
| Inorder | O(n) |
| Preorder | O(n) |
| Postorder | O(n) |
| Level Order | O(n) |
| Height | O(n) |
| Count Leaves | O(n) |
| Delete | O(log n) Average |
Real-World Applications
Tree traversals are widely used in:
- File system navigation
- Database indexing
- XML and HTML document parsing
- Compiler syntax trees
- Artificial Intelligence search
- Decision tree evaluation
- Network topology analysis
- Organization hierarchy processing
AVL Trees and Heap Data Structures in JavaScript
After learning Binary Search Trees (BST), one important question naturally arises:
What happens if the BST becomes unbalanced?
An unbalanced BST behaves like a Linked List, causing search, insertion, and deletion operations to degrade from O(log n) to O(n).
To solve this problem, self-balancing trees such as AVL Trees were introduced.
Another important structure is the Heap, which efficiently manages priority-based data.
Overview
AVL Tree
What is an AVL Tree?
An AVL Tree is a Self-Balancing Binary Search Tree.
It automatically maintains balance after every insertion and deletion.
The name AVL comes from its inventors:
- Adelson-Velsky
- Landis
Why Do We Need AVL Trees?
Consider inserting numbers into a BST.
10
↓
20
↓
30
↓
40
↓
50
The tree becomes
10
↓
20
↓
30
↓
40
↓
50
Searching now becomes
O(n)
instead of
O(log n)
AVL Trees automatically rebalance the tree.
Balanced AVL Tree
30
/ \
20 40
/ \
10 50
The height remains small.
AVL Property
For every node,
| Height(Left)
-
Height(Right) |
≤ 1
This value is called the Balance Factor.
Balance Factor
Formula
Balance Factor
=
Height(Left)
-
Height(Right)
Possible values
-1
0
1
Any other value means the tree is unbalanced.
Example
30
/ \
20 40
Left Height = 1
Right Height = 1
Balance Factor
0
Balanced.
Unbalanced Example
50
↓
40
↓
30
↓
20
Balance Factor becomes
2
Tree must be rotated.
AVL Rotations
AVL Trees use four rotations.

1. Left-Left (LL) Rotation
Occurs when a node is inserted into the left subtree of the left child.
Before
30
/
20
/
10
After Right Rotation
20
/ \
10 30
2. Right-Right (RR) Rotation
Occurs when insertion happens in the right subtree of the right child.
Before
10
\
20
\
30
After Left Rotation
20
/ \
10 30
3. Left-Right (LR) Rotation
Before
30
/
10
\
20
Step 1
Left Rotation
Step 2
Right Rotation
Result
20
/ \
10 30
4. Right-Left (RL) Rotation
Before
10
\
30
/
20
Step 1
Right Rotation
Step 2
Left Rotation
Result
20
/ \
10 30
AVL Node
class AVLNode{
constructor(data){
this.data=data;
this.left=null;
this.right=null;
this.height=1;
}
}
Advantages of AVL Trees
- Guaranteed balance
- Fast searching
- Fast insertion
- Fast deletion
- Predictable performance
Disadvantages
- More complex implementation
- Additional memory for height
- Rotations increase insertion overhead
AVL Complexity
| Operation | Complexity |
|---|---|
| Search | O(log n) |
| Insert | O(log n) |
| Delete | O(log n) |
Heap Data Structure
What is a Heap?
A Heap is a Complete Binary Tree that satisfies the Heap Property.
Unlike a BST,
a Heap does not maintain sorted order.
Instead,
it guarantees that the root has either the minimum or maximum value.
Types of Heap
Min Heap
The parent node is always smaller than its children.
10
/ \
20 30
/ \
40 50
Smallest value
10
is always at the root.
Max Heap
The parent node is always greater than its children.
90
/ \
70 60
/ \
30 20
Largest value
90
is always at the root.
Complete Binary Tree
A Heap must always be a Complete Binary Tree.
A
/ \
B C
/ \ /
D E F
Every level is filled except possibly the last.
Array Representation
Unlike BST,
Heaps are stored using arrays.
Tree
50
/ \
30 40
/ \
10 20
Array
Index
0 1 2 3 4
50 30 40 10 20
Parent and Child Formula
For index i
Left Child
2i + 1
Right Child
2i + 2
Parent
(i - 1) / 2
Heap Insertion
Insert
60
Step 1
Place at the end.
50
30
40
10
20
60
Step 2
Compare with parent.
Step 3
Swap until Heap Property is satisfied.
Heapify
Heapify restores the Heap Property.
Example
20
↓
40
↓
60
After Heapify
60
↓
40
↓
20
JavaScript Heap Class
class MaxHeap{
constructor(){
this.heap=[];
}
}
Insert Operation
insert(value){
this.heap.push(value);
}
A complete heap implementation will also perform heapify-up after insertion.
Delete Root
Deleting the root involves:
- Replace the root with the last element.
- Remove the last element.
- Perform heapify-down.
Heap Sort
Heap Sort uses a Heap for sorting.
Steps
- Build Heap
- Remove root
- Heapify
- Repeat
Complexity
| Operation | Complexity |
|---|---|
| Build Heap | O(n) |
| Insert | O(log n) |
| Delete Root | O(log n) |
| Peek | O(1) |
| Heap Sort | O(n log n) |
AVL vs BST
| Feature | BST | AVL |
|---|---|---|
| Self-Balancing | No | Yes |
| Search | O(log n) Average | O(log n) Guaranteed |
| Worst Search | O(n) | O(log n) |
| Rotations | No | Yes |
Heap vs BST
| Heap | BST |
|---|---|
| Parent follows Heap Property | Left < Root < Right |
| Fast root access | Fast searching |
| Used in Priority Queues | Used in Searching |
| Stored in arrays | Usually linked nodes |
Real-World Applications
AVL Trees
- Database indexing
- Memory management
- File systems
- Routing tables
Heaps
- Priority Queues
- CPU Scheduling
- Dijkstra’s Algorithm
- Task Scheduling
- Event Simulation
- Heap Sort
Graphs in JavaScript
What is a Graph?
A Graph is a non-linear data structure consisting of a collection of vertices (nodes) connected by edges.
Unlike trees, graphs do not have a root node and can contain cycles, multiple paths, and disconnected components.
In simple words,
A Graph is a collection of nodes connected through edges that represent relationships between different entities.
Definition
A Graph is a non-linear data structure represented as:
Graph = (V, E)
Where:
- V = Set of Vertices (Nodes)
- E = Set of Edges (Connections)
Real-World Analogy
Consider a road map.
City A -------- City B
│ │
│ │
City C -------- City D
Cities represent vertices, while roads represent edges.
Why Do We Need Graphs?
Suppose we want to represent friendships.
Using arrays:
Akshay
Rahul
Sneha
Neha
Relationships cannot be represented effectively.
Using a graph:
Akshay ----- Rahul
│
Sneha ----- Neha
Connections become easy to visualize and process.
Components of a Graph
Vertex (Node)
A Vertex represents an individual object.
Examples:
- Person
- City
- Computer
- Web Page
- Router
Visualization
A
B
C
D
Edge
An Edge represents the connection between two vertices.
A ------- B
Weighted Edge
Some graphs assign a value to each edge.
Example
A -----5----- B
\
2
\
C
Weights may represent:
- Distance
- Time
- Cost
- Bandwidth
Types of Graphs

Undirected Graph
Connections work in both directions.
A -------- B
|
|
C
If A is connected to B,
then B is also connected to A.
Examples
- Facebook Friends
- LAN Network
- Railway Connections
Directed Graph
Edges have direction.
A -----> B
↓
C
A connection from A to B does not imply a connection from B to A.
Examples
- Twitter Follow
- Instagram Follow
- YouTube Subscription
- Website Links
Weighted Graph
Edges contain weights.
A ----5---- B
\
3
\
C
Applications
- Google Maps
- GPS Navigation
- Airline Routes
- Delivery Systems
Unweighted Graph
All edges are equal.
A ----- B
|
|
C
Cyclic Graph
Contains one or more cycles.
A
/ \
B---C
You can start at one vertex and return to it by following the edges.
Acyclic Graph
Contains no cycles.
A
|
B
|
C
|
D
Connected Graph
Every vertex can be reached.
A ---- B
| |
C ---- D
Disconnected Graph
Some vertices are isolated.
A ---- B
C ---- D
E
Graph Terminology
Adjacent Vertices
Vertices connected directly.
A ----- B
A and B are adjacent.
Degree
Number of edges connected to a vertex.
B
|
A ----C---- D
|
E
Degree of C = 4
Path
Sequence of connected vertices.
A
↓
B
↓
C
↓
D
Path
A → B → C → D
Cycle
A path that begins and ends at the same vertex.
A
↓
B
↓
C
↓
A
Graph Representation
Graphs can be stored in two ways.
Graph
│
┌─────────┴─────────┐
│ │
Adjacency Matrix Adjacency List
Adjacency Matrix
Uses a two-dimensional array.
Example
A B C D
A [0 1 1 0]
B [1 0 0 1]
C [1 0 0 1]
D [0 1 1 0]
Advantages
- Fast edge lookup
- Simple implementation
Disadvantages
- Wastes memory for sparse graphs
- O(V²) space complexity
Adjacency List
Stores neighboring vertices.
Example
A → B → C
B → A → D
C → A → D
D → B → C
Advantages
- Efficient memory usage
- Faster traversal of sparse graphs
Disadvantages
- Slightly slower edge lookup than an adjacency matrix
JavaScript Graph Class
class Graph{
constructor(){
this.adjacencyList={};
}
}
Adding a Vertex
addVertex(vertex){
if(!this.adjacencyList[vertex]){
this.adjacencyList[vertex]=[];
}
}
Adding an Edge
addEdge(vertex1,vertex2){
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
Creating a Graph
const graph=new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addEdge("A","B");
graph.addEdge("A","C");
console.log(graph.adjacencyList);
Output
{
A:['B','C'],
B:['A'],
C:['A']
}
Graph Visualization
A
/ \
B C
\ /
D
Adjacency List
A → B, C
B → A, D
C → A, D
D → B, C
Time Complexity
| Representation | Space | Edge Lookup |
|---|---|---|
| Adjacency Matrix | O(V²) | O(1) |
| Adjacency List | O(V+E) | O(V) |
Advantages of Graphs
- Represents complex relationships
- Flexible structure
- Efficient traversal algorithms
- Suitable for large networks
- Models real-world systems naturally
Disadvantages
- More complex implementation
- Traversal algorithms can be computationally intensive
- Dense graphs require more memory
- Cycle handling increases algorithm complexity
Real-World Applications
Graphs are used in:
- Google Maps
- GPS Navigation
- Computer Networks
- Airline Route Planning
- Blockchain Networks
- Recommendation Systems
- Search Engines
- Web Crawlers
- Knowledge Graphs
- Dependency Management
Graph Traversal Algorithms in JavaScript
Graph Traversal is the process of visiting every vertex of a graph exactly once in a systematic manner.
There are two fundamental graph traversal algorithms:
- Breadth-First Search (BFS)
- Depth-First Search (DFS)
Both algorithms visit every node, but they do so in different orders and are suited for different types of problems.
Overview
Sample Graph
We will use the following graph throughout this section.
A
/ \
B C
/ \ / \
D E F G
Adjacency List
A → B, C
B → A, D, E
C → A, F, G
D → B
E → B
F → C
G → C
Breadth-First Search (BFS)
What is BFS?
Breadth-First Search visits vertices level by level.
Instead of going deep into one branch, BFS first visits all neighboring vertices before moving to the next level.
It uses a Queue to maintain the order of traversal.
How BFS Works
Algorithm
- Start from the source vertex.
- Mark it as visited.
- Insert it into the queue.
- Remove one vertex from the queue.
- Visit all unvisited neighbors.
- Repeat until the queue becomes empty.
BFS Visualization
Start from A
Queue
[A]
Visit
A
↓
Queue
[B,C]
Visit
B
↓
Queue
[C,D,E]
Visit
C
↓
Queue
[D,E,F,G]
Traversal
A
↓
B
↓
C
↓
D
↓
E
↓
F
↓
G
BFS JavaScript Implementation
class Graph{
constructor(){
this.adjacencyList={};
}
addVertex(vertex){
if(!this.adjacencyList[vertex]){
this.adjacencyList[vertex]=[];
}
}
addEdge(vertex1,vertex2){
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
bfs(start){
const queue=[start];
const visited={};
visited[start]=true;
while(queue.length){
const vertex=queue.shift();
console.log(vertex);
for(const neighbor of this.adjacencyList[vertex]){
if(!visited[neighbor]){
visited[neighbor]=true;
queue.push(neighbor);
}
}
}
}
}
Example
const graph=new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addVertex("E");
graph.addVertex("F");
graph.addVertex("G");
graph.addEdge("A","B");
graph.addEdge("A","C");
graph.addEdge("B","D");
graph.addEdge("B","E");
graph.addEdge("C","F");
graph.addEdge("C","G");
graph.bfs("A");
Output
A
B
C
D
E
F
G
Complexity
| Operation | Complexity |
|---|---|
| Time | O(V + E) |
| Space | O(V) |
Where:
- V = Number of Vertices
- E = Number of Edges
Applications of BFS
- Shortest path in unweighted graphs
- Social network analysis
- GPS navigation
- Web crawlers
- Broadcasting systems
- Network routing
Depth-First Search (DFS)
What is DFS?
Depth-First Search explores one path completely before backtracking.
DFS uses:
- Recursion, or
- Stack
How DFS Works
Algorithm
- Visit current vertex.
- Mark it as visited.
- Move to an unvisited neighbor.
- Continue until no unvisited neighbors remain.
- Backtrack.
- Repeat until all vertices are visited.
DFS Visualization
A
↓
B
↓
D
↑
↓
E
↑
↓
C
↓
F
↑
↓
G
Traversal
A
↓
B
↓
D
↓
E
↓
C
↓
F
↓
G
Recursive DFS
dfs(vertex,visited={}){
visited[vertex]=true;
console.log(vertex);
for(const neighbor of this.adjacencyList[vertex]){
if(!visited[neighbor]){
this.dfs(neighbor,visited);
}
}
}
Example
graph.dfs("A");
Output
A
B
D
E
C
F
G
Complexity
| Operation | Complexity |
|---|---|
| Time | O(V + E) |
| Space | O(V) |
Iterative DFS Using Stack
Instead of recursion, we can explicitly use a stack.
iterativeDFS(start){
const stack=[start];
const visited={};
while(stack.length){
const vertex=stack.pop();
if(!visited[vertex]){
visited[vertex]=true;
console.log(vertex);
for(const neighbor of this.adjacencyList[vertex].reverse()){
if(!visited[neighbor]){
stack.push(neighbor);
}
}
}
}
}
BFS vs DFS
| Feature | BFS | DFS |
|---|---|---|
| Data Structure | Queue | Stack / Recursion |
| Traversal | Level by Level | Depth First |
| Shortest Path | Yes (Unweighted Graphs) | No |
| Memory Usage | Higher | Lower (Typically) |
| Backtracking | No | Yes |
Connected Components
A graph may contain multiple disconnected parts.
Example
A ----- B
C ----- D ----- E
This graph has:
2 Connected Components
DFS or BFS can be used to count connected components.
Cycle Detection
Graphs may contain cycles.
Example
A
/ \
B--C
Cycle
A
↓
B
↓
C
↓
A
Cycle detection is essential for:
- Deadlock detection
- Dependency management
- Network analysis
- Scheduling systems
Shortest Path in an Unweighted Graph
BFS always finds the shortest path in an unweighted graph.
Example
A
|
B
|
C
|
D
Shortest Path
A → B → C → D
JavaScript Example (Shortest Path Skeleton)
function shortestPath(graph,start){
const queue=[start];
const visited=new Set();
visited.add(start);
while(queue.length){
const vertex=queue.shift();
console.log(vertex);
}
}
A complete shortest-path implementation typically stores each node’s predecessor (parent) and distance so the actual path can be reconstructed after BFS completes.
Real-World Applications
Graph Traversal is used in:
- Google Maps
- Facebook Friend Suggestions
- Web Crawlers
- Network Routing
- Search Engines
- AI Pathfinding
- File Systems
- Recommendation Engines
- Package Dependency Resolution
- Robotics
Traversal Comparison
| Algorithm | Best Use |
|---|---|
| BFS | Shortest Path |
| DFS | Maze Solving |
| DFS | Topological Sorting |
| BFS | Broadcasting |
| DFS | Cycle Detection |
Time Complexity
| Algorithm | Time | Space |
|---|---|---|
| BFS | O(V + E) | O(V) |
| DFS (Recursive) | O(V + E) | O(V) |
| DFS (Iterative) | O(V + E) | O(V) |
Advantages
Breadth-First Search
- Finds shortest path in unweighted graphs
- Simple implementation
- Complete traversal
Depth-First Search
- Requires less auxiliary memory in many sparse graphs
- Good for recursive problems
- Ideal for backtracking
- Useful for topological sorting and cycle detection
Advanced Graph Algorithms in JavaScript
Graph traversal helps us visit vertices, but real-world applications require solving more complex problems such as:
- Finding the shortest route
- Connecting all cities with minimum cost
- Scheduling dependent tasks
- Detecting cycles
- Managing connected networks
These problems are solved using advanced graph algorithms.
Overview of Graph Algorithms
Graph Algorithms
│
┌──────────────────┼───────────────────┐
│ │ │
Shortest Path Minimum Spanning Ordering
Tree
│ │
Dijkstra Prim's Algorithm
Bellman-Ford Kruskal's Algorithm
Floyd-Warshall
│
Topological Sort
│
Union Find (DSU)
1. Dijkstra’s Algorithm
What is Dijkstra’s Algorithm?
Dijkstra’s Algorithm finds the shortest path from one source vertex to every other vertex in a graph with non-negative edge weights.
It always chooses the vertex with the currently known shortest distance and expands from there.
Real-World Example
Google Maps
Home ----5---- Office
\
2
\
Mall ----2---- Office
Possible routes
Home → Office = 5 km
Home → Mall → Office = 4 km
Dijkstra chooses
Home → Mall → Office
Graph Example
A
4 / \ 2
B C
\ /
D
3
Weights
A → B = 4
A → C = 2
C → D = 3
B → D = 5
Shortest path
A → C → D
Distance = 5
How Dijkstra Works
Algorithm
- Assign every vertex an initial distance of Infinity.
- Set the source distance to 0.
- Choose the unvisited vertex with the smallest distance.
- Update distances to neighboring vertices if a shorter path is found.
- Mark the current vertex as visited.
- Repeat until all vertices have been processed.
Visualization
Initial
A = 0
B = ∞
C = ∞
D = ∞
After processing A
A = 0
B = 4
C = 2
D = ∞
After processing C
A = 0
B = 4
C = 2
D = 5
JavaScript Example
const graph = {
A: {
B:4,
C:2
},
B:{
D:5
},
C:{
D:3
},
D:{}
};
function dijkstra(graph,start){
const distances={};
const visited={};
for(const vertex in graph){
distances[vertex]=Infinity;
}
distances[start]=0;
while(true){
let closest=null;
let shortest=Infinity;
for(const vertex in distances){
if(!visited[vertex] && distances[vertex]<shortest){
shortest=distances[vertex];
closest=vertex;
}
}
if(closest===null){
break;
}
visited[closest]=true;
for(const neighbor in graph[closest]){
const distance=
distances[closest]+
graph[closest][neighbor];
if(distance<distances[neighbor]){
distances[neighbor]=distance;
}
}
}
return distances;
}
console.log(dijkstra(graph,"A"));
Output
{
A:0,
B:4,
C:2,
D:5
}
Complexity
| Implementation | Complexity |
|---|---|
| Simple Array | O(V²) |
| Priority Queue (Heap) | O((V + E) log V) |
Applications
- GPS Navigation
- Google Maps
- Network Routing
- Airline Reservation Systems
- Robotics
- Delivery Optimization
Limitations
Dijkstra’s Algorithm does not work correctly with negative edge weights.
2. Bellman-Ford Algorithm
What is Bellman-Ford?
Bellman-Ford also finds the shortest path from a source vertex to every other vertex.
Unlike Dijkstra, it supports negative edge weights and can detect negative weight cycles.
Example
A ----4---- B
\
5
\
C
|
-2
|
B
The edge from C to B has a negative weight.
Bellman-Ford handles this correctly.
How Bellman-Ford Works
- Initialize all distances.
- Relax every edge V − 1 times.
- Perform one additional pass to check for negative cycles.
- If any distance still decreases, a negative cycle exists.
JavaScript Skeleton
function bellmanFord(vertices,edges,start){
const distance={};
for(const vertex of vertices){
distance[vertex]=Infinity;
}
distance[start]=0;
for(let i=0;i<vertices.length-1;i++){
for(const edge of edges){
const {
source,
destination,
weight
}=edge;
if(
distance[source]!==Infinity &&
distance[source]+weight<distance[destination]
){
distance[destination]=
distance[source]+weight;
}
}
}
return distance;
}
Complexity
| Operation | Complexity |
|---|---|
| Time | O(V × E) |
| Space | O(V) |
Applications
- Currency exchange systems
- Network routing protocols
- Financial analysis
- Graphs with negative edge weights
Dijkstra vs Bellman-Ford
| Feature | Dijkstra | Bellman-Ford |
|---|---|---|
| Negative Weights | No | Yes |
| Detect Negative Cycles | No | Yes |
| Faster | Yes | No |
| Complexity | O((V+E) log V) | O(V × E) |
3. Floyd-Warshall Algorithm
What is Floyd-Warshall?
Floyd-Warshall finds the shortest paths between every pair of vertices in a weighted graph.
Unlike Dijkstra, which starts from one source, Floyd-Warshall computes the shortest distance between all pairs.
Visualization
A ----2---- B
\ /
4 1
\ /
C
A → B
A → C
B → C
C → A
C → B
Complexity
| Operation | Complexity |
|---|---|
| Time | O(V³) |
| Space | O(V²) |
Applications
- Airline route planning
- Road networks
- Network analysis
- Distance matrices
4. Minimum Spanning Tree (MST)
What is an MST?
A Minimum Spanning Tree connects all vertices in a graph with:
- No cycles
- Minimum total edge weight
Example
A
2 | 3
B
1 | 4
C
The MST selects the minimum-cost edges while keeping all vertices connected.
Characteristics
- Connects every vertex.
- Contains exactly V − 1 edges.
- Has no cycles.
- Produces the minimum possible total cost.
Prim’s Algorithm
Prim’s Algorithm starts from any vertex and repeatedly selects the minimum-weight edge that connects a visited vertex to an unvisited vertex.
Visualization
Start
↓
A
↓
Smallest Edge
↓
B
↓
Smallest Edge
↓
C
Complexity
| Implementation | Complexity |
|---|---|
| Binary Heap | O(E log V) |
Applications
- Cable network design
- Road construction
- Water pipeline planning
- Electrical grid design
Kruskal’s Algorithm
Kruskal’s Algorithm sorts all edges by weight and repeatedly selects the smallest edge that does not create a cycle.
Steps
- Sort all edges by weight.
- Select the smallest edge.
- Skip edges that create cycles.
- Continue until V − 1 edges are selected.
Visualization
Edges
1
↓
2
↓
3
↓
4
↓
5
Select the smallest edges while avoiding cycles.
Complexity
| Implementation | Complexity |
|---|---|
| Sorting + Union-Find | O(E log E) |
Prim vs Kruskal
| Feature | Prim | Kruskal |
|---|---|---|
| Starts From Vertex | Yes | No |
| Sorts Edges | No | Yes |
| Uses Priority Queue | Yes | Optional |
| Uses Union-Find | No | Yes |
| Best for Dense Graphs | Yes | No |
| Best for Sparse Graphs | No | Yes |
5. Topological Sorting
What is Topological Sorting?
Topological Sorting arranges the vertices of a Directed Acyclic Graph (DAG) so that every directed edge goes from an earlier vertex to a later vertex.
Example
HTML
↓
CSS
↓
JavaScript
↓
React
The dependencies must be respected.
Applications
- Task scheduling
- Build systems
- Course prerequisite planning
- Package dependency resolution
6. Union-Find (Disjoint Set Union)
Union-Find efficiently manages collections of disjoint sets.
It supports two operations:
- Find – Determine which set an element belongs to.
- Union – Merge two sets.
Applications
- Kruskal’s Algorithm
- Cycle detection
- Network connectivity
- Image processing
- Social network grouping
Comparison of Graph Algorithms
| Algorithm | Purpose | Time Complexity |
|---|---|---|
| BFS | Shortest path (unweighted) | O(V + E) |
| DFS | Traversal | O(V + E) |
| Dijkstra | Shortest path (non-negative weights) | O((V + E) log V) |
| Bellman-Ford | Shortest path (negative weights) | O(V × E) |
| Floyd-Warshall | All-pairs shortest paths | O(V³) |
| Prim | Minimum Spanning Tree | O(E log V) |
| Kruskal | Minimum Spanning Tree | O(E log E) |
| Topological Sort | Dependency ordering | O(V + E) |
Real-World Applications
Advanced graph algorithms are used in:
- Google Maps
- GPS navigation
- Airline route optimization
- Computer network routing
- Logistics and supply chain management
- Compiler dependency analysis
- Recommendation engines
- Social network analysis
- Power grid design
- Telecommunications
Searching and Sorting Algorithms in JavaScript
Searching and Sorting are two of the most commonly used algorithmic techniques.
Searching helps locate a specific element from a collection of data, while sorting arranges data into a specific order, such as ascending or descending.
Efficient searching often depends on efficient sorting.
Overview

Searching Algorithms
What is Searching?
Searching is the process of finding the location of a particular element within a collection of data.
For example,
Suppose an array contains student roll numbers.
12
25
37
48
59
64
71
Find
48
Searching algorithms determine whether the element exists and, if so, where it is located.
Types of Searching
Searching
│
┌─────────┴─────────┐
│ │
Linear Search Binary Search
1. Linear Search
What is Linear Search?
Linear Search checks each element one by one until the target element is found or the end of the collection is reached.
It works on both sorted and unsorted data.
How Linear Search Works
Array
10
20
30
40
50
Search
40
Process
10
↓
20
↓
30
↓
40
Found
Algorithm
- Start from the first element.
- Compare the current element with the target.
- If equal, return its index.
- Otherwise, move to the next element.
- Repeat until the element is found or the array ends.
JavaScript Implementation
function linearSearch(array,target){
for(let i=0;i<array.length;i++){
if(array[i]===target){
return i;
}
}
return -1;
}
const numbers=[10,20,30,40,50];
console.log(
linearSearch(numbers,40)
);
Output
3
Complexity
| Operation | Complexity |
|---|---|
| Best Case | O(1) |
| Average Case | O(n) |
| Worst Case | O(n) |
Advantages
- Very simple implementation
- Works on unsorted arrays
- No preprocessing required
Disadvantages
- Slow for large datasets
- Requires sequential comparison
Real-World Applications
- Small datasets
- Unsorted collections
- Simple lookup operations
- Searching in linked lists
2. Binary Search
What is Binary Search?
Binary Search is a highly efficient searching algorithm that works only on sorted data.
Instead of checking every element, it repeatedly divides the search space into two halves.
Why is Binary Search Faster?
Array
10
20
30
40
50
60
70
Search
50
Middle
40
Since
50 > 40
Ignore the left half.
Continue searching only in the right half.
Binary Search Visualization
10 20 30 40 50 60 70
↑
Middle
↓
Search Right
↓
50 60 70
↓
Middle
↓
50
Found
Algorithm
- Set
lowto the first index. - Set
highto the last index. - Find the middle element.
- If it matches the target, return the index.
- If the target is smaller, search the left half.
- Otherwise, search the right half.
- Repeat until found or the search range becomes empty.
JavaScript Implementation
function binarySearch(array,target){
let low=0;
let high=array.length-1;
while(low<=high){
const mid=Math.floor(
(low+high)/2
);
if(array[mid]===target){
return mid;
}
if(target<array[mid]){
high=mid-1;
}
else{
low=mid+1;
}
}
return -1;
}
const numbers=[10,20,30,40,50,60,70];
console.log(
binarySearch(numbers,50)
);
Output
4
Complexity
| Operation | Complexity |
|---|---|
| Best Case | O(1) |
| Average Case | O(log n) |
| Worst Case | O(log n) |
Recursive Binary Search
function recursiveBinarySearch(array,target,low,high){
if(low>high){
return -1;
}
const mid=Math.floor(
(low+high)/2
);
if(array[mid]===target){
return mid;
}
if(target<array[mid]){
return recursiveBinarySearch(
array,
target,
low,
mid-1
);
}
return recursiveBinarySearch(
array,
target,
mid+1,
high
);
}
Example
const numbers=[10,20,30,40,50,60,70];
console.log(
recursiveBinarySearch(
numbers,
60,
0,
numbers.length-1
)
);
Output
5
Linear Search vs Binary Search
| Feature | Linear Search | Binary Search |
|---|---|---|
| Data Requirement | Sorted or Unsorted | Sorted Only |
| Best Case | O(1) | O(1) |
| Average Case | O(n) | O(log n) |
| Worst Case | O(n) | O(log n) |
| Implementation | Very Simple | Moderate |
| Suitable for Large Data | No | Yes |
Choosing the Right Search Algorithm
| Scenario | Recommended Algorithm |
|---|---|
| Small dataset | Linear Search |
| Unsorted data | Linear Search |
| Large sorted dataset | Binary Search |
| Frequently searched data | Binary Search |
Advantages of Binary Search
- Extremely fast
- Reduces search space by half each iteration
- Efficient for large sorted datasets
- Widely used in databases and search engines
Disadvantages
- Requires sorted data
- More complex than Linear Search
- Sorting overhead if data changes frequently
Time Complexity Comparison
| Algorithm | Best | Average | Worst |
|---|---|---|---|
| Linear Search | O(1) | O(n) | O(n) |
| Binary Search | O(1) | O(log n) | O(log n) |
Real-World Applications
Linear Search
- Searching in small lists
- Configuration files
- Simple forms
- Linked Lists
Binary Search
- Database indexing
- Search engines
- Phone directories
- Dictionary lookup
- Product search
- Library systems
Best Practices
- Use Binary Search only when the data is sorted.
- Prefer Linear Search for very small or unsorted datasets.
- Validate array boundaries before implementing Binary Search.
- Avoid recursive Binary Search for extremely deep recursion where stack limits may be a concern.
Sorting Algorithms in JavaScript
What is Sorting?
Sorting is the process of arranging data in a specific order.
The order can be:
- Ascending
- Descending
- Alphabetical
- Chronological
- Priority-based
In simple words,
Sorting is the process of organizing data into a meaningful order to make searching, processing, and analysis more efficient.
Definition
Sorting is an algorithmic process that rearranges elements of a collection according to a predefined order.
Why Do We Need Sorting?
Suppose an online shopping website stores product prices.
Unsorted
650
120
980
300
450
Finding the cheapest product is difficult.
Sorted
120
300
450
650
980
Searching, filtering, and analysis become much easier.
Real-World Applications
Sorting is used in:
- Search engines
- Online shopping websites
- Banking systems
- Student result processing
- Library management
- Database indexing
- File managers
- Social media feeds
- Leaderboards
- Payroll systems
Types of Sorting
Classification of Sorting Algorithms
Characteristics of a Good Sorting Algorithm
A good sorting algorithm should:
- Produce correct results
- Be efficient
- Use minimal memory
- Handle duplicate values correctly
- Scale well for large datasets
Important Terminology
Before learning sorting algorithms, let’s understand a few important terms.
Stable Sorting
A sorting algorithm is stable if equal elements retain their original order after sorting.
Example
Before
Student A
Marks = 90
Student B
Marks = 90
After Stable Sorting
Student A
Student B
The original order is preserved.
Unstable Sorting
An unstable algorithm may change the order of equal elements.
Example
Student B
Student A
In-Place Sorting
An algorithm that sorts data without requiring significant additional memory.
Examples
- Bubble Sort
- Selection Sort
- Insertion Sort
- Heap Sort
Out-of-Place Sorting
Requires additional memory.
Examples
- Merge Sort
- Counting Sort
- Radix Sort
Bubble Sort
What is Bubble Sort?
Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
Larger elements gradually move (“bubble”) toward the end of the array after each pass.
Visualization
Initial Array
64 34 25 12 22
Pass 1
34 25 12 22 64
Pass 2
25 12 22 34 64
Pass 3
12 22 25 34 64
Sorted
How Bubble Sort Works
Algorithm
- Compare adjacent elements.
- Swap if needed.
- Continue until the end.
- Repeat until no swaps occur.
Step-by-Step Example
Original Array
5 3 8 4
Compare
5 3
Swap
3 5 8 4
Compare
5 8
No Swap
3 5 8 4
Compare
8 4
Swap
3 5 4 8
Second Pass
3 4 5 8
Sorted.
Bubble Sort JavaScript Implementation
function bubbleSort(array){
const length = array.length;
for(let i = 0; i < length - 1; i++){
let swapped = false;
for(let j = 0; j < length - i - 1; j++){
if(array[j] > array[j + 1]){
[array[j], array[j + 1]] = [array[j + 1], array[j]];
swapped = true;
}
}
if(!swapped){
break;
}
}
return array;
}
const numbers = [64,34,25,12,22];
console.log(bubbleSort(numbers));
Output
[12,22,25,34,64]
Bubble Sort Visualization
Pass 1
64 34 25 12 22
↓
34 25 12 22 64
↓
Pass 2
34 25 12 22 64
↓
25 12 22 34 64
↓
Pass 3
25 12 22 34 64
↓
12 22 25 34 64
Bubble Sort Complexity
| Case | Complexity |
|---|---|
| Best | O(n) |
| Average | O(n²) |
| Worst | O(n²) |
| Space | O(1) |
Advantages
- Easy to understand
- Easy to implement
- Stable sorting algorithm
- In-place sorting
- Suitable for educational purposes
Disadvantages
- Very slow for large datasets
- High number of comparisons
- High number of swaps
- Rarely used in production systems
Bubble Sort Applications
Although inefficient for large datasets, Bubble Sort is useful for:
- Learning sorting concepts
- Small datasets
- Detecting whether data is already sorted
- Educational demonstrations
Selection Sort
What is Selection Sort?
Selection Sort repeatedly selects the smallest element from the unsorted portion of the array and places it at its correct position.
Unlike Bubble Sort, Selection Sort performs fewer swaps.
Visualization
Original Array
64 25 12 22 11
Find Minimum
11
Swap
11 25 12 22 64
Next Pass
Find Minimum
12
Swap
11 12 25 22 64
Continue until the array is sorted.
Algorithm
- Find the smallest element.
- Swap it with the first unsorted position.
- Move the sorted boundary forward.
- Repeat until all elements are sorted.
JavaScript Implementation
function selectionSort(array){
const length = array.length;
for(let i = 0; i < length - 1; i++){
let minIndex = i;
for(let j = i + 1; j < length; j++){
if(array[j] < array[minIndex]){
minIndex = j;
}
}
if(minIndex !== i){
[array[i], array[minIndex]] = [array[minIndex], array[i]];
}
}
return array;
}
const numbers = [64,25,12,22,11];
console.log(selectionSort(numbers));
Output
[11,12,22,25,64]
Selection Sort Complexity
| Case | Complexity |
|---|---|
| Best | O(n²) |
| Average | O(n²) |
| Worst | O(n²) |
| Space | O(1) |
Bubble Sort vs Selection Sort
| Feature | Bubble Sort | Selection Sort |
|---|---|---|
| Stable | Yes | No |
| In-Place | Yes | Yes |
| Best Case | O(n) | O(n²) |
| Average Case | O(n²) | O(n²) |
| Worst Case | O(n²) | O(n²) |
| Swaps | Many | Few |
Insertion Sort, Merge Sort, Quick Sort, Heap Sort, Counting Sort, and Radix Sort
After learning the basic sorting algorithms, it is time to explore the algorithms that power modern applications, databases, browsers, operating systems, and programming language libraries.
Some algorithms are ideal for small datasets, while others are optimized for handling millions of records efficiently.
Overview
Efficient Sorting
│
┌───────────────┼────────────────┐
│ │ │
Insertion Merge Sort Quick Sort
│
Heap Sort
│
Counting & Radix Sort
Insertion Sort
What is Insertion Sort?
Insertion Sort builds the sorted portion of the array one element at a time.
It is similar to arranging playing cards in your hand.
Real-World Analogy
Suppose you receive playing cards one by one.
8
↓
3
↓
6
↓
2
Each new card is inserted into its correct position.
Visualization
Original Array
8 4 5 2
Pass 1
4 8 5 2
Pass 2
4 5 8 2
Pass 3
2 4 5 8
Sorted.
Algorithm
- Consider the first element as sorted.
- Pick the next element.
- Compare it with previous elements.
- Shift larger elements to the right.
- Insert the current element into its correct position.
- Repeat for all remaining elements.
JavaScript Implementation
function insertionSort(array){
for(let i=1;i<array.length;i++){
const current=array[i];
let j=i-1;
while(j>=0 && array[j]>current){
array[j+1]=array[j];
j--;
}
array[j+1]=current;
}
return array;
}
const numbers=[8,4,5,2];
console.log(insertionSort(numbers));
Output
[2,4,5,8]
Complexity
| Case | Complexity |
|---|---|
| Best | O(n) |
| Average | O(n²) |
| Worst | O(n²) |
| Space | O(1) |
Advantages
- Stable
- In-place
- Very efficient for nearly sorted data
- Excellent for small datasets
Disadvantages
- Slow for large datasets
- Performance decreases with many inversions
Merge Sort
What is Merge Sort?
Merge Sort uses the Divide and Conquer strategy.
Instead of sorting the entire array at once, it repeatedly divides the array into smaller parts until each part contains only one element. The smaller arrays are then merged in sorted order.
Visualization
Original
38 27 43 3
Divide
38 27
43 3
Further Divide
38
27
43
3
Merge
27 38
3 43
Final Merge
3 27 38 43
Divide and Conquer
Array
↓
Divide
↓
Smaller Arrays
↓
Merge
↓
Sorted Array
JavaScript Implementation
function merge(left,right){
const result=[];
let i=0;
let j=0;
while(i<left.length && j<right.length){
if(left[i]<right[j]){
result.push(left[i]);
i++;
}
else{
result.push(right[j]);
j++;
}
}
return result
.concat(left.slice(i))
.concat(right.slice(j));
}
function mergeSort(array){
if(array.length<=1){
return array;
}
const middle=Math.floor(array.length/2);
const left=mergeSort(array.slice(0,middle));
const right=mergeSort(array.slice(middle));
return merge(left,right);
}
console.log(
mergeSort([38,27,43,3])
);
Output
[3,27,38,43]
Complexity
| Case | Complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
| Space | O(n) |
Advantages
- Stable
- Predictable performance
- Excellent for large datasets
- Suitable for linked lists
- Parallelizable
Disadvantages
- Requires additional memory
- Slower than Quick Sort in many practical scenarios
Quick Sort
What is Quick Sort?
Quick Sort is another Divide and Conquer algorithm.
Instead of dividing into equal halves, it selects a pivot element and partitions the array so that:
- Smaller elements move to the left.
- Larger elements move to the right.
The same process is repeated recursively.
Visualization
Original
40 20 70 10 60
Pivot
40
Partition
20 10
40
70 60
Recursive Sorting
10 20
40
60 70
Sorted.
JavaScript Implementation
function quickSort(array){
if(array.length<=1){
return array;
}
const pivot=array[array.length-1];
const left=[];
const right=[];
for(let i=0;i<array.length-1;i++){
if(array[i]<pivot){
left.push(array[i]);
}
else{
right.push(array[i]);
}
}
return [
...quickSort(left),
pivot,
...quickSort(right)
];
}
console.log(
quickSort([40,20,70,10,60])
);
Output
[10,20,40,60,70]
Complexity
| Case | Complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n²) |
| Space | O(log n) Average |
Advantages
- Very fast in practice
- Cache-friendly
- Widely used
- In-place implementations are available
Disadvantages
- Worst case O(n²)
- Pivot selection affects performance
- Not stable in standard implementations
Heap Sort
What is Heap Sort?
Heap Sort uses a Binary Heap to repeatedly remove the largest (or smallest) element and place it in its correct position.
Visualization
Array
↓
Build Max Heap
↓
Remove Root
↓
Heapify
↓
Sorted Array
Complexity
| Case | Complexity |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
| Space | O(1) |
Advantages
- Guaranteed O(n log n)
- In-place
- No worst-case degradation
Disadvantages
- Not stable
- Slower than Quick Sort in many real-world cases
Counting Sort
What is Counting Sort?
Counting Sort is a non-comparison sorting algorithm.
Instead of comparing elements, it counts how many times each value occurs.
Example
Original
4 2 1 4 3 2
Count Array
1
2
1
2
Output
1 2 2 3 4 4
Complexity
| Case | Complexity |
|---|---|
| Time | O(n + k) |
| Space | O(n + k) |
Where k is the range of input values.
Advantages
- Extremely fast for small integer ranges
- Stable
- Linear time under suitable conditions
Disadvantages
- Works only with integer keys
- Inefficient for a very large value range
Radix Sort
What is Radix Sort?
Radix Sort sorts numbers digit by digit, starting from either the least significant digit (LSD) or the most significant digit (MSD).
It typically uses Counting Sort as a stable subroutine.
Visualization
Original
329
457
657
839
436
Sort by Units
↓
Sort by Tens
↓
Sort by Hundreds
↓
Sorted Array
Complexity
| Case | Complexity |
|---|---|
| Time | O(d × (n + k)) |
| Space | O(n + k) |
Where:
- d = Number of digits
- k = Digit range (usually 10)
Applications
- Large numeric datasets
- Telephone numbers
- Employee IDs
- ZIP codes
Stability Comparison
| Algorithm | Stable |
|---|---|
| Bubble Sort | Yes |
| Selection Sort | No |
| Insertion Sort | Yes |
| Merge Sort | Yes |
| Quick Sort | No |
| Heap Sort | No |
| Counting Sort | Yes |
| Radix Sort | Yes |
In-Place Comparison
| Algorithm | In-Place |
|---|---|
| Bubble Sort | Yes |
| Selection Sort | Yes |
| Insertion Sort | Yes |
| Merge Sort | No |
| Quick Sort | Yes (Typical implementations) |
| Heap Sort | Yes |
| Counting Sort | No |
| Radix Sort | No |
Complete Complexity Comparison
| Algorithm | Best | Average | Worst | Space |
|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) Average |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) |
| Counting Sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) |
| Radix Sort | O(d × (n + k)) | O(d × (n + k)) | O(d × (n + k)) | O(n + k) |
Choosing the Right Sorting Algorithm
| Scenario | Recommended Algorithm |
|---|---|
| Small arrays | Insertion Sort |
| Nearly sorted data | Insertion Sort |
| Large general-purpose datasets | Merge Sort |
| Fast average performance | Quick Sort |
| Guaranteed worst-case performance | Heap Sort |
| Small integer ranges | Counting Sort |
| Large numeric identifiers | Radix Sort |
Dynamic Programming (DP) in JavaScript
What is Dynamic Programming?
Dynamic Programming (DP) is an algorithmic technique used to solve complex problems by breaking them into smaller overlapping subproblems and storing the results so they are not computed repeatedly.
Instead of solving the same subproblem multiple times, DP solves it once and reuses the stored answer.
In simple words,
Dynamic Programming is an optimization technique that saves previously computed results to avoid redundant calculations.
Why Do We Need Dynamic Programming?
Consider calculating the Fibonacci sequence.
Recursive Approach
F(5)
/ \
F(4) F(3)
/ \ / \
F(3) F(2) F(2) F(1)
/
F(2)
Notice that F(3) and F(2) are calculated multiple times.
This leads to unnecessary work.
Dynamic Programming stores these values.
F(0)=0
F(1)=1
↓
Store
↓
Reuse
Characteristics of DP Problems
A problem can be solved using Dynamic Programming if it has:
- Overlapping Subproblems
- Optimal Substructure
Overlapping Subproblems
The same smaller problem appears multiple times.
Example
F(5)
↓
F(4)
↓
F(3)
↓
F(2)
The values are repeatedly computed.
Optimal Substructure
An optimal solution can be built from optimal solutions of smaller subproblems.
Examples
- Shortest Path
- Knapsack Problem
- Matrix Chain Multiplication
- Longest Common Subsequence
Dynamic Programming Techniques
Dynamic Programming
│
┌────────────┴────────────┐
│ │
Memoization Tabulation
(Top-Down) (Bottom-Up)
Memoization (Top-Down)
Memoization uses recursion along with storage.
If a result already exists, it is returned immediately.
Visualization
Solve Problem
↓
Check Memory
↓
Exists?
↓
Yes → Return
↓
No → Compute
↓
Store
↓
Return
Fibonacci Using Memoization
function fibonacci(n,memo={}){
if(n<=1){
return n;
}
if(memo[n]){
return memo[n];
}
memo[n]=
fibonacci(n-1,memo)
+
fibonacci(n-2,memo);
return memo[n];
}
console.log(
fibonacci(10)
);
Output
55
Tabulation (Bottom-Up)
Instead of recursion,
build the answer iteratively from smaller values.
Visualization
0
↓
1
↓
1
↓
2
↓
3
↓
5
↓
8
Fibonacci Using Tabulation
function fibonacci(n){
const dp=[0,1];
for(let i=2;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
console.log(
fibonacci(10)
);
Output
55
Memoization vs Tabulation
| Feature | Memoization | Tabulation |
|---|---|---|
| Approach | Top-Down | Bottom-Up |
| Uses Recursion | Yes | No |
| Stack Memory | Yes | No |
| Usually Easier | Yes | Moderate |
| Often Faster | Sometimes | Often |
Classic DP Problem 1
Climbing Stairs
A person can climb:
- 1 step
- 2 steps
How many different ways exist to reach step n?
Example
Step 4
↓
1+1+1+1
1+1+2
1+2+1
2+1+1
2+2
Answer
5 Ways
JavaScript
function climbStairs(n){
if(n<=2){
return n;
}
let first=1;
let second=2;
for(let i=3;i<=n;i++){
const current=
first+second;
first=second;
second=current;
}
return second;
}
console.log(
climbStairs(5)
);
Output
8
Classic DP Problem 2
Coin Change
Coins
1
2
5
Target
11
Minimum Coins
5
5
1
Answer
3 Coins
Classic DP Problem 3
Longest Common Subsequence (LCS)
Strings
ABCDEF
ACE
Longest Common Subsequence
ACE
Length
3
Applications
- DNA sequencing
- Version control
- Text comparison
- Spell checking
Classic DP Problem 4
0/1 Knapsack
Items
Weight
Value
Goal
Choose items to maximize value without exceeding the weight limit.
Applications
- Cargo loading
- Budget allocation
- Investment optimization
Classic DP Problem 5
Matrix Chain Multiplication
Goal
Determine the most efficient order for multiplying matrices.
Applications
- Scientific computing
- Graphics
- Machine Learning
Time Complexity Comparison
| Approach | Fibonacci |
|---|---|
| Recursive | O(2ⁿ) |
| Memoization | O(n) |
| Tabulation | O(n) |
Real-World Applications
Dynamic Programming is used in:
- Google Maps
- GPS navigation
- AI game engines
- Robotics
- Bioinformatics
- Compiler optimization
- Image processing
- Stock market analysis
- Resource allocation
- Network routing
Advantages
- Eliminates repeated calculations
- Improves performance significantly
- Solves optimization problems efficiently
- Often converts exponential solutions into polynomial-time solutions
Disadvantages
- Higher memory usage
- Can be difficult to identify DP problems
- State definition may become complex
Practical Mini Projects, Coding Interview Preparation, and DSA Cheat Sheet
Learning Data Structures and Algorithms is only the first step. The real understanding comes from applying these concepts to solve real-world problems.
In this final chapter, we will:
- Build practical projects using different data structures.
- Solve common coding interview problems.
- Review time and space complexities.
- Summarize important concepts for quick revision.
Practical Mini Projects
The following projects combine multiple data structures and algorithms learned throughout this guide.
Practical Projects
│
┌───────────────┼────────────────┐
│ │ │
Browser History Student Records Route Finder
│ │ │
Stack BST Graph
│ │ │
Contact Manager Music Playlist Printer Queue
Project 1 – Student Record Management System
Concepts Used
- Binary Search Tree
- Searching
- Inorder Traversal
Features
- Add Student
- Search Student
- Delete Student
- Display Students in Sorted Order
Data Structure
Student BST
50
/ \
30 70
/ \ / \
20 40 60 80
Learning Outcomes
- BST insertion
- Searching
- Deletion
- Traversal
Project 2 – Browser History Manager
Concepts Used
- Stack
Features
- Visit New Page
- Back
- Forward
- Display History
Visualization
Google
↓
YouTube
↓
GitHub
↓
Stack Top
Project 3 – Contact Management System
Concepts Used
- Hash Table
Features
- Add Contact
- Search Contact
- Update Contact
- Delete Contact
Visualization
Akshay
↓
8275278587
----------------
Rahul
↓
6358587858
Project 4 – Music Playlist
Concepts Used
- Doubly Linked List
Features
- Next Song
- Previous Song
- Add Song
- Delete Song
Visualization
Song A
⇄
Song B
⇄
Song C
Project 5 – Printer Queue
Concepts Used
- Queue
Features
- Add Print Job
- Print Document
- Display Queue
Visualization
Job 1
↓
Job 2
↓
Job 3
Project 6 – Route Finder
Concepts Used
- Graph
- BFS
- Dijkstra
Features
- Find Shortest Route
- Display Connected Cities
- Calculate Distance
Visualization
City A
↓
City B
↓
City C
Project 7 – Library Management System
Concepts Used
- Arrays
- Searching
- Sorting
- Hash Tables
Features
- Add Books
- Search Books
- Sort Books
- Borrow Books
Project 8 – Parking Management System
Concepts Used
- Queue
- Stack
Features
- Vehicle Entry
- Vehicle Exit
- Parking History
Project 9 – File System Explorer
Concepts Used
- Tree
Visualization
Root
├── Documents
├── Downloads
└── Pictures
Project 10 – Undo/Redo Text Editor
Concepts Used
- Stack
Visualization
Edit
↓
Edit
↓
Undo
↓
Redo
Coding Interview Preparation
Technical interviews typically evaluate your ability to:
- Choose the appropriate data structure.
- Analyze time and space complexity.
- Write clean code.
- Optimize brute-force solutions.
Common Interview Pattern
Problem
↓
Brute Force
↓
Optimization
↓
Best Solution
↓
Complexity Analysis
Frequently Asked Coding Problems
Arrays
- Two Sum
- Maximum Subarray
- Merge Intervals
- Product of Array Except Self
- Rotate Array
- Move Zeroes
- Best Time to Buy and Sell Stock
Strings
- Reverse String
- Valid Anagram
- Longest Common Prefix
- Longest Palindromic Substring
- Group Anagrams
- String Compression
Linked Lists
- Reverse Linked List
- Detect Cycle
- Merge Two Sorted Lists
- Remove Nth Node from End
- Middle of Linked List
Stacks
- Valid Parentheses
- Min Stack
- Next Greater Element
- Daily Temperatures
- Evaluate Postfix Expression
Queues
- Implement Queue Using Stacks
- Circular Queue
- Sliding Window Maximum
Trees
- Maximum Depth
- Lowest Common Ancestor
- Inorder Traversal
- Validate BST
- Balanced Binary Tree
Graphs
- BFS Traversal
- DFS Traversal
- Number of Islands
- Clone Graph
- Course Schedule
- Shortest Path
Dynamic Programming
- Fibonacci
- Climbing Stairs
- Coin Change
- House Robber
- Longest Common Subsequence
- Longest Increasing Subsequence
- 0/1 Knapsack
DSA Cheat Sheet
Time Complexity of Data Structures
| Data Structure | Search | Insert | Delete | Access |
|---|---|---|---|---|
| Array | O(n) | O(n) | O(n) | O(1) |
| Linked List | O(n) | O(1) | O(1) | O(n) |
| Stack | O(n) | O(1) | O(1) | O(n) |
| Queue | O(n) | O(1) | O(1) | O(n) |
| Hash Table | O(1)* | O(1)* | O(1)* | O(1)* |
| Binary Search Tree | O(log n)* | O(log n)* | O(log n)* | O(log n)* |
| AVL Tree | O(log n) | O(log n) | O(log n) | O(log n) |
| Heap | O(n) | O(log n) | O(log n) | O(1) |
*Average case.
Sorting Complexity Cheat Sheet
| Algorithm | Best | Average | Worst | Stable |
|---|---|---|---|---|
| Bubble | O(n) | O(n²) | O(n²) | Yes |
| Selection | O(n²) | O(n²) | O(n²) | No |
| Insertion | O(n) | O(n²) | O(n²) | Yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | Yes |
| Quick | O(n log n) | O(n log n) | O(n²) | No |
| Heap | O(n log n) | O(n log n) | O(n log n) | No |
| Counting | O(n+k) | O(n+k) | O(n+k) | Yes |
| Radix | O(d(n+k)) | O(d(n+k)) | O(d(n+k)) | Yes |
Searching Complexity Cheat Sheet
| Algorithm | Best | Average | Worst |
|---|---|---|---|
| Linear Search | O(1) | O(n) | O(n) |
| Binary Search | O(1) | O(log n) | O(log n) |
Graph Algorithm Cheat Sheet
| Algorithm | Purpose | Complexity |
|---|---|---|
| BFS | Traversal | O(V+E) |
| DFS | Traversal | O(V+E) |
| Dijkstra | Shortest Path | O((V+E) log V) |
| Bellman-Ford | Negative Weights | O(VE) |
| Floyd-Warshall | All-Pairs Shortest Path | O(V³) |
| Prim | Minimum Spanning Tree | O(E log V) |
| Kruskal | Minimum Spanning Tree | O(E log E) |
Tree Traversal Cheat Sheet
| Traversal | Order |
|---|---|
| Preorder | Root → Left → Right |
| Inorder | Left → Root → Right |
| Postorder | Left → Right → Root |
| Level Order | Level by Level |
Dynamic Programming Cheat Sheet
| Problem | Technique |
|---|---|
| Fibonacci | Memoization / Tabulation |
| Climbing Stairs | DP |
| Coin Change | DP |
| Knapsack | DP |
| Longest Common Subsequence | DP |
| Matrix Chain Multiplication | DP |
Common Interview Mistakes
Avoid these mistakes during coding interviews:
- Ignoring edge cases
- Not analyzing time complexity
- Forgetting null or empty inputs
- Using unnecessary nested loops
- Choosing the wrong data structure
- Writing code without testing sample inputs
- Optimizing too early before producing a correct solution
DSA Learning Roadmap

Final Revision Checklist
Before attending a coding interview, make sure you can confidently:
- Explain Big-O notation.
- Implement all basic data structures from scratch.
- Solve array and string problems efficiently.
- Reverse and manipulate linked lists.
- Implement stacks and queues.
- Use hash tables effectively.
- Traverse binary trees using all four methods.
- Implement Binary Search Trees.
- Understand heaps and priority queues.
- Represent and traverse graphs.
- Apply BFS and DFS correctly.
- Choose appropriate searching and sorting algorithms.
- Solve introductory Dynamic Programming problems.
- Analyze time and space complexity for every solution.
Final Thoughts
Data Structures and Algorithms form the foundation of efficient software development. While frameworks, libraries, and programming languages evolve rapidly, the principles of DSA remain relevant across domains such as web development, mobile applications, artificial intelligence, cloud computing, cybersecurity, game development, and data engineering.
Rather than memorizing algorithms, focus on understanding:
- Why a particular data structure is appropriate for a problem.
- How algorithmic choices affect performance.
- The trade-offs between time complexity, space complexity, readability, and maintainability.
- Practical applications through projects and coding exercises.
Consistent practice is the key to mastery. Solving problems regularly, reviewing complexity analysis, and building projects using these concepts will strengthen your problem-solving skills and prepare you for technical interviews as well as real-world software development.
Conclusion
You have now completed a comprehensive journey through JavaScript Data Structures and Algorithms, covering:
- Big-O Analysis
- Arrays and Strings
- Linked Lists
- Stacks and Queues
- Hash Tables
- Trees, Binary Search Trees, and AVL Trees
- Heaps
- Graphs and Graph Algorithms
- Searching and Sorting Algorithms
- Dynamic Programming
- Practical Projects
- Coding Interview Preparation
- DSA Cheat Sheets
With regular implementation and practice, this knowledge provides a solid foundation for software engineering interviews, competitive programming, and building efficient, scalable applications.










