Popular Algorithms in Javascript.

Just trying to learn some DSA to pass school exams and maybe interviews

Linear Search:

function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}

console.log(linearSearch([1, 2, 3, 4, 5], 3));  // 2
console.log(linearSearch([1, 2, 3, 4, 5], 6));  // -1

Binary Search:

function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  while (left <= right) {
    const 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([1, 2, 3, 4, 5], 3));  // 2
console.log(binarySearch([1, 2, 3, 4, 5], 6));  // -1

Bubble Sort:

function bubbleSort(arr) {
  let swapped;
  do {
    swapped = false;
    for (let i = 0; i < arr.length - 1; i++) {
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        swapped = true;
      }
    }
  } while (swapped);
  return arr;
}

console.log(bubbleSort([5, 2, 1, 4, 3]));  // [1, 2, 3, 4, 5]

Merge Sort:

function mergeSort(arr) {
  if (arr.length <= 1) return arr;
  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));
  return merge(left, right);
}

function merge(left, right) {
  const result = [];
  while (left.length > 0 && right.length > 0) {
    if (left[0] < right[0]) {
      result.push(left.shift());
    } else {
      result.push(right.shift());
    }
  }
  return result.concat(left, right);
}

console.log(mergeSort([5, 2, 1, 4, 3]));  // [1, 2, 3, 4, 5]

Breath first search (BFS):

class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function breadthFirstSearch(root, target) {
  const queue = [root];
  while (queue.length > 0) {
    const node = queue.shift();
    if (node.val === target) return true;
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  return false;
}

const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);

console.log(breadthFirstSearch(root, 4));  // true
console.log(breadthFirstSearch(root, 6));  // false

Depth first search :

function depthFirstSearch(node, target) {
  if (!node) return false;
  if (node.val === target) return true;
  return depthFirstSearch(node.left, target) || depthFirstSearch(node.right, target);
}

console.log(depthFirstSearch(root, 4));  // true
console.log(depthFirstSearch(root, 6));  // false
  1. Find the minimum element in a rotated sorted array:

     function findMin(nums) {
       let left = 0;
       let right = nums.length - 1;
       while (left < right) {
         const mid = Math.floor((left + right) / 2);
         if (nums[mid] > nums[right]) {
           left = mid + 1;
         } else {
           right = mid;
         }
       }
       return nums[left];
     }
    
     console.log(findMin([3, 4, 5, 1, 2]));  // 1
     console.log(findMin([4, 5, 6, 7, 0, 1, 2]));  // 0
    
    1. Implement a trie (prefix tree):

       class TrieNode {
         constructor() {
           this.children = new Map();
           this.isEnd = false;
         }
       }
      
       class Trie {
         constructor() {
           this.root = new TrieNode();
         }
      
         insert(word) {
           let current = this.root;
           for (const c of word) {
             if (!current.children.has(c)) {
               current.children.set(c, new TrieNode());
             }
             current = current.children.get(c);
           }
           current.isEnd = true;
         }
      
         search(word) {
           let current = this.root;
           for (const c of word) {
             if (!current.children.has(c)) return false;
             current = current.children.get(c);
           }
           return current.isEnd;
         }
      
         startsWith(prefix) {
           let current = this.root;
           for (const c of prefix) {
             if (!current.children.has(c)) return false;
             current = current.children.get(c);
           }
           return true;
         }
       }
      
       const trie = new Trie();
       trie.insert('apple');
       trie.insert('app');
       console.log(trie.search('apple'));  // true
       console.log(trie.search('app'));  // true
       console.log(trie.startsWith('ap'));  // true
       console.log(trie.startsWith('ba'));  // false
      
      1. Find the kth largest element in an unsorted array:

         function findKthLargest(nums, k) {
           return nums.sort((a, b) => b - a)[k - 1];
         }
        
         console.log(findKthLargest([3, 2, 1, 5, 6, 4], 2));  // 5
         console.log(findKthLargest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4));  // 4
        
        1. Check if a string is a palindrome:

           function isPalindrome(s) {
             s = s.toLowerCase().replace(/[^a-z0-9]/g, '');
             return s === s.split('').reverse().join('');
           }
          
           console.log(isPalindrome('racecar'));  // true
           console.log(isPalindrome('hello'));  // false
           console.log(isPalindrome('A man, a plan, a canal: Panama'));  // true
          
          1. Implement an LRU cache:

             class LRUCache {
               constructor(capacity) {
                 this.capacity = capacity;
                 this.cache = new Map();
               }
            
               get(key) {
                 if (!this.cache.has(key)) return -1;
                 const value = this.cache.get(key);
                 this.cache.delete(key);
                 this.cache.set(key, value);
                 return value;
               }
            
               put(key, value) {
                 if (this.cache.has(key)) this.cache.delete(key);
                 this.cache.set(key, value);
                 if (this.cache.size > this.capacity) {
                   this.cache.delete(this.cache.keys().next().value);
                 }
               }
             }
            
             const cache = new LRUCache(2);
             cache.put(1, 1);
             cache.put(2, 2);
             console.log(cache.get(1));  // 1
             cache.put(3, 3);
             console.log(cache.get(2));  // -1
             cache.put(4, 4);
             console.log(cache.get(1));  // -1
             console.log(cache.get(3));  // 3
             console.log(cache.get(4));  // 4
            
            1. Given a list of words, return the words that are exactly five letters long and start and end with the same letter:

               function specialWords(words) {
                 return words.filter(word => word.length === 5 && word[0] === word[4]);
               }
              
               console.log(specialWords(['hello', 'world', 'whole', 'apple', 'echo']));  // ['whole', 'echo']