JavaScript Algorithms

CK CK 3788 
Created at
Updated at  
716 0 0

Two Sum

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const max_index = nums.length;
    for(var i=0; i<(max_index-1); i++)
    {
        num1 = nums[i];
        for(let j=i+1; j<max_index; j++)
        {
            num2 = nums[j];
            if ((num1+num2)==target) return [ i, j ];
        }
    }
    return [];
};

 

 Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.


Example 1:


Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
 

Constraints:

The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    var root = new ListNode( 0, null);
    var node = root;

    while(l1 || l2) {
        if (l1) {
            node.val += l1.val;
            l1=l1.next;
        }
        if (l2) {
            node.val += l2.val;
            l2=l2.next;
        }
        if (node.val>9) {
            node.val -= 10;
            node.next = new ListNode( 1, null );
        }
        else if (l1 || l2) node.next = new ListNode( 0, null);

        node = node.next;
    }
    return root;
};

 

Palindrome Number

Given an integer x, return true if x is a palindrome, and false otherwise.
 
Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
 

Constraints:

-231 <= x <= 231 - 1
 

Follow up: Could you solve it without converting the integer to a string?
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    if (x<0) return false;
    const arr = [];
    while(x>0)
    {
        arr.push( x % 10 );
        x = Math.floor( x / 10);
    }
    const x_len = arr.length;
    let x_pos = x_len-1;
    for(let i=0; i<x_len; i++)
    {
        if (arr[i] != arr[x_pos]) return false;
        x_pos--;
    }
    return true;
};

 

Roman to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9. 
X can be placed before L (50) and C (100) to make 40 and 90. 
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let previous_value = 0;
    let tmp=0;
    let num = 0;
    const num_table = {
        "I":1,
        "V":5,
        "X":10,
        "L":50,
        "C":100,
        "D":500,
        "M":1000
    };
    for(let i=0; i<s.length; i++) {
        let v = s[i];
        let p = num_table[ v ];
        if (i==0) {
            tmp = p
        }
        else {
            if (previous_value<p) {
                num += (p-tmp);
                tmp = 0;
            }
            else if (previous_value>p) {
                num += tmp;
                tmp = p;
            }
            else tmp += p;
        }
        previous_value = p;
    }
    num += tmp;
    return num;
};

Other solutions

 public int romanToInt(String s) {
         int ans = 0, num = 0;
        for (int i = s.length()-1; i >= 0; i--) {
            switch(s.charAt(i)) {
                case 'I': num = 1; break;
                case 'V': num = 5; break;
                case 'X': num = 10; break;
                case 'L': num = 50; break;
                case 'C': num = 100; break;
                case 'D': num = 500; break;
                case 'M': num = 1000; break;
            }
            if (4 * num < ans) ans -= num;
            else ans += num;
        }
        return ans;
    }

 

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".


Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
 

Constraints:

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters.
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let pos=0;
    let break_loop=false;
    while( pos<strs[0].length ) {
        for(let i=1; i<strs.length; i++) {
            if (pos>=strs[i].length)
            {
                break_loop=true;
                break;
            }
            if (strs[0][pos]!=strs[i][pos])
            {
                break_loop=true;
                break;
            }
        }
        if (break_loop==true) break;
        pos++;
    }    
    return strs[0].substring( 0, pos);
};

 

Longest Substring Without Repeating Characters

Given a string s, find the length of the longest 
substring
 without repeating characters.

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
 

Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let max_len = 0;
    let current_len = 0;
    for(let i=0; i<s.length;i++) {
        if (max_len > (s.length-i)) break;
        
        let hash=[];
        current_len = 1;
        hash[ s[i] ] =  1;
        let j = i + 1;
        while( j < (s.length) ) {
            key = s[j];
            if (hash[key]) break;
            hash[ key ] = 1;
            current_len ++;
            j++;
        }
        max_len = ( max_len < current_len) ? current_len:max_len;
    }
    return max_len;
};

 

BinaryTree Preorder Traversal

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
 
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    const res = []; // Initialize a new array for results

    const traverse = (node) => {
        if (node !== null) {
            res.push(node.val); // Add the current node value to the result
            traverse(node.left); // Recur on the left subtree
            traverse(node.right); // Recur on the right subtree
        }
    };

    traverse(root); // Start the traversal
    return res; // Return the result array
};

 

Longest Palindromic Substring

Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:

Input: s = "cbbd"
Output: "bb"

Constraints:

1 <= s.length <= 1000
s consist of only digits and English letters.
/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
  let longest = ''; 

  const expandFromCenter = (left, right) => {
    while (left >= 0 && right < s.length && s[left] === s[right]) {
      const currentLength = right - left + 1;

      // Update longest palindrome if the current one is longer
      if (currentLength > longest.length) {
        longest = s.slice(left, right + 1);
      }

      left--;
      right++;
    }
  };

  // Iterate through each character as a potential palindrome center
  for (let i = 0; i < s.length; i++) {
    expandFromCenter(i, i);       // Odd-length palindrome (single center)
    expandFromCenter(i, i + 1);   // Even-length palindrome (double center)
  }

  return longest;
};

 

 

Zigzag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);
 

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I
Example 3:

