DEV Community

Ashwani Singh
Ashwani Singh

Posted on

LeetCode Solutions (DSA)

1. LeetCode Solutions (DSA) - Two Sum

1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

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]

Result ->


let nums = [2,7,11,15];
let target = 9
let index = [];

function 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){
        index.push(i)
        index.push(j)
      }
    }
  }
}
twoSum(nums, target)
console.log(index)

Enter fullscreen mode Exit fullscreen mode

2. 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.

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]

Result 1. ->

function AddTwoNumber(l1, l2){
  let arr = []
  let sum = Number(l1.join('')) + Number(l2.join(''));
  let str = String(sum).split('').reverse();
  for(let i=0; i<str.length; i++){
    arr.push(Number(str[i]))
  }
  return arr;
}

console.log(AddTwoNumber(l1, l2))
Enter fullscreen mode Exit fullscreen mode

Result 2. ->

function AddTwoNumbers(l1, l2){
if(l1.length != l2.length){
  let length = (l1.length > l2.length) ? l1.length - l2.length : l2.length - l1.length;
  for(let j = 0 ; j < length; j++){
  (l1.length > l2.length) ? l2.push(0) : l1.push(0)
  }
}
  let carry = 0;
  let final = []
  for(let i = 0; i < l1.length; i++){
    let sum = l1[i] + l2[i] + carry;
    if(sum > 9){
      final.push(Math.floor(sum % 10));
      carry = Math.floor(sum/10);
    } else {
      final.push(sum)
      carry = 0;
    }
  }
  if(carry >= 1){
    final.push(carry)
  }
  return final;
};
AddTwoNumbers(l1, l2)
Enter fullscreen mode Exit fullscreen mode

3. 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.

Result 1. ->

let x = 121;
var isPalindrome = function (x) {
 return x < 0 ? false : x === +x.toString().split("").reverse().join('')
};
isPalindrome(x)
--------------------------xxxxxxxxxxxxxxxx-----------------------


let val = 121;
function isPalindrome(val){
  let str = Number(String(val).split('').reverse().join(''));
  if(str === val){
    return true;
  } else return false;
}
console.log(isPalindrome(val))

Enter fullscreen mode Exit fullscreen mode

Result 2. ->

function isPalindrome(val){
let data = Array.from(String(val));
let arr = []
for(let i = data.length-1; i >= 0; i--){
  if(Number(data[i])){
  arr.push(Number(data[i]));
  } else {
    arr.push((data[i]));
  }
}
let out = arr.join('');
  if(out == val){
    return true;
  } else return false;
}
console.log(isPalindrome(val))

Enter fullscreen mode Exit fullscreen mode

4. 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.

Result :


var romanToInt = function (rom) {
    let modRoman = rom;
    let sum = 0;
    if (rom.includes('IV')) {
        modRoman = rom.replace('IV', '');
        sum = sum + 4;
    } if (rom.includes('IX')) {
        modRoman = modRoman.replace('IX', '');
        sum = sum + 9
    } if (rom.includes('XL')) {
        modRoman = modRoman.replace('XL', '')
        sum = sum + 40;
    } if (rom.includes('XC')) {
        modRoman = modRoman.replace('XC', '')
        sum = sum + 90;
    } if (rom.includes('CD')) {
        modRoman = modRoman.replace('CD', '')
        sum = sum + 400;
    } if (rom.includes('CM')) {
        modRoman = modRoman.replace('CM', '')
        sum = sum + 900;
    };
    let value = modRoman.split('');
    for (let i = 0; i < value.length; i++) {
        if (value[i] === 'I') {
            sum = sum + 1;
        } else if (value[i] === 'I') {
            sum = sum + 1;
        } else if (value[i] === 'V') {
            sum = sum + 5;
        } else if (value[i] === 'X') {
            sum = sum + 10;
        } else if (value[i] === 'L') {
            sum = sum + 50;
        } else if (value[i] === 'C') {
            sum = sum + 100;
        } else if (value[i] === 'D') {
            sum = sum + 500;
        } else if (value[i] === 'M') {
            sum = sum + 1000;
        }
    };
    return sum
};
Enter fullscreen mode Exit fullscreen mode

