DEV Community

Ashwani Singh
Ashwani Singh

Posted on • Edited 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
let nums = [8,9, 4, 6, 2,7,11,15], target = 9;

function addTwoNumbers(nums){
  const numsToIndex = new Map();

  for (var i = 0; i < nums.length; i++) {
    const val = nums[i];
    const subs = target - val; 

    if(numsToIndex.has(subs)){
      return [numsToIndex.get(subs), i]
    }

    numsToIndex.set(val, i)

  }
}

console.log(addTwoNumbers(nums))
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
let obj = {
  'I': 1,
  'IV': 4,
  'V' : 5,
  'IX': 9,
  'X': 10,
  'XL': 40,
  'L': 50,
  'XC': 90,
  'C': 100,
  'CD': 400,
  'D': 500,
  'CM': 900,
  'M': 1000
}

function romanToIntegers(s){
    let count = 0;
  for (var i = 0; i < s.length; i++) {
    if(s[i] + s[i+1] === 'IV'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'IX'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'XL'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'XC'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'CD'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'CM'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    }
    else {
      count = count + obj[s[i]]
    }
  }
    return count;
}
console.log(romanToIntegers(s))
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

function isValid(s){
  let arr = [];
  for(char of s){
    if(char === '(' || char === '{' || char === '['){
      arr.push(char)
    } else if(
      char === ')' && arr[arr.length - 1] === '(' ||
      char === '}' && arr[arr.length - 1] === '{' ||
      char === ']' && arr[arr.length - 1] === '['
      ) {
        arr.pop()
      } else {
        return false
      }
  }
  return arr.length === 0;
}
console.log(isValid(str))

Enter fullscreen mode Exit fullscreen mode
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
function isValid(str){
  let obj = {
  ')':'(',
  '}':'{',
  ']':'['
};

  let strVal = str.split("");
  let stack = [];

  if(obj[strVal[0]]) return false;

  for (var i = 0; i < strVal.length; i++) {
    if(strVal[i])

    if(!obj[strVal[i]]){
      stack.push(strVal[i])

    } else {
     // If it's a closing bracket, check if it matches the last 
        opened bracket.

      if (stack.length === 0 || stack[stack.length - 1] !== obj[strVal[i]]) {
        return false;
      }
      stack.pop()
    }
  }
    return (stack.length === 0) ? true : false

}
console.log(isValid(str))
Enter fullscreen mode Exit fullscreen mode

Search Insert Position (binary search)

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.

Example 1:

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

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

Input: nums = [1,3,5,6], target = 7
Output: 4

Result - 1

let nums = [1,3,5,6], target = 2

function searchInsert(nums, target){
  let start = 0;
  let end = nums.length - 1;
  while(start <= end){
  let middle = Math.floor((start+end)/2);
    if(nums[middle] === target){
      return middle;
    } else if(nums[middle] < target){
      start = middle + 1;
    } else if (nums[middle] > target){
      end = middle - 1;
    }
  }
  return start
};

console.log(searchInsert(nums, target))
Enter fullscreen mode Exit fullscreen mode

Result-2

let nums = [1,3,5,6], target = 5

function searchInsert(nums, target, start, end){
  if (start > end){
    return start;
  }
  let middle = Math.floor((start+end)/2);
  if(nums[middle] === target){
    return middle;
  } else if(nums[middle] < target){
    return searchInsert(nums, target, middle + 1, end)
  } else if (nums[middle] > target){
    return searchInsert(nums, target, start, middle-1)
  }
};

console.log(searchInsert(nums, target, 0, nums.length-1))
Enter fullscreen mode Exit fullscreen mode

Kaprekar Number

Input : n = 45

Output : Yes
Explanation : 452 = 2025 and 20 + 25 is 45

Input : n = 13
Output : No
Explanation : 132 = 169. Neither 16 + 9 nor 1 + 69 is equal to 13

Input : n = 297

Output : Yes
Explanation: 2972 = 88209 and 88 + 209 is 297

Input : n = 10
Output : No
Explanation: 102 = 100. It is not a Kaprekar number even if
sum of 100 + 0 is 100. This is because of the condition that
none of the parts should have value 0.

let num = 9999 
// 9, 45, 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999 

function tocheckKarpekarNumber(num){
  let sq = num*num;
  let val = sq.toString().split("")
  let n = ''
  for(let i = 0; i < 5; i++){
    n = n + val[i];
    if((Number(n) + Number(val.slice(i+1).join("")) == num)){
      return true
    }
  }
  return false
}

Enter fullscreen mode Exit fullscreen mode

Reverse String

Input
let str = "I Am Not String"

output = "g ni rtS toNmAI";

