├── Array
├── Polyfill.md
└── README.md
├── Basics
└── README.md
├── Binary Tree
├── index.js
└── question.txt
├── Linked List
└── README.md
├── Objects
└── README.md
├── Practise.js
├── Queue
└── README.md
├── README.md
├── Recursion
└── README.md
├── Searching Algorthims
└── README.md
├── Set & Map
└── README.md
├── Sorting
└── README.md
├── Stack
└── README.md
├── String
└── README.md
└── Time Complexity
└── README.md
/Array/Polyfill.md:
--------------------------------------------------------------------------------
1 | # Map, Filter & Reduce & their Polyfills
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ### Map in JavaScript
10 |
11 | ```javascript
12 | const employees = [
13 | { name: 'John', age: 32 },
14 | { name: 'Sarah', age: 28 },
15 | { name: 'Michael', age: 40 },
16 | ];
17 |
18 | const employeesName = employees.map(employee => employee.name);
19 | console.log(employeesName); // ["John", "Sarah", "Michael"]
20 | ```
21 |
22 | ### Polyfill of map()
23 |
24 | ```javascript
25 | if (!Array.prototype.myMap) {
26 | Array.prototype.myMap = function (callback) {
27 | const result = [];
28 | for (let i = 0; i < this.length; i++) {
29 | result.push(callback(this[i], i, this));
30 | }
31 | return result;
32 | };
33 | }
34 |
35 | const myEmployeesName = employees.myMap(employee => employee.name);
36 |
37 | console.log(myEmployeesName); // ["John", "Sarah", "Michael"]
38 | ```
39 |
40 | ### Filter In JavaScript
41 |
42 | ```javascript
43 | const products = [
44 | { name: 'iPhone', price: 999, inStock: true },
45 | { name: 'Samsung Galaxy', price: 899, inStock: false },
46 | { name: 'Google Pixel', price: 799, inStock: true },
47 | ];
48 |
49 | const availableProducts = products.filter(product => product.inStock);
50 | // [
51 | // { name: 'iPhone', price: 999, inStock: true },
52 | // { name: 'Google Pixel', price: 799, inStock: true },
53 | // ]
54 | ```
55 |
56 | ### Polyfill of filter()
57 |
58 | ```javascript
59 | if (!Array.prototype.myFilter) {
60 | Array.prototype.myFilter = (callback) => {
61 | const result = [];
62 | for (let i = 0; i < this.length; i++) {
63 | if (callback(this[i], i, this)) {
64 | result.push(this[i]);
65 | }
66 | }
67 | return result;
68 | };
69 | }
70 |
71 | const myAvailableProducts = products.myFilter(product => product.inStock);
72 |
73 | console.log(availableProducts);
74 | // [
75 | // { name: 'iPhone', price: 999, inStock: true },
76 | // { name: 'Google Pixel', price: 799, inStock: true },
77 | // ]
78 | ```
79 |
80 | ### Reduce in JavaScript
81 |
82 | ```javascript
83 | const orders = [
84 | { product: 'iPhone', price: 999, quantity: 2 },
85 | { product: 'Samsung Galaxy', price: 899, quantity: 1 },
86 | { product: 'Google Pixel', price: 799, quantity: 3 },
87 | ];
88 |
89 | const totalAmount = orders.reduce(function (accumulator, order) {
90 | return accumulator + order.price * order.quantity;
91 | }, 0);
92 |
93 | console.log(totalAmount); // 5294
94 | ```
95 |
96 | ### Polyfill of reduce()
97 |
98 | ```javascript
99 | if (!Array.prototype.myFilter) {
100 | Array.prototype.myReduce = (callback, initialValue) => {
101 | let accumulator = initialValue === undefined ? this[0] : initialValue;
102 | for (let i = initialValue === undefined ? 1 : 0; i < this.length; i++) {
103 | accumulator = callback(accumulator, this[i], i, this);
104 | }
105 | return accumulator;
106 | };
107 | }
108 |
109 | const myTotalAmount = orders.myReduce(function (accumulator, order) {
110 | return accumulator + order.price * order.quantity;
111 | }, 0);
112 |
113 | console.log(totalAmount); // 5294
114 | ```
115 |
116 | ### Question 1: Find the longest word length
117 |
118 | ```javascript
119 | const words = ['apple', 'banana', 'cherry', 'dragonfruit', 'elderberry'];
120 |
121 | const longestWordLength = words.reduce((maxLength, word) => {
122 | const currentLength = word.length;
123 | return currentLength > maxLength ? currentLength : maxLength;
124 | }, 0);
125 |
126 | console.log(longestWordLength); // Output: 11
127 | ```
128 |
129 | ### Question 2: Find the longest word
130 |
131 | ```javascript
132 | const longestWord = words.reduce((longestWord, word) => {
133 | return word.length > longestWord.length ? word : longestWord;
134 | }, "");
135 |
136 | console.log(longestWord); // Output: 'dragonfruit'
137 | ```
138 |
139 | ### Question 3: Calculate the factorial of the largest number in the array
140 |
141 | ```javascript
142 | const numbers = [5, 2, 8, 4, 3];
143 |
144 | const largestFactorial = numbers.reduce((largest, num) => {
145 | const currentFactorial = Array
146 | .from({ length: num })
147 | .map((_, i) => i + 1)
148 | .reduce((fact, val) => fact * val, 1);
149 |
150 | return currentFactorial > largest ? currentFactorial : largest;
151 | }, 1);
152 |
153 | console.log(largestFactorial); // Output: 40320 (8!)
154 | ```
155 |
156 | ### Question 4: Calculate the average score of students who scored above 90
157 |
158 | ```javascript
159 | const students = [
160 | { name: 'John', score: 85 },
161 | { name: 'Sarah', score: 92 },
162 | { name: 'Michael', score: 88 },
163 | { name: 'Emma', score: 95 },
164 | { name: 'Daniel', score: 90 },
165 | ];
166 |
167 | const above90StudentsAverage = students
168 | .filter((student) => student.score > 90)
169 | .reduce((acc, student, i, arr) => acc + student.score / arr.length, 0);
170 |
171 | console.log(above90StudentsAverage); // Output: 93.5 (average of 95 and 92)
172 | ```
173 |
174 | ## Practice Questions
175 |
176 | ### Question 5: Filter out books published before the year 2000 and return their titles
177 |
178 | ```javascript
179 | const books = [
180 | { title: 'Book 1', year: 1998 },
181 | { title: 'Book 2', year: 2003 },
182 | { title: 'Book 3', year: 1995 },
183 | { title: 'Book 4', year: 2001 },
184 | ];
185 |
186 | // Expected Output: ['Book 2', 'Book 4']
187 | ```
188 |
189 | ### Question 6: Capitalize the first letter of each word in the array
190 |
191 | ```javascript
192 | const strings = ['hello world', 'i am openai', 'welcome to javascript'];
193 |
194 | // Expected Output: ['Hello World', 'I Am Openai', 'Welcome To Javascript']
195 | ```
196 |
--------------------------------------------------------------------------------
/Array/README.md:
--------------------------------------------------------------------------------
1 | # Array Manipulation in JavaScript: From Basics to Advanced
2 |
3 |
4 |
5 |
6 |
7 |
8 | ### How do you create an empty array in JavaScript?
9 | ```javascript
10 | const arr = [1, 2, 3, 4, "Hello", {name: "Vishal"}, [1,2,3], 4];
11 | // const arr2 = new Array();
12 | console.log(arr);
13 | ```
14 |
15 | ### How do you access the first and last elements of an array?
16 | ```javascript
17 | const firstElement = arr[0]; // O(1)
18 | const arrLength = arr.length;
19 | const lastElement = arr[arrLength - 1];
20 | console.log(firstElement, arrLength, lastElement);
21 | ```
22 |
23 | ### How do you remove the last element from an array?
24 | ```javascript
25 | const lastElement1 = arr.pop(); // O(1)
26 | console.log(arr, lastElement1);
27 | ```
28 |
29 | ### How do you add an element to the end of an array?
30 | ```javascript
31 | arr.push(5); // O(1)
32 | console.log(arr);
33 | ```
34 |
35 | ### How do you add an element to the start of an array?
36 | ```javascript
37 | arr.unshift(0); // O(N)
38 | console.log(arr);
39 | ```
40 |
41 | ### How do you remove the first element from an array?
42 | ```javascript
43 | arr.shift(); // O(N)
44 | console.log(arr);
45 | ```
46 |
47 | ### How do you loop through an array in JavaScript?
48 | ```javascript
49 | for (let i = 0; i < arr.length; i++){
50 | console.log(arr[i]);
51 | }
52 |
53 | arr.forEach((x, i) => {
54 | console.log(x);
55 | });
56 |
57 | for (let x of arr){
58 | console.log(x);
59 | }
60 | ```
61 |
62 | ### Question 1: How do you check if an element exists in an array?
63 | ```javascript
64 | const findElement = (arr, target) => {
65 | for (let x of arr){
66 | if (x === target){
67 | return true;
68 | }
69 | }
70 | return false;
71 | }
72 |
73 | console.log(findElement(arr, "Hello"));
74 | console.log(findElement(arr, "H"));
75 | console.log(arr.includes("Hello"));
76 | ```
77 |
78 | ### Question 2: How do you find the index of an element in an array?
79 | ```javascript
80 | const findElementIndex = (arr, target) => {
81 | for (let i = 0; i < arr.length; i++){
82 | if (arr[i] === target){
83 | return i;
84 | }
85 | }
86 | return -1;
87 | }
88 |
89 | console.log(findElementIndex(arr, "Hello"));
90 | console.log(arr.indexOf("Hello"));
91 | ```
92 |
93 | ### How to delete, add & update elements from a specific index?
94 | ```javascript
95 | console.log(arr);
96 | arr.splice(1, 3);
97 | console.log(arr);
98 | arr.splice(1, 0, 2, 3, 4, 5, 6);
99 | console.log(arr);
100 | arr.splice(1, 3, 6, 7, 8);
101 | console.log(arr);
102 | ```
103 |
104 | ### `splice()` vs `slice()`
105 | ```javascript
106 | const subArr = arr.slice(1, 4); // [start, end)
107 | console.log(subArr);
108 | ```
109 |
110 | ### Shallow Copy of Array
111 | ```javascript
112 | const arrB = arr;
113 | arrB.splice(1, 4);
114 | console.log(arrB, arr);
115 | ```
116 |
117 | ### Deep Copy of Array
118 | ```javascript
119 | const arrC = [...arr];
120 | const arrD = Array.from(arr);
121 | const arrE = arr.concat();
122 | arrC.splice(1, 4);
123 | arrD.splice(1, 4);
124 | arrE.splice(1, 3);
125 | console.log(arrC, arrD, arrE, arr);
126 | ```
127 |
128 | ### How to concatenate two arrays in JavaScript?
129 | ```javascript
130 | const newArr = [...arr, ...arrE];
131 | const newArr2 = arr.concat(arrE);
132 | console.log(newArr, newArr2);
133 | ```
134 |
135 | ### Question 3: How can you check if two arrays are equal?
136 | ```javascript
137 | const isArrayEqual = (arr1, arr2) => {
138 | if (arr1.length !== arr2.length){
139 | return false;
140 | }
141 |
142 | for (let i = 0; i < arr1.length; i++){
143 | if (arr1[i] !== arr2[i]){
144 | return false;
145 | }
146 | }
147 | return true;
148 |
149 | // One Line solution
150 | // return arr1.length === arr2.length && arr1.every((ele, i) => arr1[i] === arr2[i]);
151 | }
152 |
153 | console.log(isArrayEqual([1, 2, 3], [1, 2, 3]));
154 | ```
155 |
156 | ### Question 4: How to sort an array in ascending and descending order?
157 | ```javascript
158 | const x = [1, 4, 6, 0, -9, -5];
159 | x.sort(); // O(NlogN)
160 | console.log(x);
161 |
162 | x.sort((a, b) => b - a);
163 | console.log(x);
164 | ```
165 |
166 | ### Question 5: How to reverse an array?
167 | ```javascript
168 | x.reverse();
169 | console.log(x);
170 | ```
171 |
172 | ### Map, Filter & Reduce
173 | ```javascript
174 | const newMapArr = x.map((ele, i) => ele * ele);
175 | console.log(newMapArr);
176 |
177 | const positiveNumbers = x.filter((ele, i) => ele > 0);
178 | console.log(positiveNumbers);
179 |
180 | const sumOFArr = positiveNumbers.reduce((acc, ele) => acc + ele);
181 | console.log(sumOFArr);
182 | ```
183 |
184 | ### Flat: [1, 2, 4, 5, 6, 7, 8, 9]
185 | ```javascript
186 | const y = [1, 2, [4, 5, [6, 7]], 8, 9];
187 | const flattedArray = y.flat(2);
188 | console.log(flattedArray);
189 | ```
190 |
191 | ### `filter()` vs `find()`
192 | ```javascript
193 | const positiveNumber = x.find((ele, i) => ele > 0);
194 | console.log(positiveNumber);
195 | ```
196 |
197 | ## Practice Questions
198 |
199 | - [Two Sum](https://leetcode.com/problems/two-sum/)
200 | - [Majority Element](https://leetcode.com/problems/majority-element/)
201 | - [Remove Duplicates from sorted array](https://leetcode.com/problems/remove-duplicates-from-sorted-array)
202 | - [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array)
203 | - [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/)
204 | - [Move Zeroes](https://leetcode.com/problems/move-zeroes)
205 | - [Remove Element](https://leetcode.com/problems/remove-element)
206 | - [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)
--------------------------------------------------------------------------------
/Basics/README.md:
--------------------------------------------------------------------------------
1 | # Practise Loop, functions & Math Problems
2 |
3 |
4 |
5 |
6 |
7 |
8 | ### Question 1: Sum of all natural numbers from 1 to n
9 |
10 | ```javascript
11 | function sumOfNaturalNumber(num){
12 | let sum = 0;
13 | for(let i=1; i<=num; i++){
14 | sum = sum + i;
15 | }
16 | return sum;
17 | }
18 |
19 | console.log(sumOfNaturalNumber(5)); // 15
20 | console.log(sumOfNaturalNumber(10)); // 55
21 | console.log(sumOfNaturalNumber(8)); // 36
22 | ```
23 |
24 | ### Question 2: Sum of digits of a number
25 |
26 | ```javascript
27 | function sumOfDigits(num){
28 | let sum = 0;
29 | while(num > 0){
30 | sum += num%10;
31 | num = Math.floor(num / 10);
32 | }
33 | return sum;
34 | }
35 |
36 | console.log(sumOfDigits(1287)); // 18
37 | ```
38 |
39 | ### Question 3: Count the number of digits of a number
40 |
41 | ```javascript
42 | function countDigits(num){
43 | num = Math.abs(num);
44 | let count = 0;
45 | do {
46 | count++;
47 | num = Math.floor(num / 10);
48 | } while (num > 0);
49 | return count;
50 | }
51 |
52 | console.log(countDigits(121)); // 3
53 | console.log(countDigits(-1211413131)); // 10
54 | ```
55 |
56 | ### Question 4: Check if a number is palindrome
57 |
58 | ```javascript
59 | let isPalindrome = function(x) {
60 | let copyNum = x, reverseNum = 0;
61 |
62 | while(copyNum > 0){
63 | const lastDigit = copyNum % 10;
64 | reverseNum = reverseNum * 10 + lastDigit;
65 | copyNum = Math.floor(copyNum / 10);
66 | }
67 |
68 | return x === reverseNum;
69 | };
70 |
71 | console.log(isPalindrome(121)); // true
72 | console.log(isPalindrome(1234)); // false
73 | ```
74 |
75 | ### Question 5: Find nth Fibonacci number
76 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence,
77 | such that each number is the sum of the two preceding ones, starting from 0 and 1.
78 |
79 | ```javascript
80 | let fib = function(n) {
81 | if(n < 2){
82 | return n;
83 | }
84 |
85 | let prev = 0, curr = 1, next;
86 | for(let i=2; i<= n; i++){
87 | next = prev + curr;
88 | prev = curr;
89 | curr = next;
90 | }
91 | return next;
92 | };
93 |
94 | // Fibonacci Sequence: 0 1 1 2 3 5 8...
95 | console.log(fib(5)); // 5
96 | console.log(fib(10)); // 55
97 | ```
98 |
99 | ### Question 6: Missing Number in an Array
100 | Given an array nums containing n distinct numbers in the range [0, n],
101 | return the only number in the range that is missing from the array.
102 | ```javascript
103 | let missingNumber = function(nums) {
104 | let sum = 0;
105 | for(let i=0; i nums.length*(nums.length+1)/2 - nums.reduce((acc, num) => num + acc);
113 |
114 | console.log(missingNumber([3,0,1])); // 2
115 | console.log(missingNumber([9,6,4,2,3,5,7,0,1])); // 8
116 | ```
117 |
118 | ## Practice Questions
119 |
120 | - [Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/)
121 | - [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)
122 | - [Power of Two](https://leetcode.com/problems/power-of-two/)
123 | - [Find Square root of a Number](https://leetcode.com/problems/sqrtx/)
--------------------------------------------------------------------------------
/Binary Tree/index.js:
--------------------------------------------------------------------------------
1 | // Binary Tree
2 |
3 | class Node{
4 | constructor(data){
5 | this.data = data;
6 | this.left = null;
7 | this.right = null;
8 | }
9 | }
10 |
11 |
12 | class BinaryTree{
13 | constructor(){
14 | this.root = null;
15 | }
16 |
17 | insert(data){
18 | const newNode = new Node(data);
19 | if(this.root == null){
20 | this.root = newNode;
21 | } else{
22 | this.insertNode(this.root, newNode);
23 | }
24 | }
25 |
26 | insertNode(node, newNode){
27 | if (newNode.data < node.data){
28 | if(node.left == null){
29 | node.left = newNode;
30 | } else {
31 | this.insertNode(node.left, newNode);
32 | }
33 | } else {
34 | if(node.right == null){
35 | node.right = newNode;
36 | } else {
37 | this.insertNode(node.right, newNode);
38 | }
39 | }
40 | }
41 |
42 | inOrder(node = this.root){
43 | if(node != null){
44 | this.inOrder(node.left);
45 | console.log(node.data);
46 | this.inOrder(node.right);
47 | }
48 | }
49 |
50 | preOrder(node = this.root) {
51 | if (node != null) {
52 | console.log(node.data);
53 | this.preOrder(node.left);
54 | this.preOrder(node.right);
55 | }
56 | }
57 |
58 | postOrder(node = this.root) {
59 | if (node != null) {
60 | this.postOrder(node.left);
61 | this.postOrder(node.right);
62 | console.log(node.data);
63 | }
64 | }
65 |
66 | levelOrder(node = this.root){
67 | if(node == null){
68 | return;
69 | }
70 |
71 | const queue = [root];
72 |
73 | while(queue.length > 0){
74 | const currNode = queue.shift();
75 | console.log(currNode.data);
76 |
77 | if(currNode.left){
78 | queue.push(currNode.left);
79 | }
80 |
81 | if(currNode.right){
82 | queue.push(currNode.right);
83 | }
84 | }
85 | }
86 |
87 | levelOrderRecursive = function (root) {
88 | const result = [];
89 | const traverse = (node, level) => {
90 | if (!node) return;
91 |
92 | if (result.length === level) {
93 | result.push([]);
94 | }
95 |
96 | result[level].push(node.val);
97 | traverse(node.left, level + 1);
98 | traverse(node.right, level + 1);
99 | };
100 | traverse(root, 0, result);
101 | return result;
102 | };
103 |
104 | zigZagLevelOrderTraversal(node = this.root) {
105 | if (node == null) {
106 | return [];
107 | }
108 |
109 | const queue = [root];
110 | const result = [];
111 | let direction = 0;
112 | while (queue.length > 0) {
113 | const currSize = queue.length;
114 | const currentLevel = [];
115 | while(currSize--){
116 | const currNode = queue.shift();
117 | currentLevel.push(currNode.data)
118 |
119 | if (currNode.left) {
120 | queue.push(currNode.left);
121 | }
122 |
123 | if (currNode.right) {
124 | queue.push(currNode.right);
125 | }
126 | }
127 | if(direction){
128 | direction = 0;
129 | currentLevel.reverse();
130 | } else {
131 | direction = 1;
132 | }
133 | result.push(currentLevel);
134 | }
135 | return result;
136 | }
137 |
138 | /**
139 | * 1
140 | * 2 3
141 | * 5 4
142 | *
143 | * q[ 5, 4]
144 | * 1, 2, 3, 5, 4
145 | */
146 |
147 | /**
148 | * A binary tree's maximum depth is the number of nodes
149 | * along the longest path from the root node down to the farthest leaf node.
150 | */
151 | maxiMumDepthOfBinaryTree(node = this.root){
152 | if(node == null){
153 | return 0;
154 | }
155 |
156 | return 1 + Math.max(this.maxiMumDepthOfBinaryTree(node.left), this.maxiMumDepthOfBinaryTree(node.right));
157 | }
158 |
159 | /**
160 | * Given the root of a binary tree and an integer targetSum, return true if the tree has a
161 | * root-to-leaf path such that adding up all the values along the path equals targetSum.
162 | */
163 | pathSum(node = this.root, targetSum){
164 | if(node == null){
165 | return false;
166 | }
167 |
168 | if(node.left == null & node.right == null){
169 | return node.data === targetSum;
170 | }
171 |
172 | return this.pathSum(node.left, targetSum - node.data) || this.pathSum(node.right, targetSum - node.data);
173 | }
174 |
175 | /**
176 | * Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
177 | */
178 | symmetricTree(node = this.root){
179 | return this.symmetricTreeHelper(node, node);
180 | }
181 |
182 | symmetricTreeHelper(p, q){
183 | if(p == null && q == null){
184 | return true;
185 | }
186 |
187 | if(p == null || q == null){
188 | return false;
189 | }
190 |
191 | return p.data == q.data && this.symmetricTreeHelper(p.left, q.right) && this.symmetricTreeHelper(p.right, q.left)
192 | }
193 |
194 | /**
195 | * Given the roots of two binary trees p and q, write a function to check if they are the same or not.
196 | */
197 | sameTree(p, q){
198 | if(p == null && q == null){
199 | return true;
200 | }
201 |
202 | if(p == null || q == null){
203 | return false;
204 | }
205 |
206 | return p.data == q.data && this.sameTree(p.left, q.left) && this.sameTree(p.right, q.right)
207 | }
208 |
209 | diameterOfBinaryTree(node = this.root){
210 | let ans = [0];
211 | this.diameterOfBinaryTreeHelper(node, ans);
212 | return ans[0];
213 | }
214 |
215 | diameterOfBinaryTreeHelper(node, ans){
216 | if(node == null){
217 | return 0;
218 | }
219 |
220 | let leftDepth = this.diameterOfBinaryTreeHelper(node.left, ans);
221 | let rightDepth = this.diameterOfBinaryTreeHelper(node.right, ans);
222 |
223 | ans[0] = Math.max(ans[0], 1 + leftDepth + rightDepth);
224 |
225 | return max(leftDepth, rightDepth);
226 | }
227 |
228 |
229 | // Given the root of a binary tree, invert the tree, and return its root.
230 | invertBinaryTree(node = this.root){
231 | if(node){
232 | node.left = this.invertBinaryTree(node.right);
233 | node.right = this.invertBinaryTree(node.left);
234 | }
235 | return node;
236 | }
237 |
238 | /**
239 | * A height-balanced binary tree is a binary tree in which the depth
240 | * of the two subtrees of every node never differs by more than one.
241 | */
242 |
243 | heightOfBinaryTree(node = this.root){
244 | if(node == null){
245 | return 0;
246 | }
247 |
248 | leftHeight = this.heightOfBinaryTree(node.left);
249 | if(leftHeight == -1){
250 | return -1;
251 | }
252 |
253 | rightHeight = this.heightOfBinaryTree(node.right);
254 | if(rightHeight == -1){
255 | return -1;
256 | }
257 |
258 | if(Math.abs(left - right) > 1){
259 | return -1;
260 | }
261 |
262 | return max(leftHeight, rightHeight) + 1;
263 | }
264 |
265 | balanceBinaryTree(node = this.root){
266 | return this.heightOfBinaryTree(node) != -1;
267 | }
268 |
269 | /**
270 | * “The lowest common ancestor is defined between two nodes p and q as the lowest node
271 | * in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
272 | */
273 | lowestCommonAncestor(node = this.root, p, q){
274 | if(p.data < node.data && q.data < node.data){
275 | return this.lowestCommonAncestor(node.left);
276 | }
277 |
278 | if (p.data > node.data && q.data > node.data) {
279 | return this.lowestCommonAncestor(node.right);
280 | }
281 | return this.root;
282 | }
283 |
284 | /**
285 | *
286 | * Given the root of a binary tree, imagine yourself standing on the right side of it,
287 | * return the values of the nodes you can see ordered from top to bottom.
288 | */
289 | rightSideView = function (root) {
290 | if (root == null) return []
291 | let result = []
292 | let queue = [root]
293 | while (queue.length > 0) {
294 | let currSize = queue.length;
295 | result.push(queue[currSize - 1].val);
296 |
297 | while (currSize--) {
298 | let node = queue.shift()
299 | if (node.left) queue.push(node.left);
300 | if (node.right) queue.push(node.right);
301 | }
302 | }
303 | return result;
304 | };
305 |
306 | recursiveRightSideView = function (root) {
307 | const result = [];
308 | const traverse = (node, level) => {
309 | if (!node) return;
310 | if (result.length === level) result.push(node.val);
311 | traverse(node.right, level + 1);
312 | traverse(node.left, level + 1);
313 | };
314 | traverse(root, 0);
315 | return result;
316 | };
317 |
318 | buildTree = function (preorder, inorder) {
319 | if (preorder.length == 0) return null;
320 | const rootIndex = inorder.indexOf(preorder[0]);
321 | const rootNode = new Node(preorder[0]);
322 |
323 | rootNode.left = this.buildTree(preorder.slice(1, rootIndex + 1), inorder.slice(0, rootIndex));
324 | rootNode.right = this.buildTree(preorder.slice(rootIndex + 1), inorder.slice(rootIndex + 1));
325 | return rootNode;
326 | };
327 |
328 | /**
329 | * inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
330 | * root = 3, rootIndex = 1, inorder: [9] [15, 20, 7], postorder: [9], [15, 7, 20]
331 | */
332 |
333 | buildTree = function (inorder, postorder) {
334 | if(postorder.length == 0) return null;
335 | let postOrderLength = postorder.length;
336 | const rootIndex = inorder.indexOf(postorder[postOrderLength - 1]);
337 | const rootNode = new Node(postorder[postOrderLength - 1]);
338 |
339 | rootNode.left = this.buildTree(inorder.slice(0, rootIndex), postorder.slice(0, rootIndex));
340 | rootNode.right = this.buildTree(inorder.slice(rootIndex + 1), postorder.slice(rootIndex, postOrderLength - 1));
341 | return rootNode;
342 | };
343 |
344 | /**
345 | * You are given the root of a binary tree containing digits from 0 to 9 only.
346 | * Each root-to-leaf path in the tree represents a number.
347 | * For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
348 | * Return the total sum of all root-to-leaf numbers
349 | */
350 | sumNumbers = function (node, curr = 0) {
351 | if (node == null) {
352 | return 0;
353 | }
354 |
355 | curr = curr * 10 + node.val;
356 | if (node.left == null && node.right == null) {
357 | return curr;
358 | }
359 |
360 | return this.sumNumbers(node.left, curr) + this.sumNumbers(node.right, curr);
361 | }
362 |
363 | /**
364 | * Given the root of a binary tree, flatten the tree into a "linked list":
365 | * The "linked list" should use the same TreeNode class where the right child pointer points to the next
366 | * node in the list and the left child pointer is always null.
367 | * The "linked list" should be in the same order as a pre-order traversal of the binary tree.
368 | */
369 | flatten(node = this.root){
370 | if(node == null){
371 | return;
372 | }
373 | let curr = node, last = null;
374 | while(curr){
375 | if(curr.left){
376 | last = curr.left;
377 |
378 | while(last.right){
379 | last = last.right;
380 | }
381 |
382 | last.right = curr.right;
383 | curr.right = curr.left;
384 | curr.left = null;
385 | }
386 | curr = curr.right;
387 | }
388 | }
389 |
390 |
391 | maxPathSum = function (root) {
392 | const res = [Number.NEGATIVE_INFINITY]
393 | solve(root, res);
394 | return res;
395 | };
396 |
397 | solve = function (root, res) {
398 | if (root == null) {
399 | return 0;
400 | }
401 |
402 | let leftPathSum = solve(root.left, res);
403 | let rightPathSum = solve(root.right, res);
404 |
405 | let currPathSum = Math.max(Math.max(leftPathSum, rightPathSum) + root.val, root.val);
406 | let ans = Math.max(currPathSum, leftPathSum + rightPathSum + root.val);
407 | res[0] = Math.max(res[0], ans);
408 | return currPathSum;
409 | }
410 | }
411 |
412 |
413 | /***
414 | *
415 | *
416 | *
417 | * 1
418 | * 2 3
419 | * 4 5 7
420 | * 6
421 | *
422 | *
423 | * 1
424 | * 2
425 | * 4
426 | * 6
427 | * 5
428 | * 3
429 | * 7
430 | *
431 | *
432 | * curr = 1, last = null
433 | * curr = 4, last = 6
434 | *
435 | */
436 |
437 |
--------------------------------------------------------------------------------
/Binary Tree/question.txt:
--------------------------------------------------------------------------------
1 | Sure, here are the binary tree questions along with their LeetCode links:
2 |
3 | ### Easy
4 |
5 | 1. Binary Tree Inorder Traversal: https://leetcode.com/problems/binary-tree-inorder-traversal/
6 |
7 | 2. Binary Tree Preorder Traversal: https://leetcode.com/problems/binary-tree-preorder-traversal/
8 |
9 | 3. Binary Tree Postorder Traversal: https://leetcode.com/problems/binary-tree-postorder-traversal/
10 |
11 | 4. Maximum Depth of Binary Tree: https://leetcode.com/problems/maximum-depth-of-binary-tree/
12 |
13 | 5. Symmetric Tree: https://leetcode.com/problems/symmetric-tree/
14 |
15 | 6. Path Sum: https://leetcode.com/problems/path-sum/
16 |
17 | 7. Invert Binary Tree: https://leetcode.com/problems/invert-binary-tree/
18 |
19 | 8. Diameter of Binary Tree: https://leetcode.com/problems/diameter-of-binary-tree/
20 |
21 | 9. Balanced Binary Tree: https://leetcode.com/problems/balanced-binary-tree/
22 |
23 | 10. Lowest Common Ancestor of a Binary Search Tree: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
24 |
25 | 11. Same Tree: https://leetcode.com/problems/same-tree/
26 |
27 | ### Medium
28 |
29 | 1. Binary Tree Level Order Traversal: https://leetcode.com/problems/binary-tree-level-order-traversal/
30 |
31 | 2. Binary Tree Right Side View: https://leetcode.com/problems/binary-tree-right-side-view/
32 |
33 | 3. Construct Binary Tree from Preorder and Inorder Traversal: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
34 |
35 | 4. Construct Binary Tree from Inorder and Postorder Traversal: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
36 |
37 | 5. Binary Tree Zigzag Level Order Traversal: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
38 |
39 | 6. Sum Root to Leaf Numbers: https://leetcode.com/problems/sum-root-to-leaf-numbers/
40 |
41 | 7. Flatten Binary Tree to Linked List: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
42 |
43 | 8. Binary Tree Maximum Path Sum: https://leetcode.com/problems/binary-tree-maximum-path-sum/
44 |
45 | 9. Find Bottom Left Tree Value: https://leetcode.com/problems/find-bottom-left-tree-value/
46 |
47 | 10. Lowest Common Ancestor of a Binary Tree: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
48 |
49 | ### Hard
50 |
51 | 1. Serialize and Deserialize Binary Tree: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
52 |
53 | 2. Recover Binary Search Tree: https://leetcode.com/problems/recover-binary-search-tree/
54 |
55 | 3. Binary Tree Cameras: https://leetcode.com/problems/binary-tree-cameras/
56 |
57 | 4. Binary Tree Maximum Path Sum II: https://leetcode.com/problems/binary-tree-maximum-path-sum-ii/ (Note: LeetCode does not have this exact problem; consider practicing asimilar problem like [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/))
58 |
59 | 5. Vertical Order Traversal of a Binary Tree: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
60 |
61 | 6. All Nodes Distance K in Binary Tree: https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/
62 |
63 | 7. Sum of Distances in Tree: https://leetcode.com/problems/sum-of-distances-in-tree/
64 |
65 | 8. Count Complete Tree Nodes: https://leetcode.com/problems/count-complete-tree-nodes/
66 |
67 | 9. Kth Smallest Element in a BST: https://leetcode.com/problems/kth-smallest-element-in-a-bst/
68 |
69 | 10. Smallest Subtree with All the Deepest Nodes: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
70 |
71 |
72 | ### Very Hard (by Akash Bansal):
--------------------------------------------------------------------------------
/Linked List/README.md:
--------------------------------------------------------------------------------
1 | # Linked List in JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ## Source Code
10 | ```javascript
11 | class Node {
12 | constructor(data) {
13 | this.data = data;
14 | this.next = null;
15 | }
16 | }
17 |
18 | class LinkedList {
19 | constructor() {
20 | this.head = null;
21 | this.size = 0;
22 | }
23 |
24 | insertAtHead(data) {
25 | const newNode = new Node(data);
26 | newNode.next = this.head;
27 | this.head = newNode;
28 | this.size++;
29 | }
30 |
31 | insertAt(index, data) {
32 | if (index < 0 || index > this.size) {
33 | return "Invalid Index"
34 | }
35 |
36 | if (index === 0) {
37 | this.insertAtHead(data)
38 | return;
39 | }
40 |
41 | let newNode = new Node(data)
42 | let temp = this.head;
43 | for (let i = 0; i < index - 1; i++) {
44 | temp = temp.next;
45 | }
46 |
47 | newNode.next = temp.next;
48 | temp.next = newNode;
49 |
50 | this.size++;
51 | }
52 |
53 | print() {
54 | let result = ""
55 | let temp = this.head;
56 | while (temp) {
57 | result += `${temp.data}->`
58 | temp = temp.next;
59 | }
60 | return result
61 | }
62 |
63 | removeAtHead() {
64 | if (this.isEmpty()) {
65 | return "List is already empty"
66 | }
67 |
68 | this.head = this.head.next;
69 | this.size--;
70 | }
71 |
72 | removeElement(data) {
73 | if (this.isEmpty()) {
74 | return "List is already empty"
75 | }
76 |
77 | let current = this.head, prev = null;
78 | while (current) {
79 | if (current.data === data) {
80 | if (prev === null) {
81 | this.head = current.next;
82 | } else {
83 | prev.next = current.next;
84 | }
85 | this.size--;
86 | return current.element
87 | }
88 | prev = current;
89 | current = prev.next;
90 | }
91 | return -1;
92 | }
93 |
94 | searchElement(data) {
95 | let curr = this.head;
96 | let index = 0;
97 |
98 | while (curr) {
99 | if (curr.data === data) {
100 | return index;
101 | }
102 | index++;
103 | curr = curr.next;
104 | }
105 | return -1;
106 | }
107 |
108 | middleNode() {
109 | let slow = this.head, fast = this.head;
110 | while (fast && fast.next) {
111 | fast = fast.next.next;
112 | slow = slow.next;
113 | }
114 | return slow;
115 | };
116 |
117 | reverse() {
118 | let prev = null, curr = this.head, next;
119 | while (curr) {
120 | next = curr.next;
121 | curr.next = prev;
122 | prev = curr;
123 | curr = next;
124 | }
125 | this.head = prev;
126 | }
127 |
128 | isCycle() {
129 | let slow = this.head, fast = this.head;
130 | while (fast && fast.next) {
131 | fast = fast.next.next;
132 | slow = slow.next;
133 |
134 | if (slow === fast) {
135 | return true;
136 | }
137 | }
138 | return false;
139 | }
140 |
141 | isEmpty() {
142 | return this.size === 0;
143 | }
144 | }
145 |
146 | let list = new LinkedList()
147 | list.insertAtHead(43) // 43
148 | list.insertAtHead(50) // 50->43
149 | list.insertAtHead(34) // 34->50->43
150 | list.insertAt(2, 46) // 34->50->46->43
151 | list.removeAtHead() // 50->46->43
152 | list.removeElement(46) // 50->43
153 | list.reverse() // 43->50
154 | console.log(list.isCycle()) // false
155 | console.log(list.middleNode()) // 50
156 | console.log(list.searchElement(50)) //1
157 | console.log(list.print()) // 43->50
158 | ```
159 |
160 | ## Practice Questions:
161 |
162 | 1. [Middle of Linked List](https://leetcode.com/problems/middle-of-the-linked-list/)
163 | 2. [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)
164 | 3. [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
165 | 4. [Remove Duplicates from Sorted list I](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)
166 | 5. [Remove Duplicates from Sorted list II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)
167 | 6. [Linked List Cycle I](https://leetcode.com/problems/linked-list-cycle/)
168 | 7. [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)
169 | 8. [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)
170 | 9. [Next Greater Node in Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/)
171 | 10. [Remove Zero Consecutive Nodes from Linked List](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/)
172 | 11. [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)
173 | 12. [Odd Even Linked list](https://leetcode.com/problems/odd-even-linked-list/)
174 | 13. [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)
175 | 14. [Reorder List](https://leetcode.com/problems/reorder-list/)
176 | 15. [Remove Nth Node from End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
177 | 16. [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
178 |
179 | **Note**: You can find solutions of all these problems in [this playlist](https://www.youtube.com/playlist?list=PLSH9gf0XETourRyZW56Rdh9e0Phx-AJM5)
180 |
181 | Before checking the solutions, challenge yourself to solve the problems on your own. If you're stuck, watch the solution video up to the intuition part. Then, code it yourself before watching the complete solution.
182 |
183 | This approach builds solid problem-solving skills.
--------------------------------------------------------------------------------
/Objects/README.md:
--------------------------------------------------------------------------------
1 | # Objects in JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ### Creating an object
10 | ```javascript
11 | const person = {
12 | name: "Vishal",
13 | age: 21,
14 | isEducator: true,
15 | skills: ["C++", "JavaScript", "ReactJS"],
16 | projects: {
17 | "Frontend Freaks": "Frontend Development Project",
18 | },
19 | code: function(){
20 | return "start coding";
21 | },
22 | walk: () => {
23 | return "start walking";
24 | }
25 | }
26 | ```
27 |
28 | ### Accessing properties using Dot Operator
29 | ```javascript
30 | console.log(person.age); // 21
31 | ```
32 |
33 | ### Accessing properties using []
34 | ```javascript
35 | console.log(person["name"]); // Vishal
36 | ```
37 |
38 | ### Checking if a key exists in the object
39 | ```javascript
40 | console.log(person.hasOwnProperty("name")) // true
41 | console.log(person.hasOwnProperty("last Name")) // false
42 | ```
43 |
44 | ### Adding, deleting, and updating keys
45 | ```javascript
46 | person.name = "Vivek" // Updating name key
47 | person.location = "New Delhi" // Adding location Key
48 | delete person.projects // Deleting projects key
49 | console.log(person);
50 | ```
51 |
52 | ### Shallow Copy
53 | ```javascript
54 | const person2 = person
55 | person2.isEducator = false;
56 | ```
57 |
58 | ### Deep Copy
59 | ```javascript
60 | const person3 = Object.assign({}, person)
61 | // Nested Objects still do shallow copy here, there for we use lodash cloneDeep method(out of scope for this course)
62 | person3.skills = null;
63 | ```
64 |
65 | ### Using freeze and seal methods
66 | ```javascript
67 | Object.freeze(person) // User can't add or delete or update keys
68 | console.log(person);
69 | console.log(Object.isFrozen(person)) // true
70 | ```
71 |
72 | ```javascript
73 | Object.seal(person) // User can't add or delete keys but can update the value
74 | console.log(Object.isSealed(person)); // true
75 | ```
76 |
77 | ### Keys, Values & Entries
78 | ```javascript
79 | console.log(Object.keys(person)) // ["name" , "age", "isEducator", ...]
80 | console.log(Object.values(person)) // ["Vishal", 21, true, ...]
81 | console.log(Object.entries(person)) // [["name", "Vishal"], ["age", 21], ["isEducator", true], ...]
82 | ```
83 |
84 | ### Looping through an Object using for...in
85 | ```javascript
86 | for (let key in person) {
87 | console.log(key + ":", person[key]); // name: Vishal age: 21, isEducator: true ...
88 | }
89 | ```
90 |
91 | ### Looping through an Object using forEach with Object.keys
92 | ```javascript
93 | Object.keys(person).forEach((key) => console.log(key))
94 | ```
95 | ### How to check if two objects are equal?
96 | ```javascript
97 | console.log(Object.is(person, person3))
98 | ```
99 |
100 | ### find count of all players
101 | ```javascript
102 | const data = {
103 | id: 1,
104 | name: ["P1", "P4"],
105 | next: {
106 | id: 2,
107 | name: ["P3"],
108 | next: {
109 | id: 3,
110 | name: ["P3", "P4", "P5"],
111 | next: {
112 | id: 4,
113 | name: ["P1", "P2", "P4"],
114 | next: {
115 | id: 5,
116 | name: ["P2", "P3", "P5"],
117 | next: null
118 | }
119 | }
120 | }
121 | }
122 | };
123 |
124 | const playerCount = (data) => {
125 | if(data === null){
126 | return {}
127 | }
128 |
129 | let countPlayer = {}
130 | for(let player of data.name){
131 | countPlayer[player] = (countPlayer[player] || 0) + 1;
132 | }
133 | const nextPlayerCount = playerCount(data.next);
134 |
135 | for(let key in nextPlayerCount){
136 | countPlayer[key] = (countPlayer[key] || 0) + nextPlayerCount[key]
137 | }
138 | return countPlayer;
139 | }
140 |
141 | const countPlayer = playerCount(data);
142 | console.log(countPlayer) // {p1: 2, p4: 3, p3: 3, p2: 2: p5: 2}
143 | ```
144 |
145 | ### Prototype and Inheritance in JavaScript Objects
146 |
147 | ```javascript
148 | const obj1 = {
149 | name: "Vishal"
150 | }
151 |
152 | const obj2 = {
153 | age: 21,
154 | __proto__: obj1
155 | }
156 |
157 | console.log(obj2.name);
158 | ```
159 |
160 | ### Question 2: Group Anagrams (LeetCode 49)
161 |
162 | ```javascript
163 | let anagrams = {};
164 | for (let i = 0; i < strs.length; i++) {
165 | const str = strs[i].split("").sort().join("")
166 | if (!anagrams.hasOwnProperty(str)) {
167 | anagrams[str] = []
168 | }
169 |
170 | anagrams[str] = [...anagrams[str], strs[i]];
171 | }
172 | return Object.values(anagrams);
173 | ```
174 |
175 | ## Practice Questions
176 |
177 | 1. [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs/)
178 | 2. [Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings/)
179 | 3. [Two Sum](https://leetcode.com/problems/two-sum/)
180 | 4. [Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements/)
181 | 5. [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/)
182 | 6. [Integer to Roman](https://leetcode.com/problems/integer-to-roman/)
183 | 7. [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
184 | 8. [Group Anagrams](https://leetcode.com/problems/group-anagrams/)
185 | 9. [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)
186 |
--------------------------------------------------------------------------------
/Practise.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FrontendFreaks/DSA-in-JavaScript/860a62bf880bca000f1db9b74a20458bdec33404/Practise.js
--------------------------------------------------------------------------------
/Queue/README.md:
--------------------------------------------------------------------------------
1 | # Queue in JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ## Queue Implementation Using Array
10 |
11 | ```javascript
12 | class Queue{
13 | constructor(){
14 | this.queue = []
15 | }
16 |
17 | enqueue(data){
18 | this.queue.push(data)
19 | }
20 |
21 | dequeue(){
22 | return this.isEmpty() ? null : this.queue.shift()
23 | }
24 |
25 | front(){
26 | return this.isEmpty() ? null : this.queue.at(0)
27 | }
28 |
29 | back(){
30 | return this.isEmpty() ? null : this.queue.at(-1)
31 | }
32 |
33 | isEmpty(){
34 | return this.queue.length === 0;
35 | }
36 |
37 | size(){
38 | return this.queue.length
39 | }
40 | }
41 |
42 | const queue = new Queue()
43 | queue.enqueue(1)
44 | queue.enqueue(2)
45 | queue.enqueue(3)
46 | console.log(queue.dequeue()) // 1
47 | console.log(queue.front()) // 2
48 | console.log(queue.back()) // 3
49 | console.log(queue.isEmpty()) // false
50 | console.log(queue.size()) // 2
51 | console.log(queue) // Queue { queue: [2, 3]}
52 | ```
53 |
54 |
55 | ## Queue Implementation Using Linked List
56 |
57 | ```javascript
58 | class Node{
59 | constructor(data){
60 | this.data = data;
61 | this.next = null;
62 | }
63 | }
64 |
65 | class QueueLinkedList{
66 | constructor(){
67 | this.head = null;
68 | this.tail = null;
69 | this.size = 0;
70 | }
71 |
72 | enqueue(data){
73 | const newNode = new Node(data);
74 |
75 | if(this.head === null){
76 | this.head = newNode;
77 | } else{
78 | this.tail.next = newNode;
79 | }
80 |
81 | this.tail = newNode;
82 | this.size++;
83 | }
84 |
85 | dequeue(){
86 | if(this.isEmpty()){
87 | return null;
88 | }
89 |
90 | const deletedItem = this.head.data;
91 | this.head = this.head.next;
92 | this.size--;
93 | return deletedItem;
94 | }
95 |
96 | front(){
97 | return this.isEmpty() ? null : this.head.data;
98 | }
99 |
100 | back(){
101 | return this.isEmpty() ? null : this.tail.data;
102 | }
103 |
104 | isEmpty(){
105 | return this.size === 0;
106 | }
107 | }
108 |
109 | const queue1 = new QueueLinkedList()
110 | queue1.enqueue(5)
111 | queue1.enqueue(6)
112 | queue1.enqueue(7)
113 | console.log(queue1.dequeue()) // 5
114 | console.log(queue1.front()) // 6
115 | console.log(queue1.back()) // 7
116 | console.log(queue1.size) // 2
117 | console.log(queue1)
118 | /* QueueLinkedList
119 | {
120 | head: Node { data: 6, next: Node { data: 7, next: null }},
121 | tail: Node{data: 7, next: null},
122 | size: 2
123 | }
124 | */
125 | ```
126 |
127 | ## Implement Queue Using Stacks
128 |
129 | ```javascript
130 | class QueueStack{
131 | constructor(){
132 | this.stack1 = []
133 | this.stack2 = []
134 | }
135 |
136 | push(x){
137 | while(this.stack1.length > 0){
138 | this.stack2.push(this.stack1.pop())
139 | }
140 |
141 | this.stack1.push(x);
142 |
143 | while(this.stack2.length > 0){
144 | this.stack1.push(this.stack2.pop())
145 | }
146 | };
147 |
148 | pop(){
149 | if(this.empty()){
150 | return null;
151 | }
152 |
153 | return this.stack1.pop()
154 | };
155 |
156 | peek(){
157 | return this.empty() ? null : this.stack1.at(-1)
158 | };
159 |
160 | empty(){
161 | return this.stack1.length === 0
162 | };
163 | }
164 | ```
165 |
166 | ## Implement Circular Queue Using Linked List
167 |
168 | ```javascript
169 | class Node {
170 | constructor(data) {
171 | this.data = data;
172 | this.next = null;
173 | }
174 | }
175 |
176 | class MyCircularQueue {
177 | constructor(k) {
178 | this.capacity = k;
179 | this.head = null;
180 | this.tail = null;
181 | this.size = 0;
182 | }
183 |
184 | enQueue(data) {
185 | if(this.isFull()){
186 | return false;
187 | }
188 |
189 | const newNode = new Node(data);
190 |
191 | if(this.head === null){
192 | this.head = newNode;
193 | } else{
194 | this.tail.next = newNode;
195 | }
196 |
197 | this.tail = newNode;
198 | this.tail.next = this.head;
199 | this.size++;
200 | return true;
201 | }
202 |
203 | deQueue() {
204 | if(this.isEmpty()){
205 | return false;
206 | }
207 |
208 | if(this.head === this.tail){
209 | this.head = null;
210 | this.tail = null;
211 | } else{
212 | this.head = this.head.next;
213 | this.tail.next = this.head;
214 | }
215 |
216 | this.size--;
217 | return true;
218 | }
219 |
220 | Front() {
221 | return this.isEmpty() ? -1 : this.head.data;
222 | }
223 |
224 | Rear() {
225 | return this.isEmpty() ? -1 : this.tail.data;
226 | }
227 |
228 | isEmpty() {
229 | return this.size === 0;
230 | }
231 |
232 | isFull() {
233 | return this.size === this.capacity;
234 | }
235 | }
236 | ```
237 |
238 | ## Practice Questions
239 |
240 | 1. [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)
241 | 2. [Implement Stacks using Queue](https://leetcode.com/problems/implement-stack-using-queues/)
242 | 3. [Design Circular Queue](https://leetcode.com/problems/design-circular-queue/)
243 | 4. [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/)
244 | 5. [Design Circular Deque](https://leetcode.com/problems/design-circular-deque/)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Data Structure & Algorithms In JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ## Features
10 |
11 | 📚 Comprehensive Content Series
12 |
13 | 🎯 Perfect for Frontend Devs
14 |
15 | 🌟 17 Essential Topics
16 |
17 | 🚀 100+ Practice Questions
18 |
19 | 💬 Live Doubts Sessions
20 |
21 | > Fill this [form](https://forms.gle/LgebEgJmbfZeuNfN9) to enter in the whatsApp community, where you can ask your doubts related to DSA.
22 |
23 | ## Curriculum
24 |
25 | - [Loops in JavaScript](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Basics/README.md)
26 | - [Time Complexity: Big O notation](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Time%20Complexity/README.md)
27 | - [Array](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Array/README.md)
28 | - [Polyfill of Map, Filter & Reduce](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Array/Polyfill.md)
29 | - [String](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/String/README.md)
30 | - [Recursion](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Recursion/README.md)
31 | - [Linear & Binary Search](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Searching%20Algorthims/README.md)
32 | - [Objects](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Objects/README.md)
33 | - [Sorting](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Sorting/README.md)
34 | - [Set & Map](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Set%20%26%20Map/README.md)
35 | - [Linked List](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Linked%20List/README.md)
36 | - [Stack](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Stack/README.md)
37 | - [Queue](https://github.com/Vishal-raj-1/DSA-In-JS-With-Vishal/blob/main/Queue/README.md)
38 |
39 | ## Upcoming Topics
40 |
41 | - Binary Tree
42 | - Binary Search Tree
43 | - Graph
44 | - Dynamic Programming
45 | - Miscellaneous
46 |
47 |
--------------------------------------------------------------------------------
/Recursion/README.md:
--------------------------------------------------------------------------------
1 | # Recursion in JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ### Factorial of a Number
10 |
11 | ```javascript
12 | function factorial(n){
13 | if(n === 0)
14 | return 1;
15 | return n * factorial(n - 1);
16 | }
17 |
18 | console.log(factorial(8));
19 | ```
20 |
21 | ### Sum of Array
22 |
23 | ```javascript
24 | function sumOfArrays(arr, n){
25 | if(n === 0){
26 | return 0;
27 | }
28 |
29 | return arr[n - 1] + sumOfArrays(arr, n - 1);
30 | }
31 |
32 | console.log(sumOfArrays([1, 2, 3, 4, 5], 5));
33 | ```
34 |
35 | ### Fibonacci Number
36 |
37 | ```javascript
38 | function fibo(n){
39 | if(n < 2){
40 | return n;
41 | }
42 | return fibo(n - 1) + fibo(n - 2);
43 | }
44 |
45 | console.log(fibo(5));
46 | ```
47 |
48 | ## Practice Questions (solve using recursion):
49 |
50 | - Check whether a string is palindrome or not
51 | - Create pow(x, n) function which returns x^n
52 | - Create a function which returns the sum of digits of a number (e.g., sumOfDigits(453) is 12)
53 | - Create a function which returns the number of digits in a number (e.g., countDigits(453) is 3)
54 | - Create a function to find the LCM of two numbers
55 | - Create a function to find the GCD of two numbers
56 | - Create a function to reverse a string
57 |
--------------------------------------------------------------------------------
/Searching Algorthims/README.md:
--------------------------------------------------------------------------------
1 | # Searching in JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ### Linear Search in JavaScript
10 |
11 | ```javascript
12 | const arr = [1, 2, 6, 9, 0, -5];
13 |
14 | const linearSearch = (arr, target) => {
15 | for (let i = 0; i < arr.length; i++) {
16 | if (arr[i] === target) {
17 | return i;
18 | }
19 | }
20 | return -1;
21 | }
22 |
23 | console.log(linearSearch(arr, 8));
24 | console.log(arr.includes(9));
25 | console.log(arr.indexOf(9));
26 | console.log(arr.find((num) => num > 0));
27 | console.log(arr.findIndex((num) => num < 0));
28 | ```
29 |
30 | ### Binary Search In JavaScript
31 |
32 | ```javascript
33 | const BinarySearch = (arr, target) => {
34 | let start = 0, end = arr.length - 1;
35 | while (start <= end) {
36 | let mid = Math.floor((start + end) / 2);
37 |
38 | if (arr[mid] === target) {
39 | return mid;
40 | }
41 |
42 | else if (arr[mid] > target) {
43 | end = mid - 1;
44 | }
45 |
46 | else {
47 | start = mid + 1;
48 | }
49 | }
50 |
51 | return -1;
52 | }
53 |
54 | console.log(BinarySearch([1, 4, 6, 9, 12, 15], 8));
55 | ```
56 |
57 | ### Binary Search using Recursion
58 |
59 | ```javascript
60 | const BinarySearchRecur = (arr, target) => {
61 | return BinarySearchUtil(arr, target, 0, arr.length);
62 | }
63 |
64 | const BinarySearchUtil = (arr, target, start, end) => {
65 | if (start > end)
66 | return -1;
67 |
68 | let mid = Math.floor((start + end) / 2);
69 |
70 | if (arr[mid] === target) {
71 | return mid;
72 | }
73 |
74 | else if (arr[mid] > target) {
75 | return BinarySearchUtil(arr, target, start, mid - 1);
76 | }
77 |
78 | else {
79 | return BinarySearchUtil(arr, target, mid + 1, end);
80 | }
81 | }
82 | ```
83 |
84 | ### Find floor and ceil value of X in an array
85 |
86 | ```javascript
87 | const floorCeil = (arr, target) => {
88 | let start = 0, end = arr.length;
89 | let floor = -1, ceil = -1;
90 | while(start <= end){
91 | let mid = Math.floor((start + end)/2);
92 |
93 | if(arr[mid] === target){
94 | floor = mid;
95 | ceil = mid;
96 | return [ceil, mid]
97 | }
98 |
99 | else if(arr[mid] > target){
100 | ceil = mid;
101 | end = mid - 1;
102 | }
103 |
104 | else {
105 | floor = mid;
106 | start = mid + 1;
107 | }
108 | }
109 |
110 | return [ceil, floor]
111 | }
112 | ```
113 |
114 | ## Practice Questions
115 |
116 | ### Level 1
117 | - [Sqrt(x)](https://leetcode.com/problems/sqrtx/)
118 | - [First Bad Version](https://leetcode.com/problems/first-bad-version)
119 | - [Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/)
120 | - [Binary Search](https://leetcode.com/problems/binary-search)
121 | - [Search Insert Position](https://leetcode.com/problems/search-insert-position)
122 | - [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array)
123 |
124 | ### Level 2
125 | - [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array)
126 | - [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/)
127 | - [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)
128 | - [Find Peak Element](https://leetcode.com/problems/find-peak-element)
129 | - [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array)
130 |
--------------------------------------------------------------------------------
/Set & Map/README.md:
--------------------------------------------------------------------------------
1 | # Map, WeakMap, Set, WeakSet in JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ## Set in JavaScript:
10 |
11 | ```javascript
12 | // Creating a Set
13 | const mySet = new Set();
14 |
15 | // Adding values to the Set
16 | mySet.add(1);
17 | mySet.add("hello");
18 | mySet.add(true);
19 |
20 | // Checking if a value exists
21 | console.log(mySet.has(1)); // true
22 |
23 | // Removing a value
24 | mySet.delete("hello");
25 |
26 | // Iterating through the Set
27 | for (const value of mySet) {
28 | console.log(value);
29 | }
30 |
31 | // Size of the Set
32 | console.log(mySet.size); // 2
33 |
34 | // Clearing the Set
35 | mySet.clear();
36 | ```
37 |
38 | ## Map in JavaScript
39 |
40 | ```javascript
41 | // Creating a Map
42 | const myMap = new Map();
43 |
44 | // Adding key-value pairs to the Map
45 | myMap.set("name", "Vishal");
46 | myMap.set("age", 21);
47 |
48 | // Getting a value using a key
49 | console.log(myMap.get("name")); // Vishal
50 |
51 | // Checking if a key exists
52 | console.log(myMap.has("age")); // true
53 |
54 | // Removing a key-value pair
55 | myMap.delete("age");
56 |
57 | // Iterating through the Map
58 | for (const [key, value] of myMap) {
59 | console.log(key, value);
60 | }
61 |
62 | // Size of the Map
63 | console.log(myMap.size); // 1
64 |
65 | // Clearing the Map
66 | myMap.clear();
67 | ```
68 |
69 | ## Weak Map in JavaScript
70 |
71 | ```javascript
72 | let obj = { key: 'value' };
73 |
74 | // Creating a WeakMap
75 | let weakMap = new WeakMap();
76 | weakMap.set(obj, 'metadata');
77 |
78 | // Checking if the object still exists in the WeakMap
79 | console.log(weakMap.has(obj)); // true
80 |
81 | // Removing the strong reference to the object
82 | obj = null;
83 |
84 | // At this point, the object is no longer strongly referenced
85 | // The WeakMap's weak reference will allow the object to be garbage collected
86 | console.log(weakMap.has(obj)); // false
87 | ```
88 |
89 | ## Practice Questions:
90 |
91 | 1. [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
92 | 2. [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) (LeetCode 349)
93 | 3. [Distribute Candies](https://leetcode.com/problems/distribute-candies/)
94 | 4. [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) (LeetCode 128)
95 | 5. [Happy Number](https://leetcode.com/problems/happy-number/)
96 | 6. [First Unique Character In A String](https://leetcode.com/problems/first-unique-character-in-a-string/)
97 | 7. [Find Common Characters](https://leetcode.com/problems/find-common-characters/)
98 | 8. [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/)
99 | 9. [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/)
100 | 10. [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)
101 | 11. [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
--------------------------------------------------------------------------------
/Sorting/README.md:
--------------------------------------------------------------------------------
1 | # Sorting In JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | ### Sort an Array
16 | ```javascript
17 | const arr = [-2, -7, 1000, 5]
18 | console.log(arr.sort()) // -2, -7, 1000, 5
19 | console.log(arr.sort((a, b) => a - b)) // -7, -2 , 5, 1000
20 | console.log(arr.sort((a, b) => b - a)) // 1000, 5, -2, -7
21 |
22 | const strArr = ["mango", "apple", "banana"]
23 | console.log(strArr.sort()) // "apple", "banana", "mango"
24 | ```
25 |
26 | ### Sort a String
27 | ```javascript
28 | const str = "Vishal"
29 | console.log(str.split("").sort().join("")) // "Vahils
30 | ```
31 |
32 | ### Bubble Sort In JavaScript
33 | ```javascript
34 | const bubbleSort = (arr) => {
35 | let swapped;
36 | do {
37 | swapped = false;
38 | for (let i = 0; i < arr.length - 1; i++) {
39 | if (arr[i] > arr[i + 1]) {
40 | [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
41 | swapped = true;
42 | }
43 | }
44 | } while (swapped)
45 | return arr;
46 | }
47 |
48 | console.log(bubbleSort(arr)) // -7, -2 , 5, 1000
49 | ```
50 |
51 | ### Selection Sort in JavaScript
52 | ```javascript
53 | const selectionSort = (arr) => {
54 | for (let i = 0; i < arr.length - 1; i++) {
55 | let minIndex = i;
56 | for (let j = i + 1; j < arr.length; j++) {
57 | if (arr[j] < arr[minIndex]) {
58 | minIndex = j;
59 | }
60 | }
61 | [arr[minIndex], arr[i]] = [arr[i], arr[minIndex]]
62 | }
63 | return arr;
64 | }
65 |
66 | console.log(selectionSort(arr)) // -7, -2 , 5, 1000
67 | ```
68 |
69 | ### Insertion Sort In JavaScript
70 | ```javascript
71 | const insertionSort = (arr) => {
72 | for(let i=1; i= 0 && arr[j] > current){
76 | arr[j+1] = arr[j];
77 | j--;
78 | }
79 | arr[j+1] = current;
80 | }
81 | return arr;
82 | }
83 |
84 | console.log(insertionSort(arr)) // -7, -2 , 5, 1000
85 | ```
86 |
87 | ### Merge Sort in JavaScript
88 | ```javascript
89 | const mergeSort = (arr) => {
90 | if (arr.length < 2) {
91 | return arr;
92 | }
93 | let mid = Math.floor(arr.length / 2);
94 | let left = mergeSort(arr.slice(0, mid))
95 | let right = mergeSort(arr.slice(mid))
96 | return merge(left, right)
97 | }
98 |
99 | const merge = (left, right) => {
100 | const result = []
101 | let leftIndex = 0, rightIndex = 0;
102 | while (leftIndex < left.length && rightIndex < right.length) {
103 | if (left[leftIndex] < right[rightIndex]) {
104 | result.push(left[leftIndex])
105 | leftIndex++;
106 | }
107 | else {
108 | result.push(right[rightIndex])
109 | rightIndex++;
110 | }
111 | }
112 |
113 | while (leftIndex < left.length) {
114 | result.push(left[leftIndex])
115 | leftIndex++;
116 | }
117 |
118 | while (rightIndex < right.length) {
119 | result.push(right[rightIndex])
120 | rightIndex++;
121 | }
122 |
123 | return result;
124 | }
125 |
126 | const arr1 = [29, 10, 8, 16, 37, 14, 4, 45]
127 | console.log(mergeSort(arr1))
128 | ```
129 | ### Merge Sort in JavaScript (Space Optimised)
130 |
131 | ```javascript
132 | const mergeSortInplace = (arr, low, high) => {
133 | if (low < high) {
134 | let mid = Math.floor((low + high) / 2);
135 | mergeSortInplace(arr, low, mid)
136 | mergeSortInplace(arr, mid + 1, high)
137 | mergeInplace(arr, low, mid, high)
138 | }
139 | }
140 |
141 | const mergeInplace = (arr, low, mid, high) => {
142 | const result = []
143 | let leftIndex = low, rightIndex = mid + 1;
144 | while (leftIndex <= mid && rightIndex <= high) {
145 | if (arr[leftIndex] < arr[rightIndex]) {
146 | result.push(arr[leftIndex])
147 | leftIndex++;
148 | }
149 | else {
150 | result.push(arr[rightIndex])
151 | rightIndex++;
152 | }
153 | }
154 |
155 | while (leftIndex <= mid) {
156 | result.push(arr[leftIndex])
157 | leftIndex++;
158 | }
159 |
160 | while (rightIndex <= high) {
161 | result.push(arr[rightIndex])
162 | rightIndex++;
163 | }
164 |
165 | for (let i = low; i <= high; i++) {
166 | arr[i] = result[i - low];
167 | }
168 | }
169 |
170 | const arr1 = [29, 10, 8, 16, 37, 14, 4, 45]
171 | console.log(mergeSortInplace(arr1, 0, arr.length - 1))
172 | console.log(arr1)
173 | ```
174 |
175 | ### Quick Sort in JavaScript
176 |
177 | ```javascript
178 | const quickSort = (arr) => {
179 | if(arr.length < 2){
180 | return arr;
181 | }
182 | let pivotIndex = Math.floor(Math.random() * arr.length);
183 | let left = [], right = [];
184 | for(let i=0; i
4 |
5 |
6 |
7 |
8 |
9 | ## Stack Implementation Using Array
10 | ```javascript
11 | class Stack{
12 | constructor(){
13 | this.stack = []
14 | }
15 |
16 | push(item){
17 | this.stack.push(item)
18 | }
19 |
20 | pop(){
21 | if(this.isEmpty()){
22 | return null;
23 | }
24 | return this.stack.pop()
25 | }
26 |
27 | peek(){
28 | if(this.isEmpty()){
29 | return null;
30 | }
31 | return this.stack[this.stack.length - 1]
32 | }
33 |
34 | isEmpty(){
35 | return this.stack.length === 0
36 | }
37 |
38 | size(){
39 | return this.stack.length;
40 | }
41 | }
42 |
43 | const stack = new Stack()
44 | stack.push(10)
45 | stack.push(12)
46 | stack.push(13)
47 | stack.push(15)
48 | stack.push(17)
49 | stack.pop()
50 | console.log(stack.peek())
51 | console.log(stack)
52 | ```
53 |
54 | ## Stack Implementation Using Linked List
55 |
56 | ```javascript
57 | class Node {
58 | constructor(data) {
59 | this.data = data;
60 | this.next = null;
61 | }
62 | }
63 |
64 | class StackLinkedList {
65 | constructor() {
66 | this.top = null;
67 | this.size = 0;
68 | }
69 |
70 | push(data) {
71 | const newNode = new Node(data);
72 | newNode.next = this.top;
73 | this.top = newNode;
74 | this.size++;
75 | }
76 |
77 | pop() {
78 | if (this.isEmpty()) {
79 | return "List is already empty"
80 | }
81 | const item = this.top.data;
82 | this.top = this.top.next;
83 | this.size--;
84 | return item;
85 | }
86 |
87 | peek(){
88 | return this.top.data;
89 | }
90 |
91 | isEmpty() {
92 | return this.size === 0;
93 | }
94 | }
95 |
96 | const stack1 = new StackLinkedList()
97 | stack1.push(10)
98 | stack1.push(12)
99 | stack1.push(14)
100 | console.log(stack1.pop())
101 | console.log(stack1.peek())
102 | console.log(stack1)
103 | ```
104 |
105 | ## Practice Questions
106 |
107 | 1. [Remove All Adjacent Duplicate in String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/)
108 | 2. [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)
109 | 3. [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/)
110 | 4. [Next Greater Element 1](https://leetcode.com/problems/next-greater-element-i/)
111 | 5. [Online Stock Span](https://leetcode.com/problems/online-stock-span/)
112 | 6. [Next Greater Element 2](https://leetcode.com/problems/next-greater-element-ii/)
113 | 7. [Remove K Digits](https://leetcode.com/problems/remove-k-digits/)
114 | 8. [Sum of Subarray Minimums](https://leetcode.com/problems/sum-of-subarray-minimums/)
115 |
116 | **Note**: You can find solutions of all these problems in [this playlist](https://www.youtube.com/playlist?list=PLSH9gf0XETotSpywVcJGIYODBNL_j0P0u)
117 |
118 | Before checking the solutions, challenge yourself to solve the problems on your own. If you're stuck, watch the solution video up to the intuition part. Then, code it yourself before watching the complete solution.
119 |
120 | This approach builds solid problem-solving skills.
--------------------------------------------------------------------------------
/String/README.md:
--------------------------------------------------------------------------------
1 | # String In JavaScript
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ### Length of a String
10 | ```javascript
11 | let firstName = "Vaishali";
12 | console.log(firstName.length);
13 | ```
14 |
15 | ### Access String Element
16 | ```javascript
17 | console.log(firstName.charAt(2)); // i
18 | console.log(firstName[2]); // i
19 | console.log(firstName.charCodeAt(2)); // 115 (Ascii Code)
20 | ```
21 |
22 | ### Check Presence of Character
23 | ```javascript
24 | console.log(firstName.includes("r")); // false (& if present it return true)
25 | console.log(firstName.indexOf("i")); // 2 (& if not present it return -1)
26 | console.log(firstName.lastIndexOf("i")); // 7
27 | ```
28 |
29 | ### Compare Two Strings
30 | ```javascript
31 | let anotherName = "Vishal";
32 | console.log(firstName.localeCompare(anotherName)); // -1 (& if strings are equal it return 0)
33 | ```
34 |
35 | ### Replace Substring
36 | ```javascript
37 | const str = "Vishal is Best Frontend Developer. Vishal is Best Developer. ";
38 | console.log(str.replace("Vishal", "Sujit")); // "Sujit is Best Frontend Developer. Vishal is Best Developer. "
39 | console.log(str.replaceAll("Vishal", "Sujit")); // "Sujit is Best Frontend Developer. Sujit is Best Developer. "
40 | ```
41 |
42 | ### Substring of a String
43 | ```javascript
44 | console.log(str.substring(6, 30));
45 | console.log(str.slice(-10, -1));
46 | ```
47 |
48 | ### Split and Join
49 | ```javascript
50 | console.log(str.split(""));
51 | const subString = str.split(" ");
52 | console.log(subString.join(" "));
53 | ```
54 |
55 | ### String Start and End
56 | ```javascript
57 | console.log(str.startsWith("Vishal")); // true
58 | console.log(str.endsWith("Developer")); // true
59 | ```
60 |
61 | ### Trim and Case Conversion
62 | ```javascript
63 | const trimStr = str.trim();
64 | const trimStrStart = str.trimStart();
65 | const trimStrEnd = str.trimEnd();
66 | console.log(trimStr, trimStr.length);
67 | console.log(str.toLowerCase());
68 | console.log(str.toUpperCase());
69 | ```
70 |
71 | ### Convert Number and Object to String
72 | ```javascript
73 | const num = 123;
74 | console.log(num, num.toString());
75 |
76 | const obj = {
77 | name: "Vishal",
78 | course: "DSA with Vishal"
79 | };
80 | console.log(obj, JSON.stringify(obj));
81 | ```
82 |
83 | ### Concatenate Strings
84 | ```javascript
85 | const lastName = "Rajput";
86 | console.log(firstName + lastName);
87 | console.log(`${firstName} ${lastName} is a Best Developer`);
88 | console.log(firstName.concat(lastName, " is a", " Best"));
89 | ```
90 |
91 | ## Practice Questions
92 |
93 | - [Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/)
94 | - [Reverse String](https://leetcode.com/problems/reverse-string)
95 | - [Valid Anagram](https://leetcode.com/problems/valid-anagram)
96 | - [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix)
97 | - [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately)
98 | - [Length of Last Word](https://leetcode.com/problems/length-of-last-word/)
99 | - [Valid Palindrome](https://leetcode.com/problems/valid-palindrome)
100 | - [String Compression](https://leetcode.com/problems/string-compression)
101 | - [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string)
102 | - [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string)
103 | - [Rotate String](https://leetcode.com/problems/rotate-string)
104 |
105 |
--------------------------------------------------------------------------------
/Time Complexity/README.md:
--------------------------------------------------------------------------------
1 | # Struggling with Time Complexity? Watch this
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | ## Practice Questions
10 |
11 | - Solve time complexity of all upcoming questions you solve in this series.
--------------------------------------------------------------------------------