Result.2

 let findInt = (Roman) =>{
    switch(Roman){
        case 'I': return 1;
        case 'V': return 5;
        case 'X': return 10;
        case 'L': return 50;
        case 'C': return 100;
        case 'D': return 500;
        case 'M': return 1000;

    }
 }
var romanToInt = function(s) {
    let result = 0;
    for(i = 0;i < s.length;i++){
        console.log(result, s[i], s[i+1])

        if(findInt(s[i]) < findInt(s[i+1])){
            result -= findInt(s[i]);
        }else{
            result +=findInt(s[i]);
        }
    }
       return result

};
console.log(romanToInt("MCMXCIV"))
Enter fullscreen mode Exit fullscreen mode

Result - 4

function romanToInt(rom){
  let obj = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
  };
  let count = 0;
  for (var i = 0; i < rom.length; i++) {
    if(rom[i] + rom[i+1] === 'IV'){
      count += 4
      i++
    } else if(rom[i] + rom[i+1] === 'IX'){
      count += 9;
      i++
    } else if(rom[i] + rom[i+1] === 'XL'){
      count += 40;
      i++
    } else if(rom[i] + rom[i+1] === 'XC'){
      count += 90;
      i++
    } else if(rom[i] + rom[i+1] === 'CD'){
      count += 400;
      i++
    } else if(rom[i] + rom[i+1] === 'CM'){
      count += 900;
      i++
    } else if (obj.hasOwnProperty(rom[i])) {
      count = count + obj[rom[i]]
    }
    }
    return count;
  }

Enter fullscreen mode Exit fullscreen mode

5. Count Characters

Javascript Practice Problems: Count Characters in String;

Results :


function findCountOfOcc(str){
  let obj = {};
  for(let i = 0; i < str.length; i++){
    let key = str[i]
    obj[key] = (obj[key] || 0) + 1;
  }
  return obj
}

console.log(findCountOfOcc("HelloWorld"));

Enter fullscreen mode Exit fullscreen mode
function findCountOfOcc(str){
  let obj = {};
  for(let i in str){
    let key = str[i]
    obj[key] = (obj[key] || 0) + 1;
  }
  return obj
}

console.log(findCountOfOcc("HelloWorld"));
Enter fullscreen mode Exit fullscreen mode
function findCountOfOcc(str){
  let obj = {};
  for(let key of str){
    if(obj[key]){
      obj[key] = obj[key] + 1
    } else obj[key] = 1
  }
  return obj
}

console.log(findCountOfOcc("HelloWorld"));
Enter fullscreen mode Exit fullscreen mode

6. 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.

Result


let strs = ["flower","flow","flight"];

function toFindPrefix(strs){
  let srt = strs.sort();
  let firstEle = srt[0];
  let lastEle = srt[srt.length-1];
  let data = ''
  for(let i = 0; i < lastEle.length; i++){
    if(lastEle[0] === firstEle[0]){
      if(lastEle[i] === firstEle[i]){
      data = `${data + firstEle[i]}`
    } else break;
    }
  }
  return data;
}
toFindPrefix(strs);

Enter fullscreen mode Exit fullscreen mode

7 Valid Parentheses

iven a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Example 1: Input: s = "()" Output: true

Example 2: Input: s = "()[]{}" Output: true

Example 3: Input: s = "(]" Output: false

Example 4: Input: s = "([])" Output: true

var isValid = function (s) {
let obj = {
    '(': ')',
    '{': '}',
    '[':']'
  };
  if(
    s[0] === '(' && !s.includes(')') || 
    s[0] === '{' && !s.includes('}') || 
    s[0] === '[' && !s.includes(']') 
  ){
    return false;
  };
  let stack = [];
  for (var i = 0; i < s.length; i++) {
    if(obj[s[i]]){
      stack.push(s[i])
    } else {
      let pop = stack.pop();
      if(obj[pop] !== s[i]){
        return false
      }
    }
  }
  return stack.length === 0;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)