DSA (Udemy Colt)
DSA (Udemy Colt)
Binary_Heap
class MaxBinaryHeap {
constructor() {
insert(element) {
this.values.push(element);
this.bubbleUp();
bubbleUp(){
this.values[parentIdx] = element;
this.values[idx] = parent;
idx = parentIdx;
}
extractMax(){
this.values[0] = end;
this.sinkDown();
return max;
sinkDown(){
let idx = 0;
while(true){
let rightchild,leftchild;
leftchild = this.values[leftChildIdx];
swap = leftChildIdx;
}
}
rightchild = this.values[rightChildIdx];
if(
swap = rightChildIdx;
this.values[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
heap.insert(55);
2. Binary_Search_Tree
class Node{
constructor(val){
this.value = val;
this.left = null;
this.right = null;
}
class BinarySearchTree{
constructor(){
this.root = null;
this.size = 0;
insert(value){
if(!this.root) {
this.root = newNode;
this.size++;
return this;
} else {
while(true){
current.left = newNode;
this.size++;
return this;
} else{
current = current.left;
}
} else if(value > current.value){
current.right = newNode;
this.size++;
return this;
} else{
current = current.right;
search(target){
current = current.left;
current = current.right;
} else{
found = true;
return found;
}
// breadth first search
BFS(){
queue = [],
node = this.root;
queue.push(node);
while(queue.length){
node = queue.shift();
data.push(node.value);
if(node.left){
queue.push(node.left);
if(node.right){
queue.push(node.right);
console.log(data);
DFSpreOrder(){
node = this.root;
function preOrder(node){
if(node === null) return; // Base case: if the node is null, return
data.push(node.value); // Visit the node (push its value to the result array)
preOrder(node.left);
preOrder(node.right);
DFSpostOrder(){
node = this.root;
function postOrder(node){
postOrder(node.left);
postOrder(node.right);
data.push(node.value); // Visit the node (push its value to the result array)
postOrder(node);
return data;
DFSinOrder(){
node = this.root;
function inOrder(node){
inOrder(node.left);
data.push(node.value); // Visit the node (push its value to the result array)
inOrder(node.right);
inOrder(node);
return data;
tree.insert(6);
tree.insert(15);
tree.insert(3);
tree.insert(8);
tree.insert(20);
tree.insert(14);
3. Bubble_Sort
function bubbleSort(arr) {
noSwaps = true;
for(let j = 0; j < i - 1; j++){ // the i-1 is the comparisons.so as i goes down so does j.
console.log(arr,`${arr[j]},${arr[j+1]} Swap`)
// SWAP method!!
// arr[j + 1] = temp;
swap(arr, j, j + 1);
noSwaps = false;
}
}
if(noSwaps){
console.log("noSwaps")
break;
return arr;
// bubbleSort([7,3,5,9,2,88,-5,22,532,543,12,53,16]);
bubbleSort([9,2,3,4,5,6,7,8])
4. Dijkstra’s
class priorityQ{
constructor(){
this.values = [];
enqueue(value,priority){
this.values.push({value,priority});
this.sort()
dequeue(){
return this.values.shift();
}
sort(){
class weightedGraph{
constructor(){
this.adjacencyList = {};
addVertex(vertex){
addEdge(v1,v2,weight){
if(this.adjacencyList[v1]) this.adjacencyList[v1].push({node:v2,weight})
if(this.adjacencyList[v2]) this.adjacencyList[v2].push({node:v1,weight})
showGraph(){
.join(", ")
}
Dijkstras(start,end){
let smallest,nextNode;
distances[vertex] = 0;
queue.enqueue(vertex,0)
} else{
distances[vertex] = Infinity;
queue.enqueue(vertex,Infinity)
} //console.log(queue,distances,previous)
while(queue.values.length){
smallest = queue.dequeue().value;
// console.log(smallest)
console.log(distances)
console.log(previous)
while(previous[smallest]){
path.push(smallest);
smallest = previous[smallest]
break;
nextNode = this.adjacencyList[smallest][neighbor]
// console.log(this.adjacencyList[smallest][neighbor]);
distances[nextNode.node] = candidate;
previous[nextNode.node] = smallest;
queue.enqueue(nextNode.node, candidate)
// path.push(start);
// path.reverse();
return path.concat(start).reverse();
}
graph.addVertex("A")
graph.addVertex("B")
graph.addVertex("C")
graph.addVertex("D")
graph.addVertex("E")
graph.addVertex("F")
graph.addEdge("A","B",4)
graph.addEdge("A","C",2)
graph.addEdge("B","E",3)
graph.addEdge("C","D",2)
graph.addEdge("C","F",4)
graph.addEdge("D","E",3)
graph.addEdge("D","F",1)
graph.addEdge("E","F",1)
graph.showGraph()
graph.Dijkstras("A","E")
5. Doubly_Linked_List
// Node
// -val
// -next
// -prev
class Node{
constructor(value){
this.value = value;
this.next = null;
this.previous = null;
// DoublyLinkedList
// -head
// -tail
// -length
class DoublyLinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
push(value){
if(!this.head){
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.previous = this.tail;
this.tail = newNode
this.length++;
return this;
pop(){
this.head = null;
this.tail = null;
} else{
this.length--;
return poppedNode;
unshift(val){
if(!this.head){
this.head = newNode;
this.tail = newNode;
} else{
newNode.next = this.head;
this.head.previous = newNode;
this.head = newNode;
this.length++;
return this;
shift(){
this.head = null;
this.tail = null;
} else {
this.length--;
return poppedNode;
}
get(index){
var current;
var counter;
current = this.head;
counter = 0;
current = current.next;
counter++;
} else {
current = this.tail;
counter = this.length - 1;
current = current.previous;
counter--;
return current;
set(index,val){
foundNode.value = val;
return true;
return false;
insert(index,val){
if (index < 0 || index > this.length) return false; // Allow insert at this.length
this.length++;
return true;
remove(index){
previousNode.next = nextNode;
nextNode.previous = previousNode;
// removedNode.next.previous = removedNode.previous
removedNode.previous = null;
removedNode.next = null;
this.length--;
clearAll(){
this.head = null;
this.tail = null;
this.length = 0;
return this;
show(){
var array = [];
while(current){
array.push(current.value);
current = current.next;
console.log(array);
list.push(65);
list.push(75);
list.push(85);
// list.push(95);
// list.push(100);
// list.push(110);
6. DFS&BFS(Graph_Using_List)
// undirected graph
class Graph{
constructor(){
this.adjacencyList = {};
addVertex(vertex){
if(!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
addEdge(v1,v2){
if(this.adjacencyList[v1]) this.adjacencyList[v1].push(v2);
if(this.adjacencyList[v2]) this.adjacencyList[v2].push(v1);
removeVertex(vertex){
if(this.adjacencyList[vertex]){
this.removeEdge(vertex, adjacentVertex);
delete this.adjacencyList[vertex];
removeEdge(v1,v2){
if(this.adjacencyList[v1]){
this.adjacencyList[v1] = this.adjacencyList[v1].filter(
v => v !== v2
);
if(this.adjacencyList[v2]){
this.adjacencyList[v2] = this.adjacencyList[v2].filter(
v => v !== v1
);
}
}
DFSRecursive(vertex = "A"){
visited[v] = true;
// console.log(visited)
result.push(v);
this.adjacencyList[v].forEach(neighbour => {
if(!visited[neighbour]){
dfshelper(neighbour);
})
dfshelper(vertex);
return result;
DFSIterative(vertex = "A"){
var currVertex;
visited[vertex] = true;
while(stack.length){
console.log(stack)
currVertex = stack.pop();
result.push(currVertex);
this.adjacencyList[currVertex].forEach(neighbor =>{
if(!visited[neighbor]){
visited[neighbor] = true;
stack.push(neighbor);
});
return result;
BFS(vertex = "A"){
let currVertex;
visited[vertex] = true;
while(queue.length){
currVertex = queue.shift()
results.push(currVertex)
//since we are using a queue we can reverse the order by removing each element and reversing
it & it gives a different order after the vertex.
// ['A', 'B', 'C', 'D', 'F', 'E'] this is for a normal queue ['A', 'C', 'B', 'F', 'D', 'E'] this is for a reverse
queue.
this.adjacencyList[currVertex].slice().reverse().forEach(neighbor =>{
if(!visited[neighbor]){
visited[neighbor] = true;
queue.push(neighbor);
})
return results;
g.addVertex("A")
g.addVertex("B")
g.addVertex("C")
g.addVertex("D")
g.addVertex("E")
g.addVertex("F")
g.addEdge("A","B");
g.addEdge("A","C");
g.addEdge("B","D");
g.addEdge("B","F");
g.addEdge("D","F");
g.addEdge("D","C");
g.addEdge("F","E");
g.addEdge("F","C");
g.DFSRecursive();
7. Hash_Function
class Hashtable{
constructor(size = 53){
_hash(key) {
let total = 0;
// seperatte chaining
set(key,value){
this.keyMap[index] = [];
this.keyMap[index].push([key,value]);
get(key){
if(this.keyMap[index]){
return this.keyMap[index][i][1];
return undefined;
values(){
if(this.keyMap[i]){
if(!valuesArr.includes(this.keyMap[i][j][1]))
valuesArr.push(this.keyMap[i][j][1])
}
}
return valuesArr;
keys(){
if(this.keyMap[i]){
if(!keysArr.includes(this.keyMap[i][j][0]))
keysArr.push(this.keyMap[i][j][0])
return keysArr;
hash.set("Red", "#FF0000");
hash.set("Red", "#FF1111");
hash.set("Green", "#00FF00")
hash.set("Blue", "#0000FF")
hash.set("Yellow", "#FFFF00")
hash.set("Cyan", "#00FFFF")
hash.set("Magenta", "#FF00FF")
hash.set("Orange", "#FFA500")
hash.set("Purple", "#800080");
hash.set("Pur", "#800080");
hash.set("ple", "#800080");
8. Insertion_Sort
function insertionSort(arr) {
arr[j + 1] = arr[j];
arr[j + 1] = currentVal
console.log(arr)
return arr;
insertionSort([21,9,1,76,4])
// [2,1,9,76,4]
// j i
// c
9. Merge_Sort
function merge(arr1,arr2) {
let j = 0
results.push(arr1[i]);
i++;
} else {
results.push(arr2[j]);
j++
results.push(arr1[i])
i++
results.push(arr2[j])
j++
return results
//depends on the size of the n & m which can be arr1 and arr2.
// merge([1,10,50],[2,14,99,100])
// i j
// [1,10,50],[2,14,99,100]
function mergeSort(arr){
if(arr.length <= 1) return arr; //if the elements are divided into a single element in array
return merge(left,right)
mergeSort([2,53,235,532,21,53,27,53,86,24,77,91])
// and the merging of the elements is n where all the elements are
10. Min_Heap_PriorityQ
class Node{
constructor(val, priority){
this.value = val;
this.priority = priority;
class priorityQ {
constructor() {
this.values = [];
enqueue(val, priority) {
this.values.push(newNode);
this.bubbleUp();
bubbleUp(){
this.values[parentIdx] = element;
this.values[idx] = parent;
// Update idx to parent index
idx = parentIdx;
dequeue(){
this.values[0] = end;
this.sinkDown();
return min;
sinkDown(){
let idx = 0;
while(true){
let rightchild,leftchild;
leftchild = this.values[leftChildIdx];
if(leftchild.priority < element.priority){
swap = leftChildIdx;
rightchild = this.values[rightChildIdx];
if(
swap = rightChildIdx;
this.values[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
er.enqueue("commom cold",5);
er.enqueue("high fever",4);
er.enqueue("gunshot",1);
er.enqueue("broken arm",2);
er.enqueue("allergic reaction",3);
11. Queue_SLL
class Node{
constructor(val){
this.value = val;
this.next = null;
class Queue {
constructor(){
this.first = null;
this.last = null;
this.size = 0;
if(!this.first){
this.first = newNode;
this.last = newNode;
}else{
current.next = newNode;
this.last = newNode;
}
return ++this.size;
dequeue(){
this.first = null;
this.last = null;
}else{
this.first = removedNode.next;
removedNode.next = null;
this.size--;
return removedNode.value;
show(){
while(current){
values.push(current.value)
current = current.next;
} console.log(values);
12. Quick_Sort
console.log(arr)
swapIdx++;
swap(arr,swapIdx,i);
console.log(arr,"swapped")
swap(arr,start,swapIdx);
return swapIdx;
// this function returns a index which the element is supposed to be in the right place.
// pivot([4,8,2,1,5,7,6,3])
// left
// right
return arr;
// for best and avg the time complexity is O(n log n) where the dividing the left and right of the
// pivot is based on the n and it divides upto (log n) and the comparison of the pivot is done to all the
// for worst case if the pivot is the first or the last element and for a sorted array we have n
decomposition
function swap(array, i, j) {
array[i] = array[j];
array[j] = temp;
if((first > mid && first < last) || (first < mid && first > last)){
piovtIdx = start;
} else if((mid > first && mid > last) || (mid < start && mid > last)){
pivotIdx = middle;
} else {
pivotIdx = end;
// Swap the median element to the start (so the pivot is at start)
swap(arr,start,piovtIdx);
swapIdx++;
swap(arr,swapIdx,i);
}
swap(arr,start,swapIdx);
return swapIdx
quickSort(arr);
// 0.00020000000298023223 seconds where median is selected and put to start as pivot function:
(medianPivot)
13. Radix_Sort
// helper1
function getDigit(num,i){
// getDigit(4,0)
// Math.abs(-21434)
// 21434
// 21434 / 10000
// 2.1434
// 2.1434 % 10
// 2.1434
// Math.floor(2.1434)
// 2
// Math.abs(-21434)
// 21434
// Math.pow(10, 7)
// 10000000
// 21434 / 10000000
// 0.0021434
// 0.002143 % 10
// 0.002143
// Math.floor(0.002143)
// 0
// helper2
function digitCount(number){
return Math.floor(Math.log10(Math.abs(number))) + 1;
// digitCount(9)
// Math.log10(238)
// 2.376576957056512
// Math.log10(2385)
// 3.3774883833761327
// Math.log10(23857)
// 4.3776158305597805
// Math.floor(4.3776158305597805)
// 4
// Math.floor(4.3776158305597805)+1
// 5
// Math.log10(99999) + 1
// 5.999995657033466
// helper 3
function max_digit_of_arr(arr){
let maxDigit = 0;
maxDigit = Math.max(maxDigit,digitCount(arr[i]));
return maxDigit;
function radixSort(arr){
console.log(digitBuckets)
// [].concat([[1],[2],[3]])
// [Array(1), Array(1), Array(1)] we dont want this all the 0 to 9 in seperate array
// [].concat(...[[1],[2],[3]]) we want them all combined in a single array, so we do the spread ...
operateor
// [1, 2, 3]
arr = [].concat(...digitBuckets);
console.log(arr)
return arr;
let arr = [4321, 984, 7865, 35, 6, 1523, 457, 3219, 678, 97996];
radixSort(arr);
14. Selection_Sort
function selectionSort(arr){
var lowest = i;
lowest = j;
}
console.log(arr[i],arr[lowest])
console.log("index",i,lowest,"swapping")
arr[i] = arr[lowest];
arr[lowest] = temp;
console.log(arr);
console.log("***********");
return arr;
selectionSort([0,2,34,22,10,19,17])
// [34,28,15,2,8,17,3,5]
// i j
// l
// we can also use the other swap swap(arr,i,lowest) const swap = (arr,idx1,idx2) =>
// in selection sort we only swap once through 1 iteration but in bubble sort we
// swap constantly if the number is greater then the number after it until the
// end gets the highest number.we swap only once in selection and get the smallest to first
15. Singly_Linked_List
// piece of data = val
class Node{
constructor(val){
this.val = val;
this.next = null;
class SinglyLinkedList {
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
this.head = newNode;
this.tail = newNode;
} else {
this.length++;
return this;
}
previousNode = currentNode;
currentNode = currentNode.next;
if(previousNode){
} else {
this.head = null;
this.tail = null;
this.length--;
this.length--;
if(!this.head){
this.tail = null;
return temp.val;
unshift(val){
if(!this.head) {
this.head = newNode;
this.tail = newNode;
} else{
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
get(index){
let counter = 0;
// }
current = current.next;
counter++;
return current;
set(index,val){
if(foundNode){
foundNode.val = val;
return true;
return false;
insert(index,val){
previous.next = newNode;
newNode.next = temp;
this.length++
return true;
remove(index){
previousNode.next = removedNode.next;
this.length--;
return removedNode.val;
reverse(){
this.tail = current;
var next;
next = current.next;
current.next = previous;
previous = current;
current = next;
return this;
find(value){
var position = 0;
while(current){
return position + 1;
position++;
return -1;
show(){
if(!this.head) return null;
while(current){
values.push(current.val)
current = current.next;
console.log(values);
// list.push(65)
// list.push(75)
// list.push(85)
// list.push(62)
// list.unshift(100)
16. Stack_Singly_Linked_List
class Node{
constructor(value){
this.value = value;
this.next = null;
class Stack_SinglyLinkedList{
constructor(){
this.first = null;
this.last = null;
this.size = 0;
push(val){
var current;
if(!this.first){
this.first = newNode;
this.last = newNode;
} else{
current = this.first;
newNode.next = current;
this.first = newNode;
this.size++;
return this.size;
pop(){
} else{
this.first = temp.next;
temp.next = null;
this.size--;
return temp.value;
17. Add
function addUpTo(n) {
let total = 0
total += i;
return total;
//which is O(1)
var t1 = performance.now();
addUpTo(1000000000);
var t2 = performance.now();
18. Alpha_Numeric
function charCount(str){
char = char.toLowerCase()
// if(obj[char]){
// obj[char] +=1;
// } else{
// obj[char] = 1;
return obj;
charCount("hello !!")
// charCount("kjhsdghg 942352&^*#$)(#$##")
//This method returns an integer between 0 and 65535, representing the UTF-16
function isAlphaNumeric(char){
//here checks if the char is not in the range of alphaNumeric if it isnt it is a different or other
characters
return false;
return true;
19. Binary_Search
let left = 0;
return mid;
else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
return -1;
binary_search([1, 2, 4, 5, 6, 12, 21, 28, 32, 37, 43, 44, 54, 120], 41)
20. Count_Unique_Values
function countUniqueValues(arr){
let i = 0;
i++;
arr[i] = arr[j];
console.log(arr)
return i+1
}
countUniqueValues([4,4,5,46,,76,57,5,46,34]);
21. Fibonacchi
function fib(n) {
memo[n] = res;
return res;
22. Find_Longest_Substring_Sliding_Window
//returns the length of the longest substring with all distinct characters.
// findLongestSubstring('') // 0
// findLongestSubstring('rithmschool') // 7
// findLongestSubstring('thisisawesome') // 6
// findLongestSubstring('thecatinthehat') // 7
// findLongestSubstring('bbbbbb') // 1
// findLongestSubstring('longestsubstring') // 8
// findLongestSubstring('thisishowwedoit') // 6
function findLongestSubstring(str) {
let maxLen = 0;
let left = 0;
while(charSet.has(str[right])){
charSet.delete(str[left])
left++;
charSet.add(str[right]);
// Update maxLength
return maxLen;
findLongestSubstring('thecatinthehat') // 7
// findLongestSubstring("bbbbbbbbc")
Java_Script_Sort
// A function that determines the order of the elements. The function is called with the
// following arguments:
// To memorize this, remember that (a, b) => a - b sorts numbers in ascending order.
function numberCompare(num1,num2){
// num1 - num2; output [2, 4, 10, 15] ascending negative value a should come before b.
// num2 - num1; output [15, 10, 4, 2] descending positive value a should come after b.
[4,2,15,10].sort(numberCompare)
function compareByLen(str1,str2) {
["steele","colt","keys","hypocrisy","DSA"].sort(compareByLen)
23. Max_SubArray_Sum
function maxSubarr_sum(arr,target) {
for(let i=0; i <= arr.length - target ; i++){ //if target is 3 8-3=5 it runs upto the index 5.
var temp = 0;
max = temp;
return max;
maxSubarr_sum([1,2,3,8,5,4,7,2],3)
//this is O(n^2)
//so we use sliding window which helps to optimize solutions that involve
//traversing or analyzing subarrays of a fixed or variable size
24. Max_SubArray_refactor_SlideWindow
function maxSubArr_sum_Slidewindow(arr,target) {
let maxSum = 0;
maxSum += arr[i]
maxSum = Math.max(tempSum,maxSum)
return maxSum
maxSubArr_sum_Slidewindow([2,6,9,3,1,8,5,6,3],3)
// arr([2,6,9,2,1,8,5,6,3],3)
//tempSum is 17 of 2,6,9 elements and now to remove the first element and add the next element
where it looks like 6,9,3 as tempSum
//after removing the previous first element next add the next element which the start of the i is arr[3]
//tempSum = 17 - arr[i - target] + arr[i] gives the next subarray sum compare the tempSumwith
another value maxSum
25. Min_SubArrayLen_refactor_SlideWindow
function minSubArrayLen(arr,target){
var left = 0;
var sum = 0;
sum +=arr[right];
minLen = Math.min(minLen,(right-left)+1);
sum -= arr[left];
left++;
//problem statement
// Write a function called minSubArrayLen which accepts two parameters - an array of positive
integers and a positive integer.
// This function should return the minimal length of a contiguous subarray of which the sum is greater
than or equal to the integer passed to the function. If there isn't one, return 0 instead.
// Examples:
// minSubArrayLen([1,4,16,22,5,7,8,9,10],39) // 3
// minSubArrayLen([1,4,16,22,5,7,8,9,10],55) // 5
// minSubArrayLen([1,4,16,22,5,7,8,9,10],95) // 0
26. Naive_Search
function naive_search(str,substr) {
let counter = 0;
// Check if the substring matches the main string starting at index 'i'
console.log(str[i+j], substr[j]);
match = false;
console.log("BREAK!!");
console.log(`found one`)
}
if(match) counter++;
return counter
naive_search("helloilo","mi");
//01234 i 3+1 j 1
//hello
// lo
27. 0&1_Partation
function partitionZeroAnd1(arr){
let left = 0;
//moves the left pointer to right ++ until 1 is found and stops there to make a swap with right
pointer
left++;
//moves the right pointer towards left -- until 0 is found and stops there to make a swap with left
pointer
return arr;
// array[1,0,1,0,1,0,0,1]
partitionZeroAnd1(arr);
28. Recursion_Helper_Method
function collectOddNum(arr) {
function helper(helperInp) {
if(helperInp.length===0){
return;
if(helperInp[0] % 2 !==0){
result.push(helperInp[0]);
helper(helperInp.slice(1))
}
helper(arr);
return result;
collectOddNum([423,42,12,243,24,5,52,22,1,5,3,4,5,6,]);
function oddRecursion(arr) {
if(arr[0] % 2 !==0){
newArr.push(arr[0]);
newArr = newArr.concat(oddRecursion(arr.slice(1)));
return newArr;
oddRecursion([3,2,5,1,5,3,6,7,3,9,0,543,7648,]);
29. Same_Frequency_Number
function same(arr1,arr2){
return false
frequencyCounter[num] = (frequencyCounter[num] || 0) + 1;
console.log(frequencyCounter);
console.log("checking in array1")
if(!frequencyCounter[squared]){
return false;
frequencyCounter[squared]--;
console.log(frequencyCounter)
return true
same([1,2,4,3],[9,16,4,1])
30. Same_Naive
//in this we use 2 for loops which run time will be O(n^2)
// }
// arr2Copy.splice(j, 1);
// found = true;
// }
// }
// if (!found) {
// return false;
// }
// }
// }
//this is also the same where 1 is for loop & the other is
return false;
console.log(arr2);
arr2.splice(correctIndex,1)
return true;
same([1,2,4,3],[9,16,4,1])
31. Sum_Zero_Naive
function sumZero(arr){
return [arr[i],arr[j]]
return false
console.log(sumZero([-5,-1,0,2,3,4,5]))
32. Sum_Zero_Refactor
function sumZero(arr) {
let left = 0;
//loop to continue checking until the left pointer crosses the right pointer
return [arr[left],arr[right]];
left++;
else{
right--;
return false;
console.log(sumZero([-5,-4,-1,0,2,3]))