The Famous 50

The Famous 50

1. Hello, World!


console.log('Hello, World!');

2. Factorial of a Number


const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
console.log(factorial(5)); // Example: 5! = 120

3. Fibonacci Series


const fib = (n) => (n <= 1 ? n : fib(n - 1) + fib(n - 2));
for (let i = 0; i < 10; i++) console.log(fib(i));

4. Prime Number Check


const isPrime = (n) => {
    for (let i = 2; i <= Math.sqrt(n); i++) if (n % i === 0) return false;
    return n > 1;
};
console.log(isPrime(7)); // Example: true

5. Palindrome Check (String)


const isPalindrome = (str) => str === str.split('').reverse().join('');
console.log(isPalindrome('madam')); // Example: true

6. Sorting an Array (Bubble Sort)


const 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;
};
console.log(bubbleSort([3, 1, 4, 1, 5, 9]));

7. Binary Search


const binarySearch = (arr, target) => {
    let left = 0, right = arr.length - 1;
    while (left <= right) {
        let mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
};
console.log(binarySearch([1, 2, 3, 4, 5], 3)); // Example: 2

8. Greatest Common Divisor (GCD)


const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
console.log(gcd(48, 18)); // Example: 6

9. Matrix Multiplication


const multiplyMatrices = (a, b) => {
    const result = Array(a.length).fill().map(() => Array(b[0].length).fill(0));
    for (let i = 0; i < a.length; i++)
        for (let j = 0; j < b[0].length; j++)
            for (let k = 0; k < b.length; k++)
                result[i][j] += a[i][k] * b[k][j];
    return result;
};
console.log(multiplyMatrices([[1, 2], [3, 4]], [[5, 6], [7, 8]]));

10. Quick Sort


const quickSort = (arr) => {
    if (arr.length <= 1) return arr;
    const pivot = arr[arr.length - 1];
    const left = arr.filter((x) => x < pivot);
    const right = arr.filter((x) => x > pivot);
    return [...quickSort(left), pivot, ...quickSort(right)];
};
console.log(quickSort([3, 1, 4, 1, 5, 9]));

11. Reverse a String


const reverseString = (str) => str.split('').reverse().join('');
console.log(reverseString('hello')); // Example: 'olleh'

12. Linear Search


const linearSearch = (arr, target) => {
    for (let i = 0; i < arr.length; i++) if (arr[i] === target) return i;
    return -1;
};
console.log(linearSearch([10, 20, 30, 40], 30)); // Example: 2

13. Merge Two Sorted Arrays


const mergeSortedArrays = (arr1, arr2) => [...arr1, ...arr2].sort((a, b) => a - b);
console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Example: [1, 2, 3, 4, 5, 6]

14. Check Armstrong Number


const isArmstrong = (n) => {
    const digits = n.toString().split('');
    return n === digits.reduce((sum, d) => sum + Math.pow(+d, digits.length), 0);
};
console.log(isArmstrong(153)); // Example: true

15. Find Largest Element in an Array


const findLargest = (arr) => Math.max(...arr);
console.log(findLargest([1, 2, 3, 4, 5])); // Example: 5

16. Count Vowels in a String


const countVowels = (str) => (str.match(/[aeiou]/gi) || []).length;
console.log(countVowels('hello world')); // Example: 3

17. Decimal to Binary Conversion


const decimalToBinary = (n) => n.toString(2);
console.log(decimalToBinary(10)); // Example: '1010'

18. Binary to Decimal Conversion


const binaryToDecimal = (binary) => parseInt(binary, 2);
console.log(binaryToDecimal('1010')); // Example: 10

19. Sum of Digits


const sumOfDigits = (n) => n.toString().split('').reduce((sum, d) => sum + +d, 0);
console.log(sumOfDigits(123)); // Example: 6

20. Check Leap Year


const isLeapYear = (year) => (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
console.log(isLeapYear(2024)); // Example: true

21. Find Missing Number in Array


const findMissing = (arr, n) => (n * (n + 1)) / 2 - arr.reduce((sum, num) => sum + num, 0);
console.log(findMissing([1, 2, 3, 5], 5)); // Example: 4

22. Check Perfect Number


const isPerfect = (n) => {
    let sum = 0;
    for (let i = 1; i <= n / 2; i++) if (n % i === 0) sum += i;
    return sum === n;
};
console.log(isPerfect(6)); // Example: true

23. Check Anagram


const isAnagram = (str1, str2) => 
    str1.split('').sort().join('') === str2.split('').sort().join('');
console.log(isAnagram('listen', 'silent')); // Example: true

24. Generate Pascal's Triangle


const pascalsTriangle = (n) => {
    const triangle = [[1]];
    for (let i = 1; i < n; i++) {
        const prev = triangle[i - 1];
        const row = [1];
        for (let j = 1; j < prev.length; j++) row.push(prev[j - 1] + prev[j]);
        row.push(1);
        triangle.push(row);
    }
    return triangle;
};
console.log(pascalsTriangle(5));

25. Count Words in a String


const countWords = (str) => str.trim().split(/\s+/).length;
console.log(countWords('hello world from node.js')); // Example: 4

26. Check Palindrome Number


const isPalindromeNumber = (n) => n.toString() === n.toString().split('').reverse().join('');
console.log(isPalindromeNumber(121)); // Example: true

27. Find the Second Largest Element


const secondLargest = (arr) => [...new Set(arr)].sort((a, b) => b - a)[1];
console.log(secondLargest([1, 2, 3, 4, 4])); // Example: 3

28. Power of a Number


const power = (base, exp) => Math.pow(base, exp);
console.log(power(2, 3)); // Example: 8

29. Sum of Array Elements


const sumArray = (arr) => arr.reduce((sum, num) => sum + num, 0);
console.log(sumArray([1, 2, 3, 4])); // Example: 10

30. Transpose of a Matrix


const transpose = (matrix) => matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]));
console.log(transpose([[1, 2], [3, 4]])); // Example: [[1, 3], [2, 4]]

