Mastering Essential Algorithms with JavaScript

Bablu RoyBablu Roy
6 min read

In the realm of programming, algorithms serve as the backbone of problem-solving methodologies, offering structured steps to tackle computational tasks efficiently. It's important to form efficient algorithms that optimize problem-solving processes. Explore fundamental algorithms implemented in JavaScript, unraveling their intricacies and showcasing their utility with illustrative examples.

1. Palindrome Checker

A palindrome is a sequence that reads the same backward as forward. The isPalindrome function scrutinizes whether a given number is a palindrome or not.

Explanation:

  • A palindrome number remains unchanged when its digits are reversed.

  • For instance, 151 when reversed is also 151.

  • The function first converts the number into a string, reverses it, and then checks if it remains unchanged.

  • If the reversed string matches the original, the number is deemed a palindrome.

Example:

const isPalindrome = (num) => {
   return num < 0 ? false : num === +num.toString().split("").reverse().join("");
};

// Example
console.log(isPalindrome(121)); // Output: true (121 is a palindrome)
console.log(isPalindrome(123)); // Output: false (123 is not a palindrome)

Code Explanation:

  • The function first checks if the input number is negative. If it is, it immediately returns false because negative numbers cannot be palindromes.

  • Next, it converts the number to a string using toString().

  • Then, it splits the string into an array of individual characters using split("").

  • After that, it reverses the order of the characters in the array using reverse().

  • Finally, it joins the reversed array back into a string using join("").

  • The function then compares this reversed string with the original string representation of the number. If they are equal, the number is a palindrome.

2. Fibonacci Number Generator

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. The fibonacciNumber function generates the Fibonacci number at a given position.

Explanation:

  • The Fibonacci sequence is generated iteratively by adding the last two numbers in the sequence to produce the next number.

  • For example, the 7th Fibonacci number is 13, calculated as 8 + 5.

  • The function initializes an array with the first two Fibonacci numbers (0 and 1) and then iterates to generate subsequent numbers.

Example:

const fibonacciNumber = (n) => {
    const arr = [0 , 1];
    for (let i = 2; i <= n; i++) {
        arr.push(arr[i- 1] + arr[i -2]);
    }
    return arr[n];
};

// Example
console.log(fibonacciNumber(7)); // Output: 13 (7th Fibonacci number)
console.log(fibonacciNumber(10)); // Output: 55 (10th Fibonacci number)

Code Explanation:

  • The function initializes an array arr with the first two Fibonacci numbers [0, 1].

  • It then enters a loop starting from index 2 up to the desired position n.

  • Inside the loop, it calculates the next Fibonacci number by adding the two preceding numbers in the array (arr[i-1] and arr[i-2]).

  • It pushes the calculated Fibonacci number into the array arr.

  • After the loop, the function returns the Fibonacci number at the specified position n.

3. Anagram Checker

An anagram is formed by rearranging the letters of a word to produce a new word or phrase. The isAnagram function verifies whether two strings are anagrams of each other.

Explanation:

  • An anagram checker compares the frequency of characters in both strings.

  • For example, "listen" and "silent" are anagrams of each other.

  • It converts both strings to arrays, sorts them, and then compares if they are equal.

Example:

const isAnagram = (s, t) => {
    s = s.split("").sort().join("");
    t = t.split("").sort().join("");
    if(s === t) return true;
    return false;
};

// Example
console.log(isAnagram('anagram', 'nagaram')); // Output: true (Both are anagrams)
console.log(isAnagram('hello', 'world')); // Output: false (Not anagrams)

Code Explanation:

  • The function converts both input strings s and t into arrays of characters using split("").

  • It then sorts both arrays alphabetically using sort().

  • After sorting, it joins the characters back into strings using join("").

  • Finally, it compares the sorted strings s and t. If they are equal, the function returns true, indicating that the strings are anagrams. Otherwise, it returns false.

4. Two Sum

The twoSum function seeks two numbers in an array that sum up to a specified target value.

Explanation:

  • The function uses a nested loop to iterate through the array and find pairs of numbers.

  • For example, in [2, 7, 11, 15], the pair [2, 7] sums up to 9.

  • It checks each pair to see if their sum equals the target value.

Example:

const twoSum = (nums, target) => {
    for (let i = 0; i < nums.length; i++) {
        for (let j = i+1; j < nums.length; j++) {
            if(nums[i] + nums[j] === target) return [i,j];
        }
    }
};  

// Example
console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1] (Indices of 2 and 7)
console.log(twoSum([3, 2, 4], 6)); // Output: [1, 2] (Indices of 2 and 4)

Code Explanation:

  • The function takes an array of numbers nums and a target value target as input.

  • It iterates over each element in the nums array using a nested loop.

  • The outer loop iterates from the beginning of the array to the second-to-last element (i).

  • The inner loop iterates from the element after i to the end of the array (j).

  • Within the loops, it checks if the sum of the current element at index i and the element at index j equals the target value.

  • If a pair of numbers is found that sums up to the target value, it returns an array containing the indices of those two numbers.

5. Maximum Profit from Stocks

The maxProfit function determines the maximum profit that can be attained by buying and selling stocks from a given array of prices.

Explanation:

  • The function tracks the minimum stock purchase price and updates the maximum profit as it iterates through the array.

  • For instance, in [7, 1, 5, 3, 6, 4], the maximum profit is 5 (buy at 1, sell at 6).

  • It calculates the potential profit by subtracting the minimum purchase price from each price in the array.

Example:

const maxProfit = (prices) => {
    let minStockPurchasePrice = prices[0] || 0;
    let profit = 0;
    for (let i = 0; i < prices.length; i++) {
        if(prices[i] < minStockPurchasePrice) {
            minStockPurchasePrice = prices[i];
        }       
        profit = Math.max(profit, prices[i] - minStockPurchasePrice);
    }
    return profit;
};

// Example
console.log(maxProfit([7, 1, 5, 3, 6, 4])); // Output: 5 (Max profit is by buying at 1 and selling at 6)
console.log(maxProfit([7, 6, 4, 3, 1])); // Output: 0 (No profit can be made)

Code Explanation:

  • The function takes an array of stock prices prices as input.

  • It initializes variables minStockPurchasePrice to store the minimum stock purchase price and profit to store the maximum profit.

  • It iterates over each price in the prices array.

  • For each price, it updates minStockPurchasePrice if the current price is lower than the previously recorded minimum.

  • It calculates the profit that could be made by selling the stock at the current price (prices[i] - minStockPurchasePrice) and updates profit to the maximum value between the current profit and the calculated profit.

  • After iterating through all prices, it returns the maximum profit that could be made.

Thanks for reading !! ❤

0
Subscribe to my newsletter

Read articles from Bablu Roy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bablu Roy
Bablu Roy