Input: s = "A", numRows = 1
Output: "A"
 

Constraints:

1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    let m = [];
    for(var i =0; i<numRows; i++) m[i] = "";

    let pos = 0;
    let cnt = 0;
    let direction=1;
    while(cnt<s.length)
    {
        m[pos] += s[cnt];
        if (numRows>1)
        {
            if (pos==0) {
                direction = 1; // move down
            }
            else if (pos==(numRows-1)) {
                direction = -1; // move up
            }
            pos += direction;
        }
        cnt++;
    }

    let result = "";
    for(var i =0; i<numRows; i++) result += m[i];

    return result;
};

 

Calculator with Method Chaining

Design a Calculator class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator class constructor should accept a number which serves as the initial value of result.

Your Calculator class should have the following methods:

add - This method adds the given number value to the result and returns the updated Calculator.
subtract - This method subtracts the given number value from the result and returns the updated Calculator.
multiply - This method multiplies the result  by the given number value and returns the updated Calculator.
divide - This method divides the result by the given number value and returns the updated Calculator. If the passed value is 0, an error "Division by zero is not allowed" should be thrown.
power - This method raises the result to the power of the given number value and returns the updated Calculator.
getResult - This method returns the result.
Solutions within 10-5 of the actual result are considered correct.

 

Example 1:

Input: 
actions = ["Calculator", "add", "subtract", "getResult"], 
values = [10, 5, 7]
Output: 8
Explanation: 
new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8
Example 2:

Input: 
actions = ["Calculator", "multiply", "power", "getResult"], 
values = [2, 5, 2]
Output: 100
Explanation: 
new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100
Example 3:

Input: 
actions = ["Calculator", "divide", "getResult"], 
values = [20, 0]
Output: "Division by zero is not allowed"
Explanation: 
new Calculator(20).divide(0).getResult() // 20 / 0 

The error should be thrown because we cannot divide by zero.
 

Constraints:

actions is a valid JSON array of strings
values is a valid JSON array of numbers
2 <= actions.length <= 2 * 104
1 <= values.length <= 2 * 104 - 1
actions[i] is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"
First action is always "Calculator"
Last action is always "getResult"
class Calculator {
    /** 
     * @param {number} value
     */
    constructor(value) {
        this.value = value;
    }
    
    /** 
     * @param {number} value
     * @return {Calculator}
     */
    add(value){
        this.value += value;
        return this;
    }
    
    /** 
     * @param {number} value
     * @return {Calculator}
     */
    subtract(value){
        this.value -= value;
        return this;
    }
    
    /** 
     * @param {number} value
     * @return {Calculator}
     */  
    multiply(value) {
        this.value *= value;
        return this;
    }
    
    /** 
     * @param {number} value
     * @return {Calculator}
     */
    divide(value) {
        if (value==0) {
            throw new Error("Division by zero is not allowed");
        }
        this.value /= value;
        return this;
    }
    
    /** 
     * @param {number} value
     * @return {Calculator}
     */
    power(value) {
        this.value **= value;
        return this;
    }
    
    /** 
     * @return {number}
     */
    getResult() {
        return this.value;
    }
}

 

 

Tags Algorithms Chain Method JavaScript Algorithms JavaScript Class JavaScript Tree Longest Common Prefix Palindrome Number Roman To Integer TwoSum Facebook X
Comments 0
Similar posts
  1. A simple Javascript class example with static method for Node.js
    660
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Tailwind CSS and shadcn/ui for React App with Charts and Graphs
    1,039
  3. HTML NoIndex: Keep Pages Off Search
    1,488
  4. JavaScript to disable Screen Saver or Power Saving Mode
    497
  5. Improving SEO with image-sitemap
    1,175
  6. Making HTML Tables Responsive on Mobile: Addressing Text Overflow
    770
  7. How do we make better SEO with schema.org?
    420
  8. A Javascript code that returns Monthly Mortgage Payment and Tax
    1,251
  9. A simple JavaScript snippet to copy a string to the clipboard
    1,049
  10. Dynamic JSON Editor based in HTML/JavaScript
    507
  11. How to post content (image or video) to Instagram using the Instagram Graph API
    6,389
  12. Font name correctly having the same width space
    1,210
  13. GraphQL Tutorial on CentOS 7: From Installation to Deployment
    555
  14. Capture all browser console logs including errors for debugging
    2,166
  15. Simple asynchronous/synchronous $.ajax() example using jQuery to make an HTTP GET request
    840
  16. JavaScript Code to Get Page Keywords
    344
  17. What is OpenGraph?
    364
  18. What is Twitter Cards?
    399
  19. Code to Extract the Site Thumbnail Image for Twitter or Facebook
    389
  20. JavaScript Code to Get the Page Title
    331
  21. JavaScript Code to Get Meta Description from HTML
    393
  22. Javascript code to extract favicon URL
    395
  23. RSS to Array in JavaScript
    2,138
  24. Javascript function to convert sitemap.xml to array
    595
  25. Understanding Elasticsearch from Installation to Trouble Shooting
    909
  26. IndexNow for better SEO
    316
  27. Enhancing SEO for Single Page Applications: Implementing Dynamic URL Updates
    1,037
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,730
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252