From 9e66249aac05c63414ce3b16c1fc9f9a1a553f8c Mon Sep 17 00:00:00 2001 From: Matt Smith Date: Mon, 26 May 2025 09:04:07 -0400 Subject: [PATCH] Add grouping --- README.md | 258 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 168 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 6775816..e2548c9 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,48 @@ -# JavaScript Algorithms (Sorted by Popularity) +# JavaScript Algorithms (Grouped by Type) -This list showcases some of the most popular JavaScript algorithms, from simple string manipulations to classic recursive solutions and efficient searching techniques. Each snippet demonstrates a fundamental concept often encountered in coding interviews and real-world development. +This repository contains a curated list of JavaScript algorithms, organized by category. These range from simple string manipulation to advanced searching and sorting techniques — perfect for interviews and foundational learning. -> **Note:** Popularity is based on common interview topics, educational resources, and usage in developer communities. +> [!Note] +> Popularity is based on common interview topics, educational materials, and developer community usage. -## 1. Reverse a String +## Algorithms + +### String Manipulation + +- [Reverse a String](#reverse-a-string) +- [Palindrome Check](#palindrome-check) +- [Character Frequency Counter](#character-frequency-counter) +- [Anagram Check](#anagram-check) + +### Math & Number Theory + +- [Prime Number Check](#prime-number-check) +- [Fibonacci Sequence (Recursive)](#fibonacci-sequence-recursive) +- [Factorial of a Number](#factorial-of-a-number) +- [Find the GCD (Greatest Common Divisor)](#find-the-gcd-greatest-common-divisor) + +### Searching + +- [Two Sum (Using Hash Map)](#two-sum-using-hash-map) +- [Binary Search](#binary-search) + +### Sorting + +- [Bubble Sort](#bubble-sort) +- [Quick Sort](#quick-sort) +- [Merge Two Sorted Arrays](#merge-two-sorted-arrays) + +### Array Utilities + +- [Find Maximum in Array](#find-maximum-in-array) + +### Utility Functions + +- [Debounce Function](#debounce-function) + +## String Manipulation + +### Reverse a String ```js function reverseString(str) { @@ -16,7 +54,9 @@ console.log(reverseString("hello")); // Output: "olleh" **Explanation**: Reverses the characters in a string by splitting, reversing, and joining them back together. -## 2. Palindrome Check +[Back to top](#algorithms) + +### Palindrome Check ```js function isPalindrome(str) { @@ -28,55 +68,44 @@ console.log(isPalindrome("racecar")); // Output: true **Explanation**: Determines if a string reads the same backward as forward using string reversal. -## 3. Binary Search +[Back to top](#algorithms) + +### Character Frequency Counter ```js -function binarySearch(arr, target) { - let left = 0, - 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; +function charFrequency(str) { + const freq = {}; + for (let char of str) { + freq[char] = (freq[char] || 0) + 1; } - return -1; + return freq; } -console.log(binarySearch([1, 2, 3, 4, 5], 4)); // Output: 3 +console.log(charFrequency("hello")); // Output: { h: 1, e: 1, l: 2, o: 1 } ``` -**Explanation**: Searches for a target in a sorted array using a divide-and-conquer approach. +**Explanation**: Counts how often each character appears in a string. -## 4. Fibonacci Sequence (Recursive) +[Back to top](#algorithms) + +### Anagram Check ```js -function fibonacci(n) { - if (n <= 1) return n; - return fibonacci(n - 1) + fibonacci(n - 2); +function isAnagram(str1, str2) { + const normalize = (str) => str.split("").sort().join(""); + return normalize(str1) === normalize(str2); } -console.log(fibonacci(6)); // Output: 8 +console.log(isAnagram("listen", "silent")); // Output: true ``` -**Explanation**: Generates the nth Fibonacci number recursively by summing the two preceding numbers. - -⚠️ **Note**: This approach has exponential time complexity `O(2^n)` and is inefficient for large inputs. - -## 5. Factorial of a Number - -```js -function factorial(n) { - if (n === 0) return 1; - return n * factorial(n - 1); -} +**Explanation**: Determines if two strings are anagrams by sorting and comparing them. -console.log(factorial(5)); // Output: 120 -``` +[Back to top](#algorithms) -**Explanation**: Calculates the factorial of a number recursively by multiplying it with decremented values. +## Math & Number Theory -## 6. Prime Number Check +### Prime Number Check ```js function isPrime(num) { @@ -92,58 +121,41 @@ console.log(isPrime(7)); // Output: true **Explanation**: Checks if a number is prime by testing divisibility up to its square root. -## 7. Find Maximum in Array +[Back to top](#algorithms) + +### Fibonacci Sequence (Recursive) ```js -function findMax(arr) { - return Math.max(...arr); +function fibonacci(n) { + if (n <= 1) return n; + return fibonacci(n - 1) + fibonacci(n - 2); } -console.log(findMax([1, 2, 3, 4, 5])); // Output: 5 +console.log(fibonacci(6)); // Output: 8 ``` -**Explanation**: Finds the largest number in an array using the `Math.max` function and spread operator. - -## 8. Merge Two Sorted Arrays - -```js -function mergeSortedArrays(arr1, arr2) { - let merged = [], i = 0, j = 0; - while (i < arr1.length && j < arr2.length) { - if (arr1[i] < arr2[j]) { - merged.push(arr1[i++]); - } else { - merged.push(arr2[j++]); - } - } - return merged.concat(arr1.slice(i)).concat(arr2.slice(j)); -} +**Explanation**: Generates the nth Fibonacci number recursively by summing the two preceding numbers. -console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6] -``` +[Back to top](#algorithms) -**Explanation**: Merges two sorted arrays into one sorted array by comparing elements sequentially. +⚠️ **Note**: This approach has exponential time complexity `O(2^n)` and is inefficient for large inputs. -## 9. Bubble Sort +### Factorial of a Number ```js -function bubbleSort(arr) { - for (let i = 0; i < arr.length; i++) { - for (let j = 0; j < arr.length - i - 1; j++) { - if (arr[j] > arr[j + 1]) { - [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; - } - } - } - return arr; +function factorial(n) { + if (n === 0) return 1; + return n * factorial(n - 1); } -console.log(bubbleSort([5, 3, 8, 4, 2])); // Output: [2, 3, 4, 5, 8] +console.log(factorial(5)); // Output: 120 ``` -**Explanation**: Sorts an array by repeatedly swapping adjacent elements if they are in the wrong order. +**Explanation**: Calculates the factorial of a number recursively by multiplying it with decremented values. -## 10. Find the GCD (Greatest Common Divisor) +[Back to top](#algorithms) + +### Find the GCD (Greatest Common Divisor) ```js function gcd(a, b) { @@ -156,7 +168,11 @@ console.log(gcd(48, 18)); // Output: 6 **Explanation**: Uses the Euclidean algorithm to compute the greatest common divisor. -## 11. Two Sum (Using Hash Map) +[Back to top](#algorithms) + +## Searching + +### Two Sum (Using Hash Map) ```js function twoSum(nums, target) { @@ -174,36 +190,54 @@ console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1] **Explanation**: Finds two indices such that their values sum to the target using a hash map. -## 12. Anagram Check +[Back to top](#algorithms) + +### Binary Search ```js -function isAnagram(str1, str2) { - const normalize = (str) => str.split("").sort().join(""); - return normalize(str1) === normalize(str2); +function binarySearch(arr, target) { + let left = 0, + 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(isAnagram("listen", "silent")); // Output: true +console.log(binarySearch([1, 2, 3, 4, 5], 4)); // Output: 3 ``` -**Explanation**: Determines if two strings are anagrams by sorting and comparing them. +**Explanation**: Searches for a target in a sorted array using a divide-and-conquer approach. + +[Back to top](#algorithms) -## 13. Character Frequency Counter +## Sorting + +### Bubble Sort ```js -function charFrequency(str) { - const freq = {}; - for (let char of str) { - freq[char] = (freq[char] || 0) + 1; +function bubbleSort(arr) { + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr.length - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; + } + } } - return freq; + return arr; } -console.log(charFrequency("hello")); // Output: { h: 1, e: 1, l: 2, o: 1 } +console.log(bubbleSort([5, 3, 8, 4, 2])); // Output: [2, 3, 4, 5, 8] ``` -**Explanation**: Counts how often each character appears in a string. +**Explanation**: Sorts an array by repeatedly swapping adjacent elements if they are in the wrong order. + +[Back to top](#algorithms) -## 14. Quick Sort +### Quick Sort ```js function quickSort(arr) { @@ -223,7 +257,49 @@ console.log(quickSort([3, 6, 8, 10, 1, 2, 1])); // Output: [1, 1, 2, 3, 6, 8, 10 **Explanation**: A divide-and-conquer sorting algorithm with an average-case time complexity of `O(n log n)`. -## 15. Debounce Function +[Back to top](#algorithms) + +### Merge Two Sorted Arrays + +```js +function mergeSortedArrays(arr1, arr2) { + let merged = [], i = 0, j = 0; + while (i < arr1.length && j < arr2.length) { + if (arr1[i] < arr2[j]) { + merged.push(arr1[i++]); + } else { + merged.push(arr2[j++]); + } + } + return merged.concat(arr1.slice(i)).concat(arr2.slice(j)); +} + +console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6] +``` + +**Explanation**: Merges two sorted arrays into one sorted array by comparing elements sequentially. + +[Back to top](#algorithms) + +## Array Utilities + +### Find Maximum in Array + +```js +function findMax(arr) { + return Math.max(...arr); +} + +console.log(findMax([1, 2, 3, 4, 5])); // Output: 5 +``` + +**Explanation**: Finds the largest number in an array using the `Math.max` function and spread operator. + +[Back to top](#algorithms) + +## Utility Functions + +### Debounce Function ```js function debounce(fn, delay) { @@ -241,3 +317,5 @@ log(); // Logs once after 300ms of inactivity ``` **Explanation**: Limits the rate at which a function can fire, commonly used in event handling (e.g., input, scroll). + +[Back to top](#algorithms)