function reverseString(val){
  let arr = val.split(" ");
  console.log(arr)
  let newVal= [];
  let data = val.split("").reverse().join("").split(" ").join("").split("");
  for (var i = 0; i < data.length; i++) {
    let d = data.splice(0, arr[i].length).join("")
    newVal.push(d)
  }
  return newVal.join(" ")
}
console.log(reverseString(str))
Enter fullscreen mode Exit fullscreen mode

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,,,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

✅ What does “in-place” mean?
It means you cannot use another array to store results. You must modify the given nums array directly, using constant extra memory (O(1)).

🧠 Approach (Two-pointer technique)
Use two pointers:

i → last index where a unique number was placed.

j → current index scanning the array.

Compare nums[j] with nums[i]:

If different: it’s a unique value → move i forward and assign nums[i] = nums[j].

function removeDuplicates(nums){
  if (nums.length === 0) return 0;
    let j = 0;
    for (var i = 0; i < nums.length; i++) {
    if(nums[i] !== nums[j]){
      j++
      nums[j] = nums[i]
      console.log(nums[j])
    }
  }
  return j+1
}
console.log(removeDuplicates(nums))
Enter fullscreen mode Exit fullscreen mode

Find the Index of the First Occurrence in a String

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

let haystack = "sadbutsad", needle = "sad";

function strStr(haystack,needle){
  let arr = []
  let index = 0;
  let l = needle.length;
  for (var i = 0; i < haystack.length; i+=l) {
    let val = haystack.slice(i, i+l);
    arr.push(val);
  };
  return arr.indexOf(needle);
}

  console.log(strStr(haystack,needle));
Enter fullscreen mode Exit fullscreen mode
function strStr(haystack,needle){
if (!haystack.length) return -1
    let val = haystack.indexOf(needle);
    return val
}
Enter fullscreen mode Exit fullscreen mode

Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in nums *in-place *

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

var removeElement = function(nums, val) {
    if(nums.length <= 0 ) return;
    let k = 0;
    for(let i = 0; i < nums.length; i++){
        if(nums[i] !== val){
            nums[k] = nums[i]
            k++
        }
    }
    return k;
};
Enter fullscreen mode Exit fullscreen mode

Search Insert Position (Binary Search)

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

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

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

Input: nums = [1,3,5,6], target = 7
Output: 4

var searchInsert = function(nums, target) {
      let start = 0;
  let end = nums.length - 1;
  while(start <= end){
  let middle = Math.floor((start+end)/2);
    if(nums[middle] === target){
      return middle;
    } else if(nums[middle] < target){
      start = middle + 1;
    } else if (nums[middle] > target){
      end = middle - 1;
    }
  }
  return start
};
Enter fullscreen mode Exit fullscreen mode

Plus One

Increment the large integer by one and return the resulting array of digits.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

let digits = [4,3,2,9];

function addOnes(){
  for(let i = digits.length-1; i >= 0; i--){
  // check if the didgits is less then 9 then just add 1 and return

        if(digits[i] < 9){
            digits[i]++;
            return digits;
        };

  // If the digit is 9, set it to 0 (and carry over to the next)

        digits[i] = 0;
        console.log(digits,"pppp")

    }

  // If we finished the loop, it means all digits were 9 (e.g., 999)
  // So we need to add a 1 at the beginning

    digits.unshift(1);
    return digits;
}

console.log(addOnes(digits))
Enter fullscreen mode Exit fullscreen mode

Add Binary

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.

let a = "1010", b = "11111";

var addBinary = function(a, b) {
  a = a.split('').reverse().join("");
  b = b.split('').reverse().join("");

  let obj = {
    '0': 0,
    '1': 1,
    '2': 0,
    '3': 1
  };
  console.log(a, b)
  let carry = 0;
  let ans = '';



  let lenA = a.length, lenB = b.length;
  for (var i = 0; i < Math.max(lenA, lenB); i++) {

    let numA = i < lenA ? Number(a[i]) : 0
    let numB = i < lenB ? Number(b[i]) : 0

    let sum = numA + numB + carry;
    sum >= 2 ? carry = 1 : carry = 0;
    let c = `${sum}`;
    ans = ans + obj[c];
  }
  if(carry) return (ans + carry).split('').reverse().join('');
  return ans.split('').reverse().join('');
};

console.log(addBinary(a,b))

Enter fullscreen mode Exit fullscreen mode
var addBinary = function(a, b) {
    let val1 = parseInt(a, 2);
    let val2 = parseInt(b, 2);

    let final = val1 + val2;
    return final.toString(2);
}
    console.log(addBinary(a,b))

Enter fullscreen mode Exit fullscreen mode

Top comments (0)