31. Count Occurrences of a Character


const countChar = (str, char) => str.split(char).length - 1;
console.log(countChar('hello world', 'l')); // Example: 3

32. Check Strong Number


const isStrong = (n) => {
    const factorial = (x) => (x <= 1 ? 1 : x * factorial(x - 1));
    return n === n.toString().split('').reduce((sum, d) => sum + factorial(+d), 0);
};
console.log(isStrong(145)); // Example: true

33. Check Perfect Square


const isPerfectSquare = (n) => Number.isInteger(Math.sqrt(n));
console.log(isPerfectSquare(25)); // Example: true

34. Generate Fibonacci Sequence Up to N


const fibonacciUpToN = (n) => {
    const seq = [0, 1];
    while (seq[seq.length - 1] + seq[seq.length - 2] <= n) seq.push(seq[seq.length - 1] + seq[seq.length - 2]);
    return seq;
};
console.log(fibonacciUpToN(21)); // Example: [0, 1, 1, 2, 3, 5, 8, 13, 21]

35. Reverse an Array


const reverseArray = (arr) => arr.reverse();
console.log(reverseArray([1, 2, 3, 4])); // Example: [4, 3, 2, 1]

36. Find HCF and LCM


const hcf = (a, b) => (b === 0 ? a : hcf(b, a % b));
const lcm = (a, b) => (a * b) / hcf(a, b);
console.log(hcf(12, 15)); // Example: 3
console.log(lcm(12, 15)); // Example: 60

37. Sum of Natural Numbers


const sumNatural = (n) => (n * (n + 1)) / 2;
console.log(sumNatural(10)); // Example: 55

38. Check Binary Number


const isBinary = (n) => /^[01]+$/.test(n.toString());
console.log(isBinary(1010)); // Example: true

39. Check Even or Odd Number


const isEven = (n) => n % 2 === 0;
console.log(isEven(4)); // Example: true

40. Check Prime Factors of a Number


const primeFactors = (n) => {
    const factors = [];
    for (let i = 2; i <= n; i++) while (n % i === 0) (factors.push(i), (n /= i));
    return factors;
};
console.log(primeFactors(56)); // Example: [2, 2, 2, 7]

41. Generate Prime Numbers Up to N


const primesUpToN = (n) => {
    const primes = [];
    for (let i = 2; i <= n; i++) if (primeFactors(i).length === 1) primes.push(i);
    return primes;
};
console.log(primesUpToN(20)); // Example: [2, 3, 5, 7, 11, 13, 17, 19]

42. Find Maximum Difference in an Array


const maxDifference = (arr) => Math.max(...arr) - Math.min(...arr);
console.log(maxDifference([1, 2, 3, 4, 5])); // Example: 4

43. Check Automorphic Number


const isAutomorphic = (n) => n.toString() === Math.pow(n, 2).toString().slice(-n.toString().length);
console.log(isAutomorphic(25)); // Example: true

44. Find All Divisors of a Number


const divisors = (n) => [...Array(n + 1).keys()].filter((i) => n % i === 0);
console.log(divisors(12)); // Example: [1, 2, 3, 4, 6, 12]

45. Check Friendly Pair


const sumOfDivisors = (n) => divisors(n).reduce((sum, d) => sum + d, 0) - n;
const isFriendlyPair = (a, b) => sumOfDivisors(a) / a === sumOfDivisors(b) / b;
console.log(isFriendlyPair(6, 28)); // Example: false

46. Find Factorial Using Iteration


const factorialIterative = (n) => {
    let fact = 1;
    for (let i = 1; i <= n; i++) fact *= i;
    return fact;
};
console.log(factorialIterative(5)); // Example: 120

47. Find nth Root


const nthRoot = (x, n) => Math.pow(x, 1 / n);
console.log(nthRoot(16, 4)); // Example: 2

48. Sort Strings Alphabetically


const sortStrings = (arr) => arr.sort();
console.log(sortStrings(['banana', 'apple', 'cherry'])); // Example: ['apple', 'banana', 'cherry']

49. Find Unique Elements in an Array


const uniqueElements = (arr) => [...new Set(arr)];
console.log(uniqueElements([1, 2, 2, 3, 3, 4])); // Example: [1, 2, 3, 4]

50. Find Sum of Even and Odd Numbers


const sumEvenOdd = (arr) => arr.reduce(([even, odd], num) => num % 2 === 0 ? [even + num, odd] : [even, odd + num], [0, 0]);
console.log(sumEvenOdd([1, 2, 3, 4])); // Example: [6, 4]