├── Practice Problems ├── HCF.js ├── Divisors Of N.js ├── Hash_Map_Functions.js ├── Oddcharacters.class ├── first_and_last_possition_of_a_sortes_array.js ├── leanerSearch.js ├── unique_element_in_array.js ├── tralling_zero.js ├── roted_array.js ├── bubbleSort.java ├── string_palindrom.js ├── Prime_Number.js ├── bubbleSort.js ├── stack │ ├── nextSmallerElement.js │ ├── allOperation.js │ ├── removeMiddleElement.js │ └── insertElementAtBottom.js ├── Oddcharacters.java ├── Find_Pivot_Element_From_Roted_sorted_array.js ├── occurences_of_a_character_in_a_string.js ├── kth_window _sum.js ├── reverse_array.js ├── linked list │ ├── linked_link_operation.js │ └── allOperatio.js ├── Next Greater Element (NGE).js └── 2Darray.js ├── question.txt ├── LEARN.md ├── CONTRIBUTING.md ├── .idea ├── vcs.xml ├── misc.xml ├── modules.xml ├── leet code.iml └── workspace.xml ├── Medium ├── 61. Rotate List.js ├── 189. Rotate Array.js ├── 56. Merge Intervals.js ├── 503. Next Greater Element II.js ├── 220. Contains Duplicate III.js ├── 532. K-diff Pairs in an Array.js ├── 438. Find All Anagrams in a String.js ├── 567. Permutation in String.js ├── 54. Spiral Matrix.js ├── 2. Add Two Numbers.js ├── 852. Peak Index in a Mountain Array.js ├── 443. String Compression.js ├── 74. Search a 2D Matrix.js ├── 34. Find First and Last Position of Element in Sorted Array.js ├── 1910. Remove All Occurrences of a Substring.js └── 33. Search in Rotated Sorted Array.js ├── Easy ├── 389. Find the Difference.js ├── 414. Third Maximum Number.js ├── 509. Fibonacci Number.js ├── 66. Plus One.js ├── 700. Search in a Binary Search Tree.js ├── 231. Power of Two.js ├── 202. Happy Number.js ├── 26. Remove Duplicates from Sorted Array.js ├── 21. Merge Two Sorted Lists.js ├── 67. Add Binary.js ├── 2351. First Letter to Appear Twice.js ├── 1047. Remove All Adjacent Duplicates In String.js ├── 496. Next Greater Element I.js ├── 242. Valid Anagram.js ├── 268. Missing Number.js ├── 392. Is Subsequence.js ├── 344. Reverse String.js ├── 283. Move Zeroes.js ├── 485. Max Consecutive Ones.js ├── 219. Contains Duplicate II.js ├── 15. 3Sum.js ├── 27. Remove Element.js ├── 448. Find All Numbers Disappeared in an Array.js ├── 13. Roman to Integer.js ├── 9. Palindrome Number.js ├── Majority Element.js ├── 1. Two Sum.js ├── Single Number.js ├── 1752. Check if Array Is Sorted and Rotated.js ├── 35. Search Insert Position.js ├── 20. Valid Parentheses.js ├── 28. Implement strStr().js ├── 349. Intersection of Two Arrays.js ├── 2006. Count Number of Pairs With Absolute Difference K.js ├── 69. Sqrt(x).js ├── 704. Binary Search.js ├── 58. Length of Last Word.js ├── 217. Contains Duplicate.js ├── 387. First Unique Character in a String.js ├── 121. Best Time to Buy and Sell Stock.js ├── 14. Longest Common Prefix.js ├── 345. Reverse Vowels of a String.js ├── 88. Merge Sorted Array.js └── 125. Valid Palindrome.js ├── Hard ├── 123. Best Time to Buy and Sell Stock III.java ├── 123. Best Time to Buy and Sell Stock III.js └── 84. Largest Rectangle in Histogram.js ├── README.md └── LICENSE /Practice Problems/HCF.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /question.txt: -------------------------------------------------------------------------------- 1 | ## When you add more dsa question? 2 | -------------------------------------------------------------------------------- /Practice Problems/Divisors Of N.js: -------------------------------------------------------------------------------- 1 | for (int i = 2; i <= 8; i++) { 2 | 3 | } -------------------------------------------------------------------------------- /LEARN.md: -------------------------------------------------------------------------------- 1 | If you want to practice leet-code problems you can check out my repository 2 | -------------------------------------------------------------------------------- /Practice Problems/Hash_Map_Functions.js: -------------------------------------------------------------------------------- 1 | var map = new Map(); 2 | map.set(1, 1); 3 | map.set(4, 1); 4 | console.log(map.get(4)); 5 | console.log(map.size); -------------------------------------------------------------------------------- /Practice Problems/Oddcharacters.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bibhuti9/DSA-leetCode-JavaScript-Solution/HEAD/Practice Problems/Oddcharacters.class -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Leet Code Problem in JavaScript 2 | 3 | If you find some bug or found more optimal solution, fork it and open a pull request thank you.. 4 | Happy Coding 5 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Medium/61. Rotate List.js: -------------------------------------------------------------------------------- 1 | /* This question is not solved */ 2 | 3 | function ListNode(val, next) { 4 | this.val = (val === undefined ? 0 : val) 5 | this.next = (next === undefined ? null : next) 6 | } 7 | ListNode(20); -------------------------------------------------------------------------------- /Practice Problems/first_and_last_possition_of_a_sortes_array.js: -------------------------------------------------------------------------------- 1 | function find_first_last_possition_a_sorted_array(arr) { 2 | console.log(arr.length); 3 | } 4 | find_first_last_possition_a_sorted_array([0, 0, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5]) -------------------------------------------------------------------------------- /Practice Problems/leanerSearch.js: -------------------------------------------------------------------------------- 1 | function leanerSearch(arr, target) { 2 | for (let i = 0; i < arr.length; i++) { 3 | if (arr[i] == target) { 4 | return i; 5 | } 6 | } 7 | return -1; 8 | } 9 | leanerSearch([]); -------------------------------------------------------------------------------- /Practice Problems/unique_element_in_array.js: -------------------------------------------------------------------------------- 1 | function unique_element(arr) { 2 | let tmp = arr[0]; 3 | for (let i = 1; i < arr.length; i++) { 4 | tmp = tmp ^ arr[i]; 5 | console.log(tmp); 6 | } 7 | } 8 | unique_element([1, 2, 4, 3, 2, 1, 3,]); 9 | -------------------------------------------------------------------------------- /Practice Problems/tralling_zero.js: -------------------------------------------------------------------------------- 1 | /* This question is not solved */ 2 | 3 | 4 | function trailling_zero(arr) { 5 | var start = 0; 6 | for (let i = 1; i < arr.length; i++) { 7 | 8 | } 9 | console.log(arr); 10 | } 11 | trailling_zero([0, 1, 0, 0, 1, 1, 0, 1]); -------------------------------------------------------------------------------- /Practice Problems/roted_array.js: -------------------------------------------------------------------------------- 1 | function rotted_array(arr) { 2 | for (let i = 0; i < arr.length; i++) { 3 | console.log(`${arr[i]} % 2 = ${arr[i] % 2}`); 4 | } 5 | } 6 | rotted_array([11, 12, 13, 14, 15]); 7 | 8 | [11, 12, 13, 14, 15] 9 | [0, 1, 2, 3, 4] 10 | 11 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Practice Problems/bubbleSort.java: -------------------------------------------------------------------------------- 1 | boolean swapped = false; 2 | for(int j=arr.length-1; j>=0 && swapped; j--) 3 | { 4 | swapped = true; 5 | for(int k=0; k < j; k++) 6 | { 7 | if(arr[k] > arr[k+1]) 8 | { 9 | int temp = arr[k]; 10 | arr[k] = arr[k+1]; 11 | arr[k+1] = temp; 12 | swapped = false; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Practice Problems/string_palindrom.js: -------------------------------------------------------------------------------- 1 | function string_palindrom(s) { 2 | let pointer = s.length - 1; 3 | for (let i = 0; i < s.length / 2; i++, pointer--) { 4 | if (s[i] != s[pointer]) { 5 | return false; 6 | } 7 | } 8 | return true; 9 | } 10 | console.log(string_palindrom("MOM")) -------------------------------------------------------------------------------- /Easy/389. Find the Difference.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} t 4 | * @return {character} 5 | */ 6 | var findTheDifference = function (s, t) { 7 | let str = t; 8 | 9 | for (let i = 0; i < s.length; i++) { 10 | str = str.replace(s[i], ''); 11 | } 12 | 13 | return str; 14 | }; -------------------------------------------------------------------------------- /.idea/leet code.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Practice Problems/Prime_Number.js: -------------------------------------------------------------------------------- 1 | function PrimeNumber(range) { 2 | 3 | for (let number = 1; number < range; number++) { 4 | 5 | if (number % 2 == 0 || number % 3 == 0) { 6 | // console.log(`Not Prime Number ${number}`); 7 | } 8 | else { 9 | console.log(`Prime number ${number}`); 10 | } 11 | } 12 | } 13 | PrimeNumber(20); -------------------------------------------------------------------------------- /Easy/414. Third Maximum Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var thirdMax = function (nums) { 6 | nums.sort((a, b) => { return b - a }); 7 | var set = new Set(nums); 8 | nums = [...set]; 9 | return nums[2] === undefined ? nums[0] : nums[2]; 10 | 11 | }; 12 | 13 | console.log(thirdMax([3, 2, 1, 4])); 14 | console.log(thirdMax([2, 2, 3, 1])); 15 | -------------------------------------------------------------------------------- /Easy/509. Fibonacci Number.js: -------------------------------------------------------------------------------- 1 | /* 2 | 509. Fibonacci Number 3 | https://leetcode.com/problems/fibonacci-number/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY O(N) */ 8 | 9 | /** 10 | * @param {number} n 11 | * @return {number} 12 | */ 13 | var fib = function (n) { 14 | if (n == 0) return 0; // 1 Base case. 15 | if (n == 1) return 1; // 2 Base case. 16 | return fib(n - 1) + fib(n - 2); 17 | }; 18 | console.log(fib(1)); -------------------------------------------------------------------------------- /Practice Problems/bubbleSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(arr, array_size) { 2 | let i, j, value; 3 | for (i = 1; i < arr.length; i++) { 4 | value = arr[i]; 5 | j = i; 6 | while ((j > 0) && (arr[j - 1] > value)) { 7 | arr[j] = arr[j - 1]; 8 | j = j - 1; 9 | 10 | } 11 | arr[j] = value; 12 | } 13 | return value; 14 | } 15 | console.log(insertionSort([10, 9, 7, 6, 5, 4, 3, 8, 2, 1])); -------------------------------------------------------------------------------- /Practice Problems/stack/nextSmallerElement.js: -------------------------------------------------------------------------------- 1 | function nextSmallerElement(array) { 2 | var stack = [-1]; 3 | for (let i = array.length - 1; i >= 0; i--) { 4 | var current = array[i]; 5 | while (stack[stack.length - 1] >= current) { 6 | stack.pop(); 7 | } 8 | array[i] = stack[stack.length - 1]; 9 | stack.push(current) 10 | } 11 | console.log(array); 12 | } 13 | nextSmallerElement([2, 1, 4, 3]); -------------------------------------------------------------------------------- /Easy/66. Plus One.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | https://leetcode.com/problems/plus-one/discuss/2407481/easy-java-script-solution-with-time-complexity-o1z 4 | 5 | */ 6 | 7 | /** 8 | * @param {number[]} digits 9 | * @return {number[]} 10 | */ 11 | var plusOne = function (digits) { 12 | var num = digits.join("") 13 | num = BigInt(num) + BigInt(1); 14 | return num.toString().split(""); 15 | }; 16 | console.log(plusOne([6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3])); -------------------------------------------------------------------------------- /Practice Problems/Oddcharacters.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | class Oddcharacters { 4 | public static void main(String[] ar) { 5 | 6 | Scanner sc = new Scanner(System.in); 7 | String s = sc.next(); 8 | for (int i = 0; i < s.length(); i++) { 9 | if (i % 2 == 0) { 10 | System.out.print(s.charAt(i)); 11 | } else { 12 | System.out.print(" "); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Practice Problems/stack/allOperation.js: -------------------------------------------------------------------------------- 1 | class Stack { 2 | constructor() { 3 | this.item = []; 4 | } 5 | add(element) { 6 | this.item.push(element); 7 | } 8 | remove() { 9 | this.item.pop(); 10 | } 11 | printStack() { 12 | return this.item; 13 | } 14 | } 15 | 16 | var stack = new Stack(); 17 | stack.add(10); 18 | stack.add(30); 19 | stack.add(60); 20 | console.log(stack.printStack()); 21 | stack.remove(); 22 | console.log(stack.printStack()); -------------------------------------------------------------------------------- /Practice Problems/stack/removeMiddleElement.js: -------------------------------------------------------------------------------- 1 | function removeMiddle(stack, count, size) { 2 | if (count === Math.floor(stack.length / 2) + 1) { 3 | stack.pop(); 4 | return; 5 | } 6 | 7 | var num = stack[stack.length - 1]; 8 | stack.pop(); 9 | removeMiddle(stack, count + 1, size); 10 | stack.push(num); 11 | if (stack.length + 1 == size) { 12 | console.log(stack); 13 | } 14 | } 15 | var stack = [1, 2, 3, 4]; 16 | removeMiddle(stack, 0, stack.length); -------------------------------------------------------------------------------- /Easy/700. Search in a Binary Search Tree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @param {number} val 12 | * @return {TreeNode} 13 | */ 14 | var searchBST = function (root, val) { 15 | 16 | }; 17 | searchBST([4, 2, 7, 1, 3], 2) -------------------------------------------------------------------------------- /Practice Problems/Find_Pivot_Element_From_Roted_sorted_array.js: -------------------------------------------------------------------------------- 1 | function find_pivot_element_in_a_sorted_roted_array(arr) { 2 | let first = 0; 3 | let last = arr.length - 1; 4 | while (first < last) { 5 | let mid = Math.floor((first + last) / 2); 6 | if (arr[mid] >= arr[0]) { 7 | first = mid + 1; 8 | } else { 9 | last = mid; 10 | } 11 | } 12 | return first; 13 | } 14 | console.log(find_pivot_element_in_a_sorted_roted_array([4, 5, 6, 7, 0, 1, 2])) -------------------------------------------------------------------------------- /Hard/123. Best Time to Buy and Sell Stock III.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxProfit(int[] prices) { 4 | int fb = Integer.MIN_VALUE, sb = Integer.MIN_VALUE; 5 | int fs = 0, ss = 0; 6 | 7 | for (int i = 0; i < prices.length; i++) { 8 | fb = Math.max(fb, -prices[i]); 9 | fs = Math.max(fs, fb + prices[i]); 10 | 11 | sb = Math.max(sb, fs - prices[i]); 12 | ss = Math.max(ss, sb + prices[i]); 13 | } 14 | return ss; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Practice Problems/stack/insertElementAtBottom.js: -------------------------------------------------------------------------------- 1 | /* Insert Element At Bottom Of the Stack */ 2 | 3 | function insertElementAtBotton(stack, count, size, desiredElement) { 4 | 5 | if (count === size) { 6 | return; 7 | } 8 | var num = stack[stack.length - 1]; 9 | console.log(stack.join(" ")); 10 | stack.pop(); 11 | insertElementAtBotton(stack, count + 1, size, desiredElement); 12 | stack.push(num); 13 | console.log(stack.join(" ")); 14 | } 15 | 16 | var stack = [1, 2, 3, 4]; 17 | insertElementAtBotton(stack, 0, stack.length, 9); -------------------------------------------------------------------------------- /Medium/189. Rotate Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 189. Rotate Array 3 | https://leetcode.com/problems/rotate-array/ 4 | */ 5 | 6 | /** 7 | * @param {number[]} nums 8 | * @param {number} k 9 | * @return {void} Do not return anything, modify nums in-place instead. 10 | */ 11 | var rotate = function (nums, k) { 12 | var ansArray = []; // Create an array 13 | for (let i = 0; i < nums.length; i++) { 14 | ansArray[((i + k) % nums.length)] = nums[i]; // Math Login 15 | } 16 | return nums = ansArray; 17 | }; 18 | console.log(rotate([1, 2, 3, 4, 5, 6, 7], 3)); -------------------------------------------------------------------------------- /Easy/231. Power of Two.js: -------------------------------------------------------------------------------- 1 | /* 2 | 231. Power of Two 3 | https://leetcode.com/problems/power-of-two/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {number} n 10 | * @return {boolean} 11 | */ 12 | 13 | var isPowerOfTwo = function (n) { 14 | if (n <= 0) return false; 15 | while (n > 1) { 16 | n /= 2; // Here Java Script always return decimal value if the number is odd 17 | } 18 | return n === 1; // if the number is odd then then number n never became 1 because java script return odd for decimal values; 19 | }; 20 | console.log(isPowerOfTwo(8)); -------------------------------------------------------------------------------- /Practice Problems/occurences_of_a_character_in_a_string.js: -------------------------------------------------------------------------------- 1 | function occurence(s) { 2 | var map = new Map(); 3 | for (let i = 0; i < s.length; i++) { 4 | if (map.has(s[i])) { 5 | map.set(s[i], map.get(s[i]) + 1); 6 | } else { 7 | map.set(s[i], 1); 8 | } 9 | } 10 | console.log(map); 11 | } 12 | occurence("chocolateeeeeehhttfervtfy"); 13 | /* 14 | Map(11) { 15 | 'c' => 2, 16 | 'h' => 3, 17 | 'o' => 2, 18 | 'l' => 1, 19 | 'a' => 1, 20 | 't' => 4, 21 | 'e' => 7, 22 | 'f' => 2, 23 | 'r' => 1, 24 | 'v' => 1, 25 | 'y' => 1 26 | } 27 | 28 | */ -------------------------------------------------------------------------------- /Easy/202. Happy Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {boolean} 4 | */ 5 | 6 | function recursion(num) { 7 | var count = 0; 8 | while (num != 0) { 9 | count += Math.floor((num % 10) * (num % 10)); 10 | num = Math.floor(num / 10); 11 | } 12 | return count; 13 | } 14 | var isHappy = function (n) { 15 | var hashMap = new Set(); 16 | 17 | while (!hashMap.has(n)) { 18 | n = recursion(n); 19 | console.log(n); 20 | if (n == 1) { 21 | return true; 22 | } 23 | hashMap.add(n); 24 | } 25 | return false; 26 | }; 27 | console.log(isHappy(19)); -------------------------------------------------------------------------------- /Medium/56. Merge Intervals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} intervals 3 | * @return {number[][]} 4 | */ 5 | var merge = function (intervals) { 6 | var ansArr = [[]]; 7 | for (let i = 0; i < intervals.length - 1; i++) { 8 | 9 | if (intervals[i][0] >= intervals[i + 1][0]) { 10 | intervals[i][0] = intervals[i + 1][0]; 11 | intervals.splice(i + 1, 1); 12 | } 13 | else if (intervals[i][1] >= intervals[i + 1][0]) { 14 | intervals[i][1] = intervals[i + 1][1]; 15 | intervals.splice(i + 1, 1); 16 | } 17 | } 18 | return intervals; 19 | }; 20 | merge([[1, 4], [0, 4]]); -------------------------------------------------------------------------------- /Medium/503. Next Greater Element II.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | 6 | 7 | var nextGreaterElements = function (nums) { 8 | var stack = []; 9 | for (let i = nums.length - 1; i > 0; i--) { 10 | stack.push(nums[i]); 11 | } 12 | for (let i = 0; i < nums.length; i++) { 13 | while (stack[stack.length - 1] <= nums[i]) { 14 | stack.pop(); 15 | } 16 | if (stack.length <= 0) { 17 | nums[i] = -1; 18 | } else { 19 | nums[i] = stack[stack.length - 1]; 20 | } 21 | } 22 | console.log(nums); 23 | }; 24 | nextGreaterElements([1, 2, 1]); -------------------------------------------------------------------------------- /Easy/26. Remove Duplicates from Sorted Array.js: -------------------------------------------------------------------------------- 1 | function removeDuplicates(nums) { 2 | return Array.from(new Set(nums)); 3 | }; 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | 10 | /* TIME COMPLEXITY O(N) */ 11 | 12 | // nums is sorted in non-decreasing order. 13 | 14 | var removeDuplicates = function (nums) { 15 | for (let i = 0; i < nums.length; i++) { 16 | if (nums[i] === nums[i + 1]) { // If the next element is same than remove from the array 17 | nums.splice(i, 1); 18 | i--; 19 | } 20 | } 21 | return nums.length; 22 | }; 23 | 24 | console.log(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])); -------------------------------------------------------------------------------- /Hard/123. Best Time to Buy and Sell Stock III.js: -------------------------------------------------------------------------------- 1 | /* This question is solved but by mathmatically */ 2 | 3 | /** 4 | * @param {number[]} prices 5 | * @return {number} 6 | */ 7 | var maxProfit = function (prices) { 8 | var fb = Number.MIN_VALUE, sb = Number.MIN_VALUE; 9 | var fs = 0, ss = 0; 10 | for (let i = 0; i < prices.length; i++) { 11 | fb = Math.max(fb, -prices[i]); 12 | fs = Math.max(fs, parseInt(fb) + parseInt(prices[i])); 13 | 14 | sb = Math.max(sb, parseInt(fs) - parseInt(prices[i])); 15 | ss = Math.max(ss, parseInt(sb) + parseInt(prices[i])); 16 | } 17 | return ss; 18 | }; 19 | 20 | console.log(maxProfit([3, 3, 5, 0, 0, 3, 1, 4])); -------------------------------------------------------------------------------- /Practice Problems/kth_window _sum.js: -------------------------------------------------------------------------------- 1 | // 1 2 | // 12 3 | // 123 4 | // 1234 5 | // 12345 6 | // 123456 7 | 8 | // 2 9 | // 23 10 | // 234 11 | // 2345 12 | // 23456 13 | 14 | // .... 15 | // 5 16 | // 56 17 | 18 | // 6 19 | function windowSum(arr, target) { 20 | let s = 0; 21 | let sum = 0; 22 | for (let i = 0; i < arr.length; i++) { 23 | sum = 0; 24 | for (let j = s; j <= i; j++) { 25 | sum += arr[j]; 26 | } 27 | if (i == arr.length - 1) { 28 | i = s; 29 | s++; 30 | } 31 | if (sum == target) { 32 | return "true"; 33 | } 34 | } 35 | return "false"; 36 | } 37 | 38 | 39 | console.log(windowSum([1, 2, 3, 4, 5, 6], 100)); -------------------------------------------------------------------------------- /Easy/21. Merge Two Sorted Lists.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @param { ListNode } list1 3 | * @param {ListNode} list2 4 | * @return {ListNode} 5 | */ 6 | var mergeTwoLists = function (list1, list2) { 7 | /* THIS SOLUTION FOR ARRAY ONLY IF THE LIST1 AND LIST2 ARE ARRAY WE CAN USE BELLOW METHOD 8 | 9 | return list1.concat(list2).sort((a, b) => { return a - b }); 10 | */ 11 | 12 | /* THIS METHOD IS USED FOR ONLY LINKED LIST */ 13 | if (list1 === null) { return list2; } 14 | else if (list2 === null) { return list1; } 15 | else if (list2.val < list1.val) { [list1, list2] = [list2, list1]; } 16 | 17 | list1.next = mergeTwoLists(list1.next, list2); 18 | return list1; 19 | }; 20 | console.log(mergeTwoLists([1, 2, 4], [1, 3, 4])); -------------------------------------------------------------------------------- /Practice Problems/reverse_array.js: -------------------------------------------------------------------------------- 1 | /* Reverse Array Using Two Pointer */ 2 | 3 | /* TIME COMPLEXITY O(LogN) */ 4 | 5 | function reverse_array(arr) { 6 | for (let i = 0; i < Math.floor(arr.length / 2); i++) { 7 | tmp = arr[i]; 8 | arr[i] = arr[(arr.length - 1) - i]; 9 | arr[(arr.length - 1) - i] = tmp; 10 | } 11 | console.log(arr); 12 | } 13 | 14 | function reverse_Array_With_Mth_Index(arr, m) { 15 | let end = arr.length - 1; 16 | for (let i = m; i < arr.length; i++, end--) { 17 | tmp = arr[i]; 18 | arr[i] = arr[end]; 19 | arr[(arr.length - 1) - i] = tmp; 20 | } 21 | console.log(arr); 22 | } 23 | reverse_Array_With_Mth_Index([10, 9, 8, 7, 6], 2); 24 | // reverse_array([11, 7, 3, 12, 4, 5, 8, 10]); -------------------------------------------------------------------------------- /Easy/67. Add Binary.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} a 3 | * @param {string} b 4 | * @return {string} 5 | */ 6 | function convertBinary(num) { 7 | var binary = []; 8 | while (num != 0) { 9 | binary.push(num % 2); 10 | num = Math.floor(num / 2); 11 | } 12 | return binary.reverse().join(""); 13 | } 14 | var addBinary = function (a, b) { 15 | 16 | a = convertBinary(a); 17 | b = convertBinary(b); 18 | 19 | console.log(a); 20 | console.log(b); 21 | 22 | // var dec = Number(parseInt(a, 2)) + Number(parseInt(b, 2)); 23 | // console.log("the number a is " + parseInt(a, 2)); 24 | // console.log("the number b is " + parseInt(b, 2)); 25 | // console.log("the dec is " + dec); 26 | // return dec.toString(2); 27 | 28 | }; 29 | console.log(addBinary(11, 1)); -------------------------------------------------------------------------------- /Easy/2351. First Letter to Appear Twice.js: -------------------------------------------------------------------------------- 1 | /* 2 | 2351. First Letter to Appear Twice 3 | https://leetcode.com/problems/first-letter-to-appear-twice/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {string} s 10 | * @return {character} 11 | */ 12 | 13 | var repeatedCharacter = function (s) { 14 | const set = new Set(); // Create a set which contain all the distinct values 15 | for (let i = 0; i < s.length; i++) { 16 | if (set.has(s[i])) { // check if the string Ith value exists in the set or not 17 | return s[i]; // return the string Ith value if set has that value. 18 | } else { 19 | set.add(s[i]); // if the value does not exists in the set add that value 20 | } 21 | } 22 | }; 23 | console.log(repeatedCharacter("abccbaacz")); -------------------------------------------------------------------------------- /Easy/1047. Remove All Adjacent Duplicates In String.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1047. Remove All Adjacent Duplicates In String 3 | https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {string} s 10 | * @return {string} 11 | */ 12 | var removeDuplicates = function (s) { 13 | let arrStack = [] // Create a stack whic contain non-repeate element 14 | for (const ch of s) { 15 | if (arrStack.length && arrStack[arrStack.length - 1] === ch) // If the stack top elemt is match to the string character then remove that top element. 16 | arrStack.pop() 17 | else arrStack.push(ch) // if not match add to the array. 18 | } 19 | return arrStack.join('') 20 | }; 21 | 22 | console.log(removeDuplicates("aababaab")); -------------------------------------------------------------------------------- /Easy/496. Next Greater Element I.js: -------------------------------------------------------------------------------- 1 | /* 2 | 496. Next Greater Element I 3 | https://leetcode.com/problems/next-greater-element-i/ 4 | */ 5 | 6 | /** 7 | * @param {number[]} nums1 8 | * @param {number[]} nums2 9 | * @return {number[]} 10 | */ 11 | var nextGreaterElement = function (nums1, nums2) { 12 | let i = 0, j = 0, numToPush; 13 | for (i = 0; i < nums1.length; i++) { 14 | j = nums2.indexOf(nums1[i]); // Find the nums1 current value index in nums2 array 15 | numToPush = -1; 16 | for (j = j + 1; j < nums2.length; j++) { 17 | if (nums2[j] > nums1[i]) { 18 | numToPush = nums2[j]; 19 | break; 20 | } 21 | } 22 | nums1[i] = numToPush; 23 | } 24 | return nums1; 25 | }; 26 | console.log(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])); -------------------------------------------------------------------------------- /Easy/242. Valid Anagram.js: -------------------------------------------------------------------------------- 1 | /* 2 | 242. Valid Anagram 3 | https://leetcode.com/problems/valid-anagram/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {string} s 10 | * @param {string} t 11 | * @return {boolean} 12 | */ 13 | var isAnagram = function (s, t) { 14 | if (s.length > t.length) return false; // If the s length is greater then t length 15 | var hasMap = s.split(""); // Convert the string to array 16 | for (let i = 0; i < t.length; i++) { 17 | if (hasMap.includes(t[i])) { // check if the t index value is exists in hasMap or not 18 | hasMap.splice(hasMap.indexOf(t[i]), 1); // If t index value is exists then delete that particular value 19 | } else { 20 | return false; // return false if the t index value does not exists in hapMap 21 | } 22 | } 23 | return true; 24 | }; 25 | console.log(isAnagram("ab", "a")); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Problem Solutions in JavaScript 2 | This repository contains my solutions to various LeetCode problems in JavaScript. 3 | 4 | ## Getting Started 5 | To run the code and test the solutions 6 | 7 | 1. Download Node.js 8 | 9 | 10 | ## Clone the repository to your local machine using 11 | 12 | 1. git clone https://github.com/bibhuti9/DSA-leetCode-JavaScript-Solution.git 13 | 14 | 15 | Each problem solution is located in its own file, with the name of the directory matching the LeetCode problem name. Within each directory, you will find the solution code, along with any additional files or notes. 16 | 17 | ## Contributing 18 | If you would like to contribute to this repository, please open a pull request with your proposed changes. All contributions are welcome! 19 | 20 | ## Feel free to add your solution with different languages 21 | 22 | License 23 | This repository is licensed under the **MIT License**. 24 | -------------------------------------------------------------------------------- /Medium/220. Contains Duplicate III.js: -------------------------------------------------------------------------------- 1 | /* 2 | 220. Contains Duplicate III 3 | https://leetcode.com/problems/contains-duplicate-iii/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @param {number} k 11 | * @param {number} t 12 | * @return {boolean} 13 | */ 14 | var containsNearbyAlmostDuplicate1 = function (nums, k, t) { 15 | var start = 0; // Make a pointer which is start from 0 16 | for (let j = 1; j < nums.length; j++) { 17 | if (Math.abs(nums[start] - nums[j]) <= t && (Math.abs(start - j) <= k)) { // check the given condition 18 | return true; 19 | } 20 | if (j === nums.length - 1) { // check when the j is equal to the nums length we increment the staty and modify the Ith value 21 | j = ++start; 22 | } 23 | } 24 | return false; 25 | }; 26 | 27 | console.log(containsNearbyAlmostDuplicate1([1, 5, 9, 1, 5, 9], 2, 3)); -------------------------------------------------------------------------------- /Easy/268. Missing Number.js: -------------------------------------------------------------------------------- 1 | /* 2 | 268. Missing Number 3 | https://leetcode.com/problems/missing-number/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @return {number} 11 | */ 12 | //Method 1 13 | var missingNumber = function (nums) { 14 | var set = new Set(nums); // Create a set which contain only 15 | for (let i = 0; i <= nums.length; i++) { 16 | if (!set.has(i)) { // check if the ith possition value exists in set or not 17 | return i; 18 | } 19 | } 20 | }; 21 | 22 | //Method 2 23 | var missingNumber2 = function (nums) { 24 | var set = new Set(nums); 25 | var totalSum = nums.length * (nums.length + 1) / 2; 26 | var totalCount = 0; 27 | for (let i = 0; i < nums.length; i++) { 28 | totalCount += nums[i]; 29 | } 30 | return totalSum - totalCount; 31 | }; 32 | 33 | console.log(missingNumber2([9, 6, 4, 2, 3, 5, 7, 0, 1])); -------------------------------------------------------------------------------- /Easy/392. Is Subsequence.js: -------------------------------------------------------------------------------- 1 | /* 2 | 392. Is Subsequence 3 | https://leetcode.com/problems/is-subsequence/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /* 9 | 10 | Example 1: 11 | 12 | Input: s = "abc", t = "ahbgdc" 13 | Output: true 14 | Example 2: 15 | 16 | Input: s = "axc", t = "ahbgdc" 17 | Output: false 18 | 19 | */ 20 | 21 | /** 22 | * @param {string} s 23 | * @param {string} t 24 | * @return {boolean} 25 | */ 26 | var isSubsequence = function (s, t) { 27 | let Sindex = 0; // Sindex for s string which is start from 0 28 | for (let j = 0; j < t.length; j++) { 29 | if (s[Sindex] == t[j]) { // here we check if s of Sindex i sequal to t of j index then increment Sindex by one 30 | Sindex++ 31 | } 32 | } 33 | return s.length == Sindex; // If s.length is equal to Sindex then it's true or false. 34 | }; 35 | 36 | console.log(isSubsequence("axc", "ahbgdc")); 37 | console.log(isSubsequence("abc", "ahbgdc")) 38 | -------------------------------------------------------------------------------- /Easy/344. Reverse String.js: -------------------------------------------------------------------------------- 1 | /* 2 | 344. Reverse String 3 | https://leetcode.com/problems/reverse-string/ 4 | */ 5 | 6 | /* TIME COMPLEXITY o(LogN) */ 7 | 8 | 9 | /* 10 | Example 1: 11 | 12 | Input: s = ["h","e","l","l","o"] 13 | Output: ["o","l","l","e","h"] 14 | Example 2: 15 | 16 | Input: s = ["H","a","n","n","a","h"] 17 | Output: ["h","a","n","n","a","H"] 18 | */ 19 | 20 | /** 21 | * @param {character[]} s 22 | * @return {void} Do not return anything, modify s in-place instead. 23 | */ 24 | var reverseString = function (s) { 25 | let pointer = s.length - 1; // Make a pointer which is start from length 26 | for (let i = 0; i < s.length / 2; i++, pointer--) { // Devide the total length to length/2 27 | let tmp = s[i]; // Swap the current Ith index to pointer index 28 | s[i] = s[pointer]; 29 | s[pointer] = tmp; 30 | } 31 | return s; // return the s 32 | }; 33 | console.log(reverseString(["H", "a", "n", "n", "a", "h"])); 34 | -------------------------------------------------------------------------------- /Easy/283. Move Zeroes.js: -------------------------------------------------------------------------------- 1 | /* 2 | 283. Move Zeroes 3 | https://leetcode.com/problems/move-zeroes/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /* 9 | 10 | Example 1: 11 | 12 | Input: nums = [0,1,0,3,12] 13 | Output: [1,3,12,0,0] 14 | Example 2: 15 | 16 | Input: nums = [0] 17 | Output: [0] 18 | 19 | */ 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @return {void} Do not return anything, modify nums in-place instead. 24 | */ 25 | var moveZeroes = function (nums) { 26 | var start = 0; // Make a pointer which is start from 0 27 | for (let i = 0; i < nums.length; i++) { 28 | if (nums[i] != 0) { // check that the ith value does not equal to zero 29 | let tmp = nums[i]; 30 | nums[i] = nums[start]; // Swap the elements 31 | nums[start] = tmp; 32 | start++; // Increase the start pointer by 1 33 | } 34 | } 35 | return nums; // return the nums array 36 | }; 37 | 38 | console.log(moveZeroes([3, 5, 0, 0, 4])) -------------------------------------------------------------------------------- /Easy/485. Max Consecutive Ones.js: -------------------------------------------------------------------------------- 1 | /* 2 | 485. Max Consecutive Ones 3 | https://leetcode.com/problems/max-consecutive-ones/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @return {number} 11 | */ 12 | var findMaxConsecutiveOnes = function (nums) { 13 | var max = 0; // Create a max which contain recent count 1 value 14 | var maxSoFar = 0; // Create a maxSoFar which contain heighest max value 15 | for (let i = 0; i < nums.length; i++) { 16 | if (nums[i] === 1) { // if the current value is 1 increment the max 17 | max++; 18 | } else { 19 | if (max > maxSoFar) { // when the max is greater then the mazSoFar modify the maxSoFar 20 | maxSoFar = max; 21 | } 22 | max = 0; // When the condition is false modify the max to 0 23 | } 24 | } 25 | return max > maxSoFar ? max : maxSoFar; // Here If the max greater then the maxSoFar return max else maxSoFae 26 | }; 27 | console.log(findMaxConsecutiveOnes([1, 0, 1, 1, 0, 1])); -------------------------------------------------------------------------------- /Easy/219. Contains Duplicate II.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {boolean} 5 | */ 6 | 7 | /* TIME COMPLEXITY O(N) */ 8 | 9 | var containsNearbyDuplicate = function (nums, k) { 10 | var map = new Map(); // Create a map to store occurences of the index value 11 | for (let i = 0; i < nums.length; i++) { 12 | if (map.has(nums[i])) { // check that if the index value exists in the map or not 13 | let firstIndex = map.get(nums[i]); // if the map contain the nums Ith value than find the index of that value in the map 14 | if (Math.abs(i - firstIndex) <= k) { 15 | return true; 16 | } else { 17 | map.set(nums[i], i); // if the condition is not true update the index value to the Ith index value 18 | } 19 | } else { 20 | map.set(nums[i], i); // set the Ith value into the map 21 | } 22 | } 23 | return false; // return false if any of condition is not true. 24 | }; 25 | 26 | console.log(containsNearbyDuplicate([1, 2, 3, 1, 2, 3], 2)); -------------------------------------------------------------------------------- /Easy/15. 3Sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var threeSum = function (nums) { 6 | nums.sort((a, b) => a - b); 7 | 8 | let res = []; 9 | for (let i = 0; i < nums.length - 2; i++) { 10 | 11 | // skipping the duplicate elements 12 | if (i > 0 && nums[i] == nums[i - 1]) continue; 13 | let j = i + 1; 14 | let k = nums.length - 1; 15 | 16 | // Two sum approach 17 | while (j < k) { 18 | let sum = nums[j] + nums[k]; 19 | 20 | if (sum == -nums[i]) { 21 | res.push([nums[i], nums[j], nums[k]]); 22 | // skipping the duplicate elements 23 | while (nums[j] == nums[j + 1]) j++; 24 | while (nums[k] == nums[k - 1]) k--; 25 | k--; 26 | j++; 27 | } 28 | else if (sum > -nums[i]) { 29 | k--; 30 | } 31 | else { 32 | j++; 33 | } 34 | } 35 | } 36 | return res; 37 | }; 38 | 39 | console.log(threeSum([-1, 0, 1, 2, -1, -4])); 40 | -------------------------------------------------------------------------------- /Easy/27. Remove Element.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | https://leetcode.com/problems/roman-to-integer/discuss/2396171/easy-java-script-solution-using-hashmap-with-explanation-on 4 | 5 | https://leetcode.com/problems/remove-element/discuss/2396677/java-script-solution-on2-and-on-two-time-complexity-solution 6 | 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @param {number} val 12 | * @return {number} 13 | */ 14 | 15 | /* 16 | * METHOD 1 * 17 | TIME COMPLEXITY O(N2) 18 | 19 | */ 20 | var removeElement = function (nums, val) { 21 | for (var i = 0; i < nums.length; i++) { 22 | if (nums[i] === val) { 23 | nums.splice(i, 1); 24 | i--; 25 | } 26 | } 27 | return nums.length; 28 | }; 29 | 30 | /* 31 | * METHOD 2 * 32 | TIME COMPLEXITY O(N) 33 | 34 | */var removeElement = function (nums, val) { 35 | var index = 0; 36 | for (var i = 0; i < nums.length; i++) { 37 | if (nums[i] != val) { 38 | nums[index++] = nums[i]; 39 | } 40 | } 41 | return index; 42 | }; 43 | console.log(removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2)); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Bibhuti Swain 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Easy/448. Find All Numbers Disappeared in an Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 448. Find All Numbers Disappeared in an Array 3 | https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 4 | */ 5 | 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number[]} 10 | */ 11 | 12 | 13 | /* 14 | Method 1 TIME COMPEXITY O(N) 15 | */ 16 | var findDisappearedNumbers = function (nums) { 17 | var set = new Set(nums); // make a set 18 | var ansArray = []; // create a extra array which store the ans array 19 | for (let i = 1; i <= nums.length; i++) { 20 | if (!set.has(i)) { // check that if the set contain Ith element then dont't add it to the ans Array 21 | ansArray.push(i); 22 | } 23 | } 24 | return ansArray; 25 | }; 26 | 27 | /* Method 2 TIME COMPLEXITY O(N) */ 28 | 29 | var findDisappearedNumbers2 = function (nums) { 30 | var ansArray = []; 31 | for (let i = 1; i <= nums.length; i++) { 32 | if (!nums.includes(i)) { 33 | ansArray.push(i); 34 | } 35 | } 36 | return ansArray; 37 | }; 38 | 39 | console.log(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1])); -------------------------------------------------------------------------------- /Easy/13. Roman to Integer.js: -------------------------------------------------------------------------------- 1 | /* 13. Roman to Integer 2 | https://leetcode.com/problems/roman-to-integer/ 3 | */ 4 | 5 | /* TIME COMPLEXITY IS O(N) */ 6 | 7 | /* 8 | Example 1: 9 | 10 | Input: s = "III" 11 | Output: 3 12 | Explanation: III = 3. 13 | Example 2: 14 | 15 | Input: s = "LVIII" 16 | Output: 58 17 | Explanation: L = 50, V= 5, III = 3. 18 | Example 3: 19 | 20 | Input: s = "MCMXCIV" 21 | Output: 1994 22 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 23 | */ 24 | 25 | var romanToInt = function (s) { 26 | // Create A Map 27 | const map = { 28 | 'I': 1, 29 | 'V': 5, 30 | 'X': 10, 31 | 'L': 50, 32 | 'C': 100, 33 | 'D': 500, 34 | 'M': 1000 35 | } 36 | let ans = 0; 37 | for (let i = 0; i < s.length; i++) { 38 | const cur = map[s[i]], next = map[s[i + 1]]; 39 | //check that the current indext value is smaller than the next index value or not if the current value smaller than next value return current value as minus(-) value. 40 | ans += cur < next ? -cur : cur; 41 | } 42 | return ans; 43 | }; 44 | romanToInt("MCMXCIV"); 45 | //Input :MCMXCIV 46 | //Output:1994 -------------------------------------------------------------------------------- /Medium/532. K-diff Pairs in an Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 532. K-diff Pairs in an Array 4 | https://leetcode.com/problems/k-diff-pairs-in-an-array/discuss/?currentPage=1&orderBy=hot&query= 5 | 6 | */ 7 | 8 | /** 9 | * @param {number[]} nums 10 | * @param {number} k 11 | * @return {number} 12 | */ 13 | // 0 <= i, j < nums.length 14 | // i != j 15 | // nums[i] - nums[j] == k 16 | 17 | var findPairs = function (nums, k) { 18 | var map = new Map(); // we make a map to store key pair index value 19 | var length = nums.length; 20 | for (let i = 0; i < nums.length; i++) { 21 | for (let j = i; j < nums.length; j++) { 22 | // These are the constraints 23 | if ( 24 | i >= 0 25 | && j < length 26 | && i != j 27 | && (Math.abs(nums[i] - nums[j]) === k)) { 28 | if ((!map.has(`${nums[j]}${nums[i]}`) && (!map.has(`${nums[i]}${nums[j]}`)))) { 29 | map.set(`${nums[i]}${nums[j]}`, 1); 30 | } 31 | } 32 | } 33 | } 34 | // console.log(map); 35 | return map.size; 36 | }; 37 | console.log(findPairs([0, 0, 1, 0, 0], 1)); 38 | -------------------------------------------------------------------------------- /Easy/9. Palindrome Number.js: -------------------------------------------------------------------------------- 1 | /* TIME COMPLEXITY IS O(1) */ 2 | 3 | /* 4 | https://leetcode.com/problems/palindrome-number/discuss/2396146/100-fastest-solution-explained-with-java-script-o1 5 | 6 | */ 7 | 8 | /* 9 | Given an integer x, return true if x is palindrome integer. 10 | An integer is a palindrome when it reads the same backward as forward. 11 | For example, 121 is a palindrome while 123 is not. 12 | 13 | Example 1: 14 | 15 | Input: x = 121 16 | Output: true 17 | Explanation: 121 reads as 121 from left to right and from right to left. 18 | Example 2: 19 | 20 | Input: x = -121 21 | Output: false 22 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 23 | Example 3: 24 | 25 | Input: x = 10 26 | Output: false 27 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 28 | */ 29 | 30 | /** 31 | * @param {number} x 32 | * @return {boolean} 33 | */ 34 | var isPalindrome = function (x) { 35 | var rev = x.toString().split("").reverse().join(""); //-121 36 | var ans = false; 37 | if (x == rev) { 38 | ans = true; 39 | } 40 | return ans; 41 | }; 42 | console.log(isPalindrome(-121)); -------------------------------------------------------------------------------- /Easy/Majority Element.js: -------------------------------------------------------------------------------- 1 | /* 2 | 169. Majority Element 3 | https://leetcode.com/problems/majority-element/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /* 9 | Example 1: 10 | 11 | Input: nums = [3,2,3] 12 | Output: 3 13 | Example 2: 14 | 15 | Input: nums = [2,2,1,1,1,2,2] 16 | Output: 2 17 | 18 | */ 19 | 20 | var majorityElement = function (nums) { 21 | var map = new Map(); //Create A New HashMap 22 | 23 | console.log(map); 24 | for (let i = 0; i < nums.length; i++) { // 0 - nums.length value 25 | if (map.has(nums[i])) { //Check Array Single Element Present in Map or not 26 | map.set(nums[i], map.get(nums[i]) + 1); //If Element present in Map than increment key:value number By One 27 | } 28 | else { 29 | map.set(nums[i], 1); //If the element not present in map than add into the map 30 | } 31 | } 32 | console.log(map); 33 | let max = Math.max(...map.values()); // Find the maximum value in map 34 | for (var [key, value] of map.entries()) { // Check Max Value Key 35 | if (max == value) { 36 | return key; 37 | } 38 | } 39 | }; 40 | 41 | console.log(majorityElement([3, 2, 3, 4, 5, 4, 4])); 42 | 43 | -------------------------------------------------------------------------------- /Practice Problems/linked list/linked_link_operation.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(element) { 3 | this.value = element; 4 | this.next = null; 5 | } 6 | } 7 | 8 | class LinkedList { 9 | 10 | constructor() { 11 | this.head = null; 12 | this.size = 0; 13 | } 14 | 15 | // add 16 | add(element) { 17 | var node = new Node(element); 18 | if (this.head === null) { 19 | this.head = node; 20 | } else { 21 | var current = this.head; 22 | while (current.next != null) { 23 | current = current.next; 24 | } 25 | current.next = node; 26 | } 27 | this.size++; 28 | } 29 | 30 | // removeElement 31 | removeElement(element) { 32 | 33 | } 34 | 35 | indexOf(element) { 36 | var count = 0; 37 | var current = this.head; 38 | while (current != null) { 39 | if (current.value === element) { 40 | return count; 41 | } 42 | count++; 43 | current = current.next; 44 | } 45 | return -1; 46 | } 47 | 48 | } 49 | 50 | var ll = new LinkedList(); 51 | ll.add(10); 52 | ll.add(20); 53 | console.log(Array.isArray(ll)); -------------------------------------------------------------------------------- /Medium/438. Find All Anagrams in a String.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} p 4 | * @return {number[]} 5 | */ 6 | var findAnagrams = function (s, p) { 7 | if (p.length > s.length) { 8 | return []; 9 | } 10 | 11 | var secondTargetArray = []; 12 | var targetArray = new Array(26).fill(0); 13 | var window = new Array(26).fill(0); 14 | for (let i = 0; i < p.length; i++) { 15 | targetArray[p[i].charCodeAt() - 97]++; 16 | window[s[i].charCodeAt() - 97]++; 17 | } 18 | 19 | // console.log(targetArray); 20 | // console.log(window); 21 | 22 | var targetHash = targetArray.join("#"); 23 | // console.log(fillTarget) 24 | 25 | var left = 0; 26 | var right = p.length - 1; 27 | 28 | while (right <= s.length) { 29 | var windowHash = window.join("#"); 30 | if (targetHash === windowHash) { 31 | // return true; 32 | secondTargetArray.push(left); 33 | } 34 | if (right + 1 >= s.length) { 35 | break; 36 | } 37 | 38 | right++; 39 | window[s[right].charCodeAt() - 97]++; 40 | window[s[left].charCodeAt() - 97]--; 41 | left++; 42 | } 43 | // return false; 44 | return secondTargetArray; 45 | }; -------------------------------------------------------------------------------- /Easy/1. Two Sum.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | You can return the answer in any order. 5 | 6 | */ 7 | 8 | /* 9 | https://leetcode.com/problems/two-sum/discuss/2388388/100-fastest-solution-java-script-solution-0n 10 | 11 | */ 12 | 13 | /* TIME COMPLEXITY IS O(logn) */ 14 | 15 | /* 16 | 17 | Example 1: 18 | 19 | Input: nums = [2,7,11,15], target = 9 20 | Output: [0,1] 21 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 22 | Example 2: 23 | 24 | Input: nums = [3,2,4], target = 6 25 | Output: [1,2] 26 | Example 3: 27 | 28 | Input: nums = [3,3], target = 6 29 | Output: [0,1] 30 | */ 31 | 32 | /** 33 | * @param {number[]} nums 34 | * @param {number} target 35 | * @return {number[]} 36 | */ 37 | var twoSum = function (nums, target) { 38 | return nums.map((s,i)=>{ 39 | if ((nums[s] + nums[i]) == target) { //check the pointer is equal to the target number or not 40 | return [s, i]; //return if both sum are equal to the target 41 | } 42 | }) 43 | } 44 | var nums = [3, 2, 4], target = 6; 45 | console.log(twoSum(nums, target)); 46 | -------------------------------------------------------------------------------- /Easy/Single Number.js: -------------------------------------------------------------------------------- 1 | /* 2 | 136. Single Number 3 | https://leetcode.com/problems/single-number/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY O(N)*/ 8 | 9 | /* 10 | 11 | Example 1: 12 | 13 | Input: nums = [2,2,1] 14 | Output: 1 15 | Example 2: 16 | 17 | Input: nums = [4,1,2,1,2] 18 | Output: 4 19 | Example 3: 20 | 21 | Input: nums = [1] 22 | Output: 1 23 | 24 | */ 25 | 26 | /* METHOD 1 */ 27 | var singleNumber = function (nums) { 28 | let s = 0; // Location of first possible suspect 29 | for (let i = s + 1; i < nums.length; i++) { 30 | if (nums[i] == nums[s]) { // If we found a duplicate 31 | nums.splice(i, 1); // Remove the duplicate so it won't confuse us next time we come across it 32 | s++; // Next suspect's location 33 | i = s; // Start of next search (i=s+1 in next loop iteration) 34 | } 35 | } 36 | return nums[s]; 37 | }; 38 | 39 | /* METHOD 2 */ 40 | function method2(arr) { 41 | let ans = 0; 42 | ans = arr[0]; //Assign the first element to the ans 43 | for (let i = 0; i < arr.length - 1; i++) { 44 | ans = ans ^ arr[i + 1]; // compute ans element with arr[ith] elements 45 | } 46 | return ans; 47 | 48 | } 49 | console.log(singleNumber([2, 2, 1])); 50 | console.log(method2([2, 2, 1])); -------------------------------------------------------------------------------- /Easy/1752. Check if Array Is Sorted and Rotated.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1752. Check if Array Is Sorted and Rotated 3 | https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY O(N) */ 8 | 9 | /* 10 | Example 1: 11 | 12 | Input: nums = [3,4,5,1,2] 13 | Output: true 14 | Explanation: [1,2,3,4,5] is the original sorted array. 15 | You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. 16 | Example 2: 17 | 18 | Input: nums = [2,1,3,4] 19 | Output: false 20 | Explanation: There is no sorted array once rotated that can make nums.ś 21 | 22 | */ 23 | 24 | /** 25 | * @param {number[]} nums 26 | * @return {boolean} 27 | */ 28 | var check = function (nums) { 29 | let count = 0; // Make a count veriable 30 | for (let i = 1; i < nums.length; i++) { 31 | if (nums[i - 1] > nums[i]) { // Check that if the i-1 index value should be greater then i possition value 32 | count++; 33 | } 34 | } 35 | if (nums[nums.length - 1] > nums[0]) { // this condition is basically used for to check last index value to first index value. 36 | count++; 37 | } 38 | return count <= 1; // return if the count is 0 or 1 then it will true or false. 39 | }; 40 | console.log(check([2, 1, 3, 4])); -------------------------------------------------------------------------------- /Easy/35. Search Insert Position.js: -------------------------------------------------------------------------------- 1 | /* 2 | 35. Search Insert Position 3 | https://leetcode.com/problems/search-insert-position/ 4 | 5 | https://leetcode.com/problems/search-insert-position/discuss/2403132/easy-solution-with-java-script-in-ologn 6 | */ 7 | 8 | /* TIME COMPLEXITY O( logN ) */ 9 | 10 | /* 11 | Example 1: 12 | 13 | Input: nums = [1,3,5,6], target = 5 14 | Output: 2 15 | Example 2: 16 | 17 | Input: nums = [1,3,5,6], target = 2 18 | Output: 1 19 | Example 3: 20 | 21 | Input: nums = [1,3,5,6], target = 7 22 | Output: 4 23 | 24 | */ 25 | 26 | /** 27 | * @param {number[]} nums 28 | * @param {number} target 29 | * @return {number} 30 | */ 31 | var searchInsert = function (nums, target) { 32 | let low = 0; 33 | let heigh = nums.length - 1; 34 | //Itterate loop with logN time 35 | while (low <= heigh) { 36 | let mid = Math.floor((low + heigh) / 2); 37 | if (target === nums[mid]) { // check that the target is match to the array elements 38 | return mid; // if match return the mid 39 | } 40 | if (target > nums[mid]) { 41 | low = mid + 1; 42 | } 43 | else { 44 | heigh = mid - 1; 45 | } 46 | } 47 | return low; // Here we return low value for inserting possition 48 | }; 49 | console.log(searchInsert([1, 3, 5, 6], 6)); -------------------------------------------------------------------------------- /Easy/20. Valid Parentheses.js: -------------------------------------------------------------------------------- 1 | /* 2 | 20. Valid Parentheses 3 | https://leetcode.com/problems/valid-parentheses/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY IS O(N) */ 8 | /* 9 | Example 1: 10 | 11 | Input: s = "()" 12 | Output: true 13 | Example 2: 14 | 15 | Input: s = "()[]{}" 16 | Output: true 17 | Example 3: 18 | 19 | Input: s = "(]" 20 | Output: false 21 | */ 22 | 23 | 24 | /** 25 | * @param {string} s 26 | * @return {boolean} 27 | */ 28 | var isValid = function (s) { 29 | if (s.length == 1) { 30 | return false; 31 | } 32 | var map = { 33 | ")": "(", 34 | "]": "[", 35 | "}": "{" 36 | } 37 | var contain = []; 38 | for (let i = 0; i < s.length; i++) { 39 | if ("{" === s[i] || "[" === s[i] || "(" === s[i]) { 40 | contain.push(s[i]); 41 | } else { 42 | if (contain.length == 1) { 43 | if (contain[0] === map[s[i]]) { 44 | contain.splice(0, 1); 45 | } else { return false } 46 | } else { 47 | if (contain[i - 1] === map[s[i]]) { 48 | contain.splice(i - 1, 1); 49 | } else { 50 | return false; 51 | } 52 | } 53 | } 54 | } 55 | return contain.length > 0 ? "false" : "true"; 56 | }; 57 | console.log(isValid("({")); -------------------------------------------------------------------------------- /Medium/567. Permutation in String.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s1 3 | * @param {string} s2 4 | * @return {boolean} 5 | */ 6 | var checkInclusion = function (s1, s2) { 7 | if (s1.length > s2.length) { 8 | return false; 9 | } 10 | const target = new Array(26).fill(0); // Time: O(26) 11 | const window = new Array(26).fill(0); // Time: O(26) 12 | 13 | 14 | for (let i = 0; i < s1.length; i++) { // Time: O(s1) 15 | target[s1[i].charCodeAt() - 'a'.charCodeAt()]++; 16 | window[s2[i].charCodeAt() - 'a'.charCodeAt()]++; 17 | } 18 | 19 | const targetHash = target.join('#'); // Time: O(26) 20 | 21 | let left = 0; 22 | let right = s1.length - 1; // This creates a window already of size s1.length from left to right. 23 | while (right < s2.length) { // Time: O(s2.length - s1.length). 24 | 25 | let windowHash = window.join('#'); // Time: O(26) 26 | if (targetHash === windowHash) { 27 | return true; 28 | } 29 | if (right + 1 >= s2.length) { 30 | break; 31 | } 32 | right++; 33 | window[s2[right].charCodeAt() - 'a'.charCodeAt()]++; // We added an item to our window increase count. 34 | window[s2[left].charCodeAt() - 'a'.charCodeAt()]--; // We removed an item from our window, so decrease this count. 35 | left++; 36 | } 37 | return false; 38 | 39 | }; -------------------------------------------------------------------------------- /Easy/28. Implement strStr().js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 28. Implement strStr() 4 | https://leetcode.com/problems/implement-strstr/ 5 | 6 | https://leetcode.com/problems/implement-strstr/discuss/2400787/java-script-fastest-and-easiest-way-to-solve-this-problem-with-on 7 | 8 | */ 9 | 10 | /* TIME COMPLEXITY O(logn) */ 11 | 12 | /* 13 | Example 1: 14 | 15 | Input: haystack = "hello", needle = "ll" 16 | Output: 2 17 | Example 2: 18 | 19 | Input: haystack = "aaaaa", needle = "bba" 20 | Output: -1 21 | 22 | */ 23 | 24 | /** 25 | * @param {string} haystack 26 | * @param {string} needle 27 | * @return {number} 28 | */ 29 | 30 | var strStr = function (haystack, needle) { 31 | for (let i = 0; i < (haystack.length - needle.length) + 1; i++) { 32 | //Here we use for loop start with 0 to ith window 33 | if (haystack.slice(i, needle.length + i) === needle) { 34 | // Return ith window array 35 | /* 36 | missi 37 | issis 38 | ssiss 39 | sissi 40 | issip 41 | ssipp 42 | sippi 43 | */ 44 | /* return one of them ith window array if it's satisfy the condition */ 45 | return i; 46 | } 47 | } 48 | return -1; // Return -1 if non of them satisfy the condition 49 | }; 50 | console.log(strStr("mississippi", "issip")); -------------------------------------------------------------------------------- /Easy/349. Intersection of Two Arrays.js: -------------------------------------------------------------------------------- 1 | /* 2 | 349. Intersection of Two Arrays 3 | https://leetcode.com/problems/intersection-of-two-arrays/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | /* SPACE COMPLEXITY O(1) */ 8 | 9 | 10 | /* 11 | Example 1: 12 | 13 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 14 | Output: [2] 15 | Example 2: 16 | 17 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 18 | Output: [9,4] 19 | Explanation: [4,9] is also accepted. 20 | 21 | */ 22 | /** 23 | * @param {number[]} nums1 24 | * @param {number[]} nums2 25 | * @return {number[]} 26 | */ 27 | var intersection = function (nums1, nums2) { 28 | // First Create a Hash Map with value of nums1 array 29 | // Because All the duplicate element in nums1 array are removed and only distinct element are in the array 30 | var hashSet = new Set(nums1); 31 | var ans = []; // Create a blank array to store the ans 32 | nums1 = [...hashSet]; // Convert the hash map to array 33 | for (let i = 0; i < nums1.length; i++) { // itterate a loop 0 to length 34 | if (nums2.includes(nums1[i])) { // check that if the nums1 index element is exists in the nums2(array2) 35 | ans.push(nums1[i]); // If the element is exists in the nums2 then add this element to the ans array. 36 | } 37 | } 38 | return ans; // return the ans array 39 | }; 40 | intersection([4, 9, 5], [9, 4, 9, 8, 4]); -------------------------------------------------------------------------------- /Medium/54. Spiral Matrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number[]} 4 | */ 5 | var spiralOrder = function (matrix) { 6 | 7 | var ansArray = []; 8 | var row = matrix.length; 9 | var col = matrix[0].length; 10 | 11 | var startingRow = 0; 12 | var startingCol = 0; 13 | var endRow = matrix.length - 1; 14 | var endCol = matrix[0].length - 1; 15 | 16 | var count = 0; 17 | var total = row * col; 18 | while (count < total) { 19 | for (let index = startingCol; count < total && index <= endCol; index++) { 20 | ansArray.pop(matrix[startingRow][index]); 21 | count++; 22 | } 23 | startingRow++; 24 | for (let index = startingRow; count < total && index <= endRow; index++) { 25 | ansArray.push(matrix[index][endCol]); 26 | count++; 27 | } 28 | endCol--; 29 | for (let index = endCol; count < total && index >= startingCol; index--) { 30 | ansArray.push(matrix[endRow][index]); 31 | count++; 32 | } 33 | endRow--; 34 | for (let index = endRow; count < total && index >= startingRow; index--) { 35 | ansArray.push(matrix[index][startingCol]); 36 | count++; 37 | } 38 | startingCol++; 39 | } 40 | console.log(ansArray); 41 | }; 42 | 43 | spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); -------------------------------------------------------------------------------- /Practice Problems/Next Greater Element (NGE).js: -------------------------------------------------------------------------------- 1 | /* 2 | Next Greater Element (NGE) for every element in given Array 3 | 4 | Given an array, print the Next Greater Element (NGE) for every element. 5 | 6 | The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. 7 | 8 | Example: 9 | 10 | Input: arr[] = [ 4 , 5 , 2 , 25 ] 11 | 12 | Output: 4 –> 5 13 | 14 | 5 –> 25 15 | 16 | 2 –> 25 17 | 18 | 25 –> -1 19 | 20 | Explanation: except 25 every element has an element greater than them present on the right side 21 | 22 | Input: arr[] = [ 13 , 7, 6 , 12 ] 23 | 24 | Output: 13 –> -1 25 | 26 | 7 –> 12 27 | 28 | 6 –> 12 29 | 30 | 12 –> -1 31 | 32 | Explanation: 13 and 12 don’t have any element greater than them present on the right side 33 | 34 | */ 35 | 36 | 37 | function NextGreaterElement(arr) { 38 | var max; 39 | var soFarMax; 40 | var map = new Map(); 41 | for (let i = arr.length - 1; i >= 0; i--) { 42 | if (arr[i] < soFarMax) { 43 | map.set(arr[i], soFarMax); 44 | soFarMax = arr[i]; 45 | } else if (arr[i] < max) { 46 | map.set(arr[i], max); 47 | soFarMax = arr[i]; 48 | } else { 49 | max = arr[i]; 50 | map.set(arr[i], -1); 51 | } 52 | } 53 | console.log(map); 54 | } 55 | NextGreaterElement([1, 3, 4, 2]); -------------------------------------------------------------------------------- /Easy/2006. Count Number of Pairs With Absolute Difference K.js: -------------------------------------------------------------------------------- 1 | /* 2 | 2006. Count Number of Pairs With Absolute Difference K 3 | https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ 4 | */ 5 | 6 | /** 7 | * @param {number[]} nums 8 | * @param {number} k 9 | * @return {number} 10 | */ 11 | 12 | /* METHOD 1 TIME COMPLEXITY O(NLogN) */ 13 | var countKDifference = function (nums, k) { 14 | var count = 0; // Create a count 15 | for (let i = 0; i < nums.length; i++) { 16 | // here if the current index value is 2 17 | // then 2 + 2 = 4 18 | // 2 - 2 = 0 19 | // if 4 and 0 is exists in next slice array then count how many the total number of accurence in that array. 20 | var val1 = nums[i] - k; 21 | var val2 = nums[i] + k; 22 | // slice array and count that number 23 | nums.slice(i + 1).forEach((v) => ((v == val1 || v == val2) && count++)); 24 | } 25 | return count; 26 | }; 27 | 28 | /* METHOD 2 TIME COMPLEXITY O(NLogN) */ 29 | var countKDifference2 = function (nums, k) { 30 | var count = 0; 31 | for (let i = 0; i < nums.length; i++) { 32 | for (let j = 1; j < nums.length; j++) { 33 | // direct check with constraints. 34 | if (i < j && (Math.abs(nums[i] - nums[j]) == k)) { 35 | count++; 36 | } 37 | } 38 | } 39 | return count; 40 | }; 41 | 42 | 43 | 44 | console.log(countKDifference([3, 2, 1, 5, 4], 2)); -------------------------------------------------------------------------------- /Hard/84. Largest Rectangle in Histogram.js: -------------------------------------------------------------------------------- 1 | /* This question is solved but TLE */ 2 | 3 | /** 4 | * @param {number[]} heights 5 | * @return {number} 6 | */ 7 | function reverse(arr, target) { 8 | var count = 0; 9 | for (let i = 0; i < arr.length; i++) { 10 | if (arr[i] >= target) { 11 | count++; 12 | } else { 13 | return count; 14 | } 15 | } 16 | return count; 17 | } 18 | function forward(arr, target) { 19 | var count = 1; 20 | for (let i = 0; i < arr.length; i++) { 21 | if (arr[i] >= target) { 22 | count++; 23 | } else { 24 | return count; 25 | } 26 | } 27 | return count; 28 | } 29 | 30 | var largestRectangleArea = function (heights) { 31 | var map = new Map(); 32 | var max = 0; 33 | for (let i = 0; i < heights.length; i++) { 34 | var forwardCount = forward(heights.slice(i + 1), heights[i]); 35 | var reverseCount = reverse(heights.slice(0, i).reverse(), heights[i]); 36 | var totalWidth = (parseInt(forwardCount) + parseInt(reverseCount)) * heights[i]; 37 | // console.log(`${heights[i]} ${totalWidth}`); 38 | if (max < totalWidth) { 39 | max = totalWidth; 40 | } 41 | // console.log(forward(heights.slice(i + 1), heights[i])); 42 | } 43 | return max; 44 | 45 | }; 46 | console.log(largestRectangleArea([2, 1, 5, 6, 2, 3])); 47 | 48 | // [2,1,5,6,9,2,3] 49 | // [2,4] 50 | // [1] 51 | // [4,2] -------------------------------------------------------------------------------- /Easy/69. Sqrt(x).js: -------------------------------------------------------------------------------- 1 | /* 2 | 69. Sqrt(x) 3 | https://leetcode.com/problems/sqrtx/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY O(LogN) */ 8 | 9 | /* 10 | Example 1: 11 | 12 | Input: x = 4 13 | Output: 2 14 | Example 2: 15 | 16 | Input: x = 8 17 | Output: 2 18 | Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. 19 | 20 | */ 21 | 22 | /** 23 | * @param {number} x 24 | * @return {number} 25 | */ 26 | 27 | /* Implement A Binary Search For This Approach */ 28 | function binarySearch(x) { 29 | let first = 0; // start from 0 30 | let last = x; // end number is x 31 | // like : 0 1 2 3 4 ......... x 32 | let mid = Math.floor((first + last) / 2); // Find the middle number 33 | while (first <= last) { 34 | let pow = mid * mid; // Find the power of the middle number 35 | if (pow == x) { // if the power number is equal to the x then return mid 36 | return mid; 37 | } 38 | if (pow > x) { // If the pow is greater-than x then modify the last to mid-1 39 | last = mid - 1; 40 | } 41 | else { 42 | first = mid + 1; // If the pow is less-than the x then modify the first to mid+1 43 | } 44 | mid = Math.floor((first + last) / 2); // Find the middle number 45 | } 46 | return mid; // Lastly return the mid number 47 | } 48 | var mySqrt = function (x) { 49 | return binarySearch(x); 50 | }; 51 | console.log(mySqrt(36)); -------------------------------------------------------------------------------- /Easy/704. Binary Search.js: -------------------------------------------------------------------------------- 1 | /* 2 | 704. Binary Search 3 | https://leetcode.com/problems/binary-search/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY O(LogN) */ 8 | 9 | /* 10 | Example 1: 11 | Input: nums = [-1,0,3,5,9,12], target = 9 12 | Output: 4 13 | Explanation: 9 exists in nums and its index is 4 14 | 15 | Example 2: 16 | Input: nums = [-1,0,3,5,9,12], target = 2 17 | Output: -1 18 | Explanation: 2 does not exist in nums so return -1 19 | */ 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @param {number} target 24 | * @return {number} 25 | */ 26 | var search = function (nums, target) { 27 | let first = 0; //start index 28 | let last = nums.length; // last index 29 | while (first <= last) { // Check First element should be less than or equal to last 30 | let mid = Math.floor((first + last) / 2); // Find the middle element 31 | if (nums[mid] == target) { // check with our target 32 | return mid; 33 | } 34 | else if (nums[mid] < target) { // if the middle element value is less then the target value then modify the first element to mid + 1 35 | first = mid + 1 36 | } 37 | else { 38 | last = mid - 1; // if the mid is greater then the target value then modify the last element to mod -1 39 | } 40 | } 41 | return -1; // return -1 if the target value does not find 42 | }; 43 | console.log(search([-1, 0, 3, 5, 9, 12], 9)); 44 | console.log(search([-1, 0, 3, 5, 9, 12], 2)); 45 | -------------------------------------------------------------------------------- /Medium/2. Add Two Numbers.js: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 5 | 6 | Input: l1 = [2,4,3], l2 = [5,6,4] 7 | Output: [7,0,8] 8 | Explanation: 342 + 465 = 807. 9 | Example 2: 10 | 11 | Input: l1 = [0], l2 = [0] 12 | Output: [0] 13 | Example 3: 14 | 15 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 16 | Output: [8,9,9,9,0,0,0,1] 17 | 18 | */ 19 | /** 20 | * Definition for singly-linked list. 21 | * function ListNode(val, next) { 22 | * this.val = (val===undefined ? 0 : val) 23 | * this.next = (next===undefined ? null : next) 24 | * } 25 | */ 26 | /** 27 | * @param {ListNode} l1 28 | * @param {ListNode} l2 29 | * @return {ListNode} 30 | */ 31 | 32 | var addTwoNumbers = function (l1, l2) { 33 | let carry = 0; 34 | let dummy = new ListNode(0); 35 | let current = dummy; 36 | while (l1 || l2) { 37 | let sum = carry; 38 | if (l1) { 39 | sum += l1.val; 40 | l1 = l1.next; 41 | } 42 | if (l2) { 43 | sum += l2.val; 44 | l2 = l2.next; 45 | } 46 | carry = Math.floor(sum / 10); 47 | current.next = new ListNode(sum % 10); 48 | current = current.next; 49 | } 50 | if (carry > 0) { 51 | current.next = new ListNode(carry); 52 | } 53 | return dummy.next; 54 | }; 55 | -------------------------------------------------------------------------------- /Easy/58. Length of Last Word.js: -------------------------------------------------------------------------------- 1 | /* 2 | 58. Length of Last Word 3 | https://leetcode.com/problems/length-of-last-word/ 4 | 5 | https://leetcode.com/problems/length-of-last-word/discuss/2407083/easy-java-script-two-way-solution-with-ologn-and-on-time-complexity 6 | 7 | */ 8 | 9 | /* 10 | Example 1: 11 | 12 | Input: s = "Hello World" 13 | Output: 5 14 | Explanation: The last word is "World" with length 5. 15 | Example 2: 16 | 17 | Input: s = " fly me to the moon " 18 | Output: 4 19 | Explanation: The last word is "moon" with length 4. 20 | Example 3: 21 | 22 | Input: s = "luffy is still joyboy" 23 | Output: 6 24 | Explanation: The last word is "joyboy" with length 6. 25 | 26 | */ 27 | 28 | /** 29 | * @param {string} s 30 | * @return {number} 31 | */ 32 | 33 | /* METHOD1 WITH ⏱️ TIME COMPLEXITY O(LogN) */ 34 | 35 | var lengthOfLastWord = function (s) { 36 | let count = 0; 37 | for (let i = s.length - 1; i >= 0; i--) { 38 | if (s[i] == " ") { 39 | if (count == 0) { 40 | continue; 41 | } else { 42 | return count; 43 | } 44 | } 45 | if ((s[i].charCodeAt() >= 97 && s[i].charCodeAt() <= 122) || (s[i].charCodeAt() >= 65 && s[i].charCodeAt() <= 90)) { 46 | count++; 47 | } 48 | } 49 | return count; 50 | }; 51 | 52 | /* METHOD2 WITH ⏱️ TIME COMPLEXITY O(N) */ 53 | 54 | var lengthOfLastWord = function (s) { 55 | var n = s.trim().split(" "); // O(N); 56 | return n[n.length - 1].length; 57 | } 58 | console.log(lengthOfLastWord("Hello WorldZ ")); -------------------------------------------------------------------------------- /Practice Problems/2Darray.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | how to find total row = martix.length 4 | how to find total column = matrinx[0].length 5 | 6 | how to find particular index value with linear array 7 | (col * i) + j = linear array index value 8 | like: 9 | [ 10 | 0 1 2 11 | 0 [1, 2, 3], 12 | 1 [4, 5, 6], 13 | 2 [7, 8, 9], 14 | ]; 15 | [1,2,3,4,5,6,7,8,9] 16 | 17 | 18 | how to find 2D array index value with linear array 19 | like: 20 | [1,2,3,4,5,6,7,8,9] 21 | [ 22 | [1, 2, 3], 23 | [4, 5, 6], 24 | [7, 8, 9], 25 | ]; 26 | 27 | row = mid / col; 28 | col = mid % col; 29 | 30 | */ 31 | 32 | // Print Rom Sum 33 | function PrintSum(arr, row, col) { 34 | for (let i = 0; i < row; i++) { 35 | var sum = 0; 36 | for (let j = 0; j < col; j++) { 37 | sum += arr[i][j]; 38 | } 39 | console.log(sum); 40 | } 41 | } 42 | 43 | // Print Col Sum 44 | function PrintSum(arr, row, col) { 45 | for (let i = 0; i < col; i++) { 46 | if (i % 2 == 0) { 47 | for (let j = 0; j < row; j++) { 48 | console.log(arr[j][i]); 49 | } 50 | } else { 51 | for (let j = row - 1; j >= 0; j--) { 52 | console.log(arr[j][i]); 53 | } 54 | } 55 | } 56 | } 57 | 58 | function array2D() { 59 | var arr = [ 60 | [1, 2, 3], 61 | [4, 5, 6], 62 | [7, 7, 8], 63 | ]; 64 | // console.log(arr); 65 | PrintSum(arr, 3, 3); 66 | } 67 | array2D(); 68 | -------------------------------------------------------------------------------- /Easy/217. Contains Duplicate.js: -------------------------------------------------------------------------------- 1 | /* 2 | 217. Contains Duplicate 3 | https://leetcode.com/problems/contains-duplicate/ 4 | */ 5 | 6 | /** 7 | * @param {number[]} nums 8 | * @return {boolean} 9 | */ 10 | 11 | /* METHOD 1 Without Space Complexity */ 12 | /* TIME COMPLEXITY O(N) */ 13 | var containsDuplicate = function (nums) { 14 | let s = 0; // Make a pointer which is start from 0 15 | for (let i = 1; i < nums.length; i++) { 16 | if (nums[s] == nums[i]) { // check that if Sth possition value equal to the Ith possition value or not 17 | return true; 18 | } 19 | if (s == nums.length) { // If the s is equal to the nums length then return false means we check all the value of this array 20 | return false; 21 | } 22 | if (i == nums.length - 1) { // check if the i value equal to the nums.length then increase both i and s 23 | i = ++s; 24 | } 25 | } 26 | return false; // return false if all case are false 27 | }; 28 | 29 | /* METHOD 2 Use Space Complexity */ 30 | /* TIME COMPLEXITY O(N) */ 31 | 32 | var containsDuplicate = function (nums) { 33 | if (nums.length == 1) 34 | return false; 35 | let set = new Set(nums); 36 | // Create a Set which is only contain the distinct value 37 | // The logic behid is that when we create a Set it remove all duplicate value from nums 38 | // And just simply check if the nums length is equal to the set length 39 | // If the nums length is greater then set length return true. 40 | if (nums.length > set.size) 41 | return true; 42 | return false; 43 | } 44 | console.log(containsDuplicate([2, 14, 18, 22, 22])); -------------------------------------------------------------------------------- /Medium/852. Peak Index in a Mountain Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 852. Peak Index in a Mountain Array 3 | https://leetcode.com/problems/peak-index-in-a-mountain-array/ 4 | 5 | 6 | https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2416281/Java-Script-or-100-Faster-or-Log(N)-or-Easy-and-Simple-Solution 7 | 8 | https://github.com/bibhuti9/DSA-JavaScript-LeetCode-Solution/blob/main/Medium/852.%20Peak%20Index%20in%20a%20Mountain%20Array.js 9 | 10 | */ 11 | 12 | /* TIME COMPLEXITY O(LogN) */ 13 | 14 | /* 15 | Example 1: 16 | 17 | Input: arr = [0,1,0] 18 | Output: 1 19 | Example 2: 20 | 21 | Input: arr = [0,2,1,0] 22 | Output: 1 23 | Example 3: 24 | 25 | Input: arr = [0,10,5,2] 26 | Output: 1 27 | */ 28 | 29 | /** 30 | * @param {number[]} arr 31 | * @return {number} 32 | */ 33 | var peakIndexInMountainArray = function (arr) { 34 | let first = 0; //Set a verible as a first index 35 | let last = arr.length - 1; // Set a veriable as last index of as array 36 | while (first < last) { // Here We Set the condition as first should be less then last index 37 | let mid = Math.floor((first + last) / 2); // set our mid veriable 38 | if (arr[mid] < arr[mid + 1]) { // check the condition that mid should be less then it's next element value. 39 | first = mid + 1; // If the condition id true then modify the first veriable value to mid+1 40 | } 41 | else { 42 | last = mid; // if the condition is false then modify the last index value as mid 43 | } 44 | } 45 | return first; // return first because it's a mount index; 46 | }; 47 | console.log(peakIndexInMountainArray([0, 10, 5, 2])); -------------------------------------------------------------------------------- /Easy/387. First Unique Character in a String.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | 6 | // METHOD 1 7 | // TIME COMPLEXITY O(N) 8 | var firstUniqChar = function (s) { 9 | var map = new Map(); // Create A map which store the occurence of the element 10 | for (let i = 0; i < s.length; i++) { 11 | if (map.has(s[i])) { // if the S Ith index value exists in the map then increment the map element value by 1 12 | map.set(s[i], map.get(s[i]) + 1); 13 | } else { 14 | map.set(s[i], 1); // if the element does not exists in the map then add/push to the map 15 | } 16 | } 17 | // This is the important method 18 | //here we itterate all the map value and check which map key value is 1 19 | // 1 means that key only exists in one time 20 | for (var [key, val] of map.entries()) { 21 | if (val == 1) return s.indexOf(key); // if the map value equal to 1 return the sth index 22 | } 23 | return -1; 24 | }; 25 | 26 | // METHOD 2 27 | // TIME COMPLEXITY O(N) 28 | var firstUniqChar = function (s) { 29 | for (i = 0; i < s.length; i++) { 30 | // This is the very simple solution 31 | // the indexOf method return the first index value and the lastIndexOf return the last index to the particular index value 32 | // If the duplicate value exists in the string the indexOf and lastIndexOf value does not equal 33 | // Our task is to find indexOf and lastIndexOf are diffrent. 34 | if (s.indexOf(s[i]) == s.lastIndexOf(s[i])) { 35 | // console.log(`${s[i]} ${s.indexOf(s[i])} ${s.lastIndexOf(s[i])}`); 36 | return i; 37 | } 38 | } 39 | return -1; 40 | }; 41 | 42 | console.log(firstUniqChar("loveleetcode")); -------------------------------------------------------------------------------- /Easy/121. Best Time to Buy and Sell Stock.js: -------------------------------------------------------------------------------- 1 | /* 2 | 121. Best Time to Buy and Sell Stock 3 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 4 | 5 | */ 6 | 7 | /** 8 | * @param {number[]} prices 9 | * @return {number} 10 | */ 11 | 12 | // This is the solution but Time Limit Exceeded 13 | 14 | /*Method 1 */ 15 | /* TIME COMPLEXITY O(N) */ 16 | 17 | var maxProfit2 = function (prices) { 18 | var minimumSofar = prices[0]; // Create a minimum veriable to store the minimux value in the array 19 | var maxProfit = 0; // Create a maximum veriable to store the maximun value 20 | for (let i = 0; i < prices.length; i++) { 21 | { 22 | if (minimumSofar > prices[i]) { // Check that the Ith possitino value is less then the minimum value if condition is true modify the minimum value to new value. 23 | minimumSofar = prices[i]; 24 | } 25 | 26 | if ((prices[i] - minimumSofar) > maxProfit) { // check Ith possition value minus minimum value profit is greater then the MaxProfit if condition is true then modify our maxProfit 27 | maxProfit = (prices[i] - minimumSofar); 28 | } 29 | } 30 | } 31 | return maxProfit; 32 | } 33 | 34 | // [3,3,5,0,0,3,1,4] 35 | 36 | /*Method 2 */ 37 | /* TIME COMPLEXITY O(N2) */ 38 | 39 | var maxProfit1 = function (prices) { 40 | var max = 0; 41 | var start = 0; 42 | for (let i = 1; i < prices.length; i++) { 43 | if ((prices[start] < prices[i]) && (prices[i] - prices[start]) > max) { 44 | max = prices[i] - prices[start]; 45 | } 46 | if (i == prices.length - 1) { 47 | i = ++start; 48 | } 49 | } 50 | return max; 51 | 52 | } 53 | console.log(maxProfit2([3, 3, 5, 0, 0, 3, 1, 4])); -------------------------------------------------------------------------------- /Easy/14. Longest Common Prefix.js: -------------------------------------------------------------------------------- 1 | /* 2 | 14. Longest Common Prefix 3 | 4 | https://leetcode.com/problems/longest-common-prefix/ 5 | 6 | https://leetcode.com/problems/longest-common-prefix/discuss/2396181/easiest-java-script-solution-on2 7 | */ 8 | 9 | /* TIME COMPLEXITY IS O(N2) */ 10 | 11 | /* 12 | Example 1: 13 | 14 | Input: strs = ["flower","flow","flight"] 15 | Output: "fl" 16 | Example 2: 17 | 18 | Input: strs = ["dog","racecar","car"] 19 | Output: "" 20 | Explanation: There is no common prefix among the input strings. 21 | */ 22 | 23 | /** 24 | * @param {string[]} strs 25 | * @return {string} 26 | */ 27 | var longestCommonPrefix = function (strs) { 28 | var firstIndexStr = strs[0], ans = ""; 29 | if (strs[0] == "") return ""; //if string contain blank 30 | if (strs.length == 1) return strs[0] //return if string contain only one word 31 | for (let i = 0; i < firstIndexStr.length; i++) { //this loop is used for check the firstWord all character with it's respective to other word character. 32 | var count = 1; //use count veriable to check that all character satisfy with all word character or not. 33 | for (let j = 1; j < strs.length; j++) { 34 | if (strs[j][i] == firstIndexStr[i]) { //here we check string First Word with other character words 35 | count++; //if the character match with other character than increment to +1 36 | } 37 | } 38 | if (count == strs.length) { //check that all word character satisfy with all character or not. 39 | ans += firstIndexStr[i]; 40 | } else { 41 | return ans.length > 0 ? ans : ""; //chect that the ans length should be greater than 1 than return ans otherwise return ""; 42 | } 43 | } 44 | return ans; 45 | }; 46 | console.log(longestCommonPrefix(["flower", "flower", "flower", "flower"])); -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 13 | 14 | 16 | 17 | 18 | 21 | 28 | 29 | 30 | 31 | 32 | 1660321435268 33 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Easy/345. Reverse Vowels of a String.js: -------------------------------------------------------------------------------- 1 | /* 2 | 345. Reverse Vowels of a String 3 | https://leetcode.com/problems/reverse-vowels-of-a-string/ 4 | 5 | */ 6 | 7 | /* TIME COMPLEXITY O(LogN) */ 8 | 9 | /** 10 | * @param {string} s 11 | * @return {string} 12 | */ 13 | var reverseVowels = function (s) { 14 | let pointer = s.length - 1; // Create A Pointer Which Is Start From End Of The Array. 15 | let ansStr = s.split(""); // Convert String To Array That Will More Easy To Solve This Problem. 16 | let i = 0; // Create A I Veriable That Start From Array Index Of 0 17 | var voewls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; // Create a All Vowels That Will Help To Check The Value Is Vowel Or Not. 18 | // You can use regex like: /[a|e|i|o|u]/gi 19 | while (i < pointer) { // Check Condition That I Should Be Less Then Pointer This Condition Devide The Time Complexity To O(N) To O(LogN). 20 | 21 | if (voewls.includes(ansStr[i]) && voewls.includes(ansStr[pointer])) { // Here we check the condition that our I possition value and Pointer possition value should be vowel 22 | let tmp = ansStr[i]; // If condition is true then swap this possition value respectively you can create a extra swap function. 23 | ansStr[i++] = ansStr[pointer]; 24 | ansStr[pointer--] = tmp; 25 | } else { 26 | if (voewls.includes(ansStr[i])) { // If the Ith possition value is vowel then we decrement the Pointer Possition value to -1; 27 | pointer--; 28 | } else { 29 | i++; // If the Ith possition value does not a vowel then increment the Ith possition by +1 30 | } 31 | } 32 | } 33 | return ansStr.join(""); // Here we convert the array to string 34 | }; 35 | console.log(reverseVowels("Marge, let's \"went.\" I await news telegram.")); -------------------------------------------------------------------------------- /Easy/88. Merge Sorted Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 88. Merge Sorted Array 3 | https://leetcode.com/problems/merge-sorted-array/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(LogN) */ 7 | 8 | /* 9 | 10 | Example 1: 11 | 12 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 13 | Output: [1,2,2,3,5,6] 14 | Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. 15 | The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. 16 | Example 2: 17 | 18 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 19 | Output: [1] 20 | Explanation: The arrays we are merging are [1] and []. 21 | The result of the merge is [1]. 22 | Example 3: 23 | 24 | Input: nums1 = [0], m = 0, nums2 = [1], n = 1 25 | Output: [1] 26 | Explanation: The arrays we are merging are [] and [1]. 27 | The result of the merge is [1]. 28 | Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. 29 | 30 | */ 31 | 32 | /** 33 | * @param {number[]} nums1 34 | * @param {number} m 35 | * @param {number[]} nums2 36 | * @param {number} n 37 | * @return {void} Do not return anything, modify nums1 in-place instead. 38 | */ 39 | var merge = function (nums1, m, nums2, n) { 40 | let pointer1 = m - 1; // create a pointer1 which is start from m-1 41 | let pointer2 = n - 1; // Same create a pointer2 which is start from n-1; 42 | let i = (m + n) - 1; // Here I is a last length of nums1 array 43 | while (pointer2 >= 0) { // Check that pointer2 should be greater than 0 44 | if (pointer1 >= 0 && nums1[pointer1] > nums2[pointer2]) { 45 | nums1[i--] = nums1[pointer1--]; 46 | // If the pointer1 is greater than pointer2 then changes values. 47 | } else { 48 | nums1[i--] = nums2[pointer2--]; 49 | } 50 | } 51 | return nums1; 52 | }; 53 | merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3); -------------------------------------------------------------------------------- /Medium/443. String Compression.js: -------------------------------------------------------------------------------- 1 | /* 2 | 443. String Compression 3 | https://leetcode.com/problems/string-compression/ 4 | */ 5 | 6 | /** 7 | * @param {character[]} chars 8 | * @return {number} 9 | */ 10 | /* 11 | 12 | Input: 13 | ["a"] 14 | Output: 15 | [] 16 | Expected: 17 | ["a"] 18 | 19 | Input: 20 | ["a","a","a","b","b","a","a"] 21 | Output: 22 | ["a","5","b","2"] 23 | Expected: 24 | ["a","3","b","2","a","2"] 25 | 26 | Input: 27 | ["a","b","b","b","b","b","b","b","b","b","b","b","b"] 28 | Output: 29 | ["a","b","12"] 30 | Expected: 31 | ["a","b","1","2"] 32 | 33 | 34 | */ 35 | 36 | 37 | var compress = function (chars) { 38 | if (chars.length == 1) { 39 | return chars.length; 40 | } 41 | var currentValue = chars[0]; 42 | var count = 1; 43 | var arr = []; 44 | for (let i = 1; i < chars.length; i++) { 45 | if (currentValue === chars[i]) { 46 | count++; 47 | } else { 48 | arr.push(currentValue); 49 | if (count > 9) { 50 | `${count}`.split("").map((value) => { 51 | arr.push(value); 52 | }); 53 | } else { 54 | if (count != 1) { 55 | arr.push(count.toString()); 56 | } 57 | } 58 | currentValue = chars[i]; 59 | count = 1; 60 | } 61 | 62 | if (i == chars.length - 1) { 63 | arr.push(currentValue); 64 | if (count > 9) { 65 | `${count}`.split("").map((value) => { 66 | arr.push(value); 67 | }); 68 | } else { 69 | if (count != 1) { 70 | arr.push(count.toString()); 71 | } 72 | } 73 | } 74 | } 75 | chars.splice(0); 76 | for (let i = 0; i < arr.length; i++) { 77 | chars.push(arr[i]); 78 | } 79 | return chars; 80 | }; 81 | console.log(compress(["a", "b", "b", "b", "c", "c", "a", "a", "a"])); -------------------------------------------------------------------------------- /Medium/74. Search a 2D Matrix.js: -------------------------------------------------------------------------------- 1 | /* 2 | 74. Search a 2D Matrix 3 | https://leetcode.com/problems/search-a-2d-matrix/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(LogN) */ 7 | 8 | /** 9 | * @param {number[][]} matrix 10 | * @param {number} target 11 | * @return {boolean} 12 | */ 13 | var searchMatrix = function (matrix, target) { 14 | var row = matrix.length; // how many row in 2D array 15 | var col = matrix[0].length; // how many column in 2D array 16 | 17 | var start = 0; // make a start pointer 18 | var end = row * col - 1; // make a end pointer 19 | var mid = Math.floor((start + end) / 2); // To find mid element 20 | while (start <= end) { 21 | mid = Math.floor((start + end) / 2); 22 | 23 | // row = mid / col; 24 | // col = mid % col; 25 | 26 | var elementIndex = matrix[Math.floor(mid / col)][Math.floor(mid % col)]; 27 | 28 | if (elementIndex == target) { 29 | return true; // when target is find 30 | } 31 | if (elementIndex > target) { 32 | end = mid - 1; // when mid element is greater then target 33 | } else { 34 | start = mid + 1; 35 | } 36 | } 37 | return false; 38 | }; 39 | console.log(searchMatrix([ 40 | [1, 3, 5, 7], 41 | [10, 11, 16, 20], 42 | [23, 30, 34, 60] 43 | ], 44 | 13)); 45 | 46 | /* 47 | Explanation: 48 | 49 | how to find total row = martix.length 50 | how to find total column = matrinx[0].length 51 | 52 | how to find particular index value with linear array 53 | (col * i) + j = linear array index value 54 | (3*1)+1 = [4] = 5 55 | like: 56 | [ 57 | 0 1 2 58 | 0 [1, 2, 3], 59 | 1 [4, 5, 6], 60 | 2 [7, 8, 9], 61 | ]; 62 | [1,2,3,4,5,6,7,8,9] 63 | 64 | 65 | how to find 2D array index value with linear array 66 | like: 67 | [1,2,3,4,5,6,7,8,9] 68 | [ 69 | [1, 2, 3], 70 | [4, 5, 6], 71 | [7, 8, 9], 72 | ]; 73 | 74 | row = mid / col; 75 | col = mid % col; 76 | 77 | * / 78 | 79 | // [1, 2, 5, 7, 10, 11, 16, 20, 23, 30, 34, 60] -------------------------------------------------------------------------------- /Medium/34. Find First and Last Position of Element in Sorted Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 34. Find First and Last Position of Element in Sorted Array 4 | https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 5 | 6 | https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/2412819/easy-java-script-solution-with-time-complexity-ologn-with-two-method-solution 7 | */ 8 | 9 | // There are two method are avilable. 10 | 11 | /** 12 | * @param {number[]} nums 13 | * @param {number} target 14 | * @return {number[]} 15 | */ 16 | 17 | 18 | /* METHOD1 AND ⏱️ TIME COMPLEXITY O(logn)*/ 19 | 20 | 21 | function firstPossition(arr, target) { 22 | var ans = -1; 23 | let first = 0; 24 | let last = arr.length - 1; 25 | while (first <= last) { 26 | var mid = Math.floor((first + last) / 2); 27 | 28 | if (arr[mid] === target) { 29 | ans = mid; 30 | last = mid - 1; 31 | } 32 | else if (target > arr[mid]) { 33 | first = mid + 1; 34 | } 35 | else if (target < arr[mid]) { 36 | last = mid - 1; 37 | } 38 | } 39 | return ans; 40 | } 41 | function secondPossition(arr, target) { 42 | var ans = -1; 43 | let first = 0; 44 | let last = arr.length - 1; 45 | while (first <= last) { 46 | var mid = Math.floor((first + last) / 2); 47 | 48 | if (arr[mid] === target) { 49 | ans = mid; 50 | first = mid + 1; 51 | } 52 | else if (target > arr[mid]) { 53 | first = mid + 1; 54 | } 55 | else if (target < arr[mid]) { 56 | last = mid - 1; 57 | } 58 | } 59 | return ans; 60 | } 61 | var searchRange = function (nums, target) { 62 | return [firstPossition(nums, target), secondPossition(nums, target)]; 63 | }; 64 | 65 | 66 | 67 | /* METHOD1 AND ⏱️ TIME COMPLEXITY O(logn)*/ 68 | 69 | var searchRange = function (nums, target) { 70 | // With Inbuild function we can solve this problem by constant time. 71 | return [nums.indexOf(target), nums.lastIndexOf(target)]; 72 | } 73 | console.log(searchRange([0, 1, 2, 2, 2, 2, 3, 4, 4, 5, 6, 6], 2)); -------------------------------------------------------------------------------- /Medium/1910. Remove All Occurrences of a Substring.js: -------------------------------------------------------------------------------- 1 | /* 2 | 1910. Remove All Occurrences of a Substring 3 | https://leetcode.com/problems/remove-all-occurrences-of-a-substring/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /* 9 | Example 1: 10 | 11 | Input: s = "daabcbaabcbc", part = "abc" 12 | Output: "dab" 13 | Explanation: The following operations are done: 14 | - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". 15 | - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". 16 | - s = "dababc", remove "abc" starting at index 3, so s = "dab". 17 | Now s has no occurrences of "abc". 18 | Example 2: 19 | 20 | Input: s = "axxxxyyyyb", part = "xy" 21 | Output: "ab" 22 | Explanation: The following operations are done: 23 | - s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb". 24 | - s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb". 25 | - s = "axxyyb", remove "xy" starting at index 2 so s = "axyb". 26 | - s = "axyb", remove "xy" starting at index 1 so s = "ab". 27 | Now s has no occurrences of "xy". 28 | 29 | */ 30 | 31 | /** 32 | * @param {string} s 33 | * @param {string} part 34 | * @return {string} 35 | */ 36 | var removeOccurrences = function (s, part) { 37 | var ansArray = s.split(""); // create a array which is used to store the string element as array. 38 | //['d', 'a', 'a', 'b', 'c', 'b', 'a', 'a', 'b', 'c', 'b', 'c']; 39 | var n = ((ansArray.length - part.length) + 1); 40 | for (var i = 0; i < n;) { 41 | if (ansArray.slice(i, i + part.length).join("") == part) { 42 | // Here is the main condition is that first 43 | // we slice the element the slice method is basically return the Ith possition value to i+part.length value 44 | ansArray.splice(i, part.length); // then we delete that match value into our array 45 | i = 0; //And then modify i to 0 because may be the array again contain same element 46 | } else { 47 | i++; 48 | } 49 | } 50 | return ansArray.join(""); // return the array as string 51 | }; 52 | console.log(removeOccurrences("daabcbaabcbc", "abc")); 53 | /* 54 | daa 55 | aab 56 | abc 57 | bcb 58 | cba 59 | bab 60 | 61 | */ 62 | -------------------------------------------------------------------------------- /Medium/33. Search in Rotated Sorted Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | 33. Search in Rotated Sorted Array 3 | https://leetcode.com/problems/search-in-rotated-sorted-array/ 4 | 5 | https://github.com/bibhuti9/DSA-JavaScript-LeetCode-Solution/blob/main/Medium/33.%20Search%20in%20Rotated%20Sorted%20Array.js 6 | 7 | https://github.com/bibhuti9/DSA-JavaScript-LeetCode-Solution/blob/main/Medium/33.%20Search%20in%20Rotated%20Sorted%20Array.js 8 | 9 | */ 10 | 11 | /* TIME COMPLEXITY O(LogN) */ 12 | 13 | 14 | /* 15 | 16 | Example 1: 17 | 18 | Input: nums = [4,5,6,7,0,1,2], target = 0 19 | Output: 4 20 | Example 2: 21 | 22 | Input: nums = [4,5,6,7,0,1,2], target = 3 23 | Output: -1 24 | Example 3: 25 | 26 | Input: nums = [1], target = 0 27 | Output: -1 28 | 29 | */ 30 | /** 31 | * @param {number[]} nums 32 | * @param {number} target 33 | * @return {number} 34 | */ 35 | 36 | /* FIND PIVOT ELEMENT */ 37 | function find_pivot_element_in_a_sorted_roted_array(arr) { 38 | let first = 0; 39 | let last = arr.length - 1; 40 | while (first < last) { 41 | let mid = Math.floor((first + last) / 2); 42 | if (arr[mid] >= arr[0]) { 43 | first = mid + 1; 44 | } else { 45 | last = mid; 46 | } 47 | } 48 | return first; 49 | } 50 | 51 | /* IMPLEMENT BINARY SEARCH */ 52 | function binary_search(arr, s, e, target) { 53 | let first = s; //s = start index 54 | let last = e; // e = last index 55 | while (first <= last) { 56 | let mid = Math.floor((first + last) / 2); 57 | if (arr[mid] == target) { 58 | return mid; 59 | } 60 | else if (arr[mid] < target) { 61 | first = mid + 1 62 | } 63 | else { 64 | last = mid - 1; 65 | } 66 | } 67 | return -1; 68 | } 69 | 70 | var search = function (nums, target) { 71 | let pivot_element = find_pivot_element_in_a_sorted_roted_array(nums); // Find the pivot element 72 | 73 | // If Our Target Element In A Right Part Then Move To Right Part 74 | // Pivot Index To Array Last Index 75 | 76 | // Like [0,1,2] It's a right part array 77 | if (target >= nums[pivot_element] && target <= nums[nums.length - 1]) { 78 | return binary_search(nums, pivot_element, nums.length - 1, target); 79 | } else { 80 | 81 | // If Our Target Element In A Lefr Part Then Move To Left Part 82 | // 0 Index To Pivot Index 83 | //Like [4, 5, 6, 7] It's a left part array 84 | return binary_search(nums, 0, pivot_element - 1, target); 85 | } 86 | 87 | }; 88 | console.log(search([4, 5, 6, 7, 0, 1, 2], 0)); 89 | -------------------------------------------------------------------------------- /Easy/125. Valid Palindrome.js: -------------------------------------------------------------------------------- 1 | /* 2 | 125. Valid Palindrome 3 | https://leetcode.com/problems/valid-palindrome/ 4 | */ 5 | 6 | /* TIME COMPLEXITY O(N) */ 7 | 8 | /* 9 | Example 1: 10 | 11 | Input: s = "A man, a plan, a canal: Panama" 12 | Output: true 13 | Explanation: "amanaplanacanalpanama" is a palindrome. 14 | Example 2: 15 | 16 | Input: s = "race a car" 17 | Output: false 18 | Explanation: "raceacar" is not a palindrome. 19 | */ 20 | 21 | /** 22 | * @param {string} s 23 | * @return {boolean} 24 | */ 25 | 26 | //Create a function to check that the whole string is palindrom or not 27 | //This function is the main function to check our string is valid palindrom or not 28 | function check_palindrom(s) { 29 | let pointer = s.length - 1; // Make a pointer which is start form length 30 | for (let i = 0; i < s.length / 2; i++, pointer--) { 31 | if (s[i] != s[pointer]) { // Check is the Ith possition value and pointer possition value is equal or not 32 | return false; // return false if any of character is not equal we don't require to itterate whole string 33 | } 34 | } 35 | return true; // Return true if all condition is satisfy 36 | } 37 | 38 | // Method 1 39 | // This Below method is basically used for non-regex method. 40 | 41 | var isPalindrome = function (s) { 42 | // Make a array which is used to store all non-alphanumeric characters. 43 | s = s.toLowerCase(); // Convert whole string to lower case. 44 | var ansArray = []; 45 | for (let i = 0; i < s.length; i++) { 46 | // The bellow condition is used to check that the number should be a-z or 0-9 47 | if ((s.charCodeAt(i) >= 97 && s.charCodeAt(i) <= 122) || (s.charCodeAt(i) >= 48 && (s.charCodeAt(i) <= 57))) { 48 | ansArray.push(s[i]) // If the condition is true then add this value to the array 49 | } 50 | } 51 | // Here The join function is used to convert array to string. 52 | return check_palindrom(ansArray.join("")); 53 | }; 54 | 55 | 56 | // Method 2 57 | // Below method is basically used for use regex 58 | 59 | var isPalindrome = function (s) { 60 | // the below replace method is basically used to remove all non-alphanumeric character 61 | // And the lower function is used for convert whole string to lower case 62 | s = s.replace(/[^A-Za-z0-9]/g, '').toLowerCase(); 63 | // Convert whole string to lower case. 64 | // Here The join function is used to convert array to string. 65 | return check_palindrom(s); 66 | }; 67 | 68 | console.log(isPalindrome("0P")); 69 | console.log(isPalindrome("A man, a plan, a canal: Panama")); 70 | // char Code 71 | // a = 97 72 | // z = 122 73 | // A = 65 74 | // Z = 90 75 | // 0 = 48 76 | // 9 = 57 77 | -------------------------------------------------------------------------------- /Practice Problems/linked list/allOperatio.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | // constructor 3 | constructor(element) { 4 | this.element = element; 5 | this.next = null 6 | } 7 | } 8 | // linkedlist class 9 | class LinkedList { 10 | constructor() { 11 | this.head = null; 12 | this.size = 0; 13 | } 14 | 15 | // adds an element at the end 16 | // of list 17 | add(element) { 18 | var node = new Node(element); 19 | var current; 20 | 21 | if (this.head == null) 22 | this.head = node; 23 | else { 24 | current = this.head; 25 | while (current.next) { 26 | current = current.next; 27 | } 28 | current.next = node; 29 | } 30 | this.size++; 31 | } 32 | 33 | // insert element at the position index 34 | // of the list 35 | insertAt(element, index) { 36 | if (index < 0 || index > this.size) 37 | return console.log("Please enter a valid index."); 38 | else { 39 | // creates a new node 40 | var node = new Node(element); 41 | var curr, prev; 42 | 43 | curr = this.head; 44 | 45 | // add the element to the 46 | // first index 47 | if (index == 0) { 48 | node.next = this.head; 49 | this.head = node; 50 | } else { 51 | curr = this.head; 52 | var it = 0; 53 | 54 | // iterate over the list to find 55 | // the position to insert 56 | while (it < index) { 57 | it++; 58 | prev = curr; 59 | curr = curr.next; 60 | } 61 | 62 | // adding an element 63 | node.next = curr; 64 | prev.next = node; 65 | } 66 | this.size++; 67 | } 68 | } 69 | 70 | // removes an element from the 71 | // specified location 72 | removeFrom(index) { 73 | if (index < 0 || index >= this.size) 74 | return console.log("Please Enter a valid index"); 75 | else { 76 | var curr, prev, it = 0; 77 | curr = this.head; 78 | prev = curr; 79 | 80 | // deleting first element 81 | if (index === 0) { 82 | this.head = curr.next; 83 | } else { 84 | // iterate over the list to the 85 | // position to removce an element 86 | while (it < index) { 87 | it++; 88 | prev = curr; 89 | curr = curr.next; 90 | } 91 | 92 | // remove the element 93 | prev.next = curr.next; 94 | } 95 | this.size--; 96 | 97 | // return the remove element 98 | return curr.element; 99 | } 100 | } 101 | 102 | // removes a given element from the 103 | // list 104 | removeElement(element) { 105 | var current = this.head; 106 | var prev = null; 107 | 108 | // iterate over the list 109 | while (current != null) { 110 | // comparing element with current 111 | // element if found then remove the 112 | // and return true 113 | if (current.element === element) { 114 | if (prev == null) { 115 | this.head = current.next; 116 | } else { 117 | prev.next = current.next; 118 | } 119 | this.size--; 120 | return current.element; 121 | } 122 | prev = current; 123 | current = current.next; 124 | } 125 | return -1; 126 | } 127 | 128 | 129 | // finds the index of element 130 | indexOf(element) { 131 | var count = 0; 132 | var current = this.head; 133 | 134 | // iterate over the list 135 | while (current != null) { 136 | // compare each element of the list 137 | // with given element 138 | if (current.element === element) 139 | return count; 140 | count++; 141 | current = current.next; 142 | } 143 | 144 | // not found 145 | return -1; 146 | } 147 | 148 | // checks the list for empty 149 | isEmpty() { 150 | return this.size == 0; 151 | } 152 | 153 | // gives the size of the list 154 | size_of_list() { 155 | console.log(this.size); 156 | } 157 | 158 | 159 | // prints the list items 160 | printList() { 161 | var curr = this.head; 162 | var str = ""; 163 | while (curr) { 164 | str += curr.element + " "; 165 | curr = curr.next; 166 | } 167 | console.log(str); 168 | } 169 | 170 | } 171 | 172 | // creating an object for the 173 | // Linkedlist class 174 | var ll = new LinkedList(); 175 | 176 | // testing isEmpty on an empty list 177 | // returns true 178 | console.log(ll.isEmpty()); 179 | 180 | // adding element to the list 181 | ll.add(10); 182 | 183 | // prints 10 184 | ll.printList(); 185 | 186 | // returns 1 187 | console.log(ll.size_of_list()); 188 | 189 | // adding more elements to the list 190 | ll.add(20); 191 | ll.add(30); 192 | ll.add(40); 193 | ll.add(50); 194 | 195 | // returns 10 20 30 40 50 196 | ll.printList(); 197 | 198 | // prints 50 from the list 199 | console.log("is element removed ?" + ll.removeElement(50)); 200 | 201 | // prints 10 20 30 40 202 | ll.printList(); 203 | 204 | // returns 3 205 | console.log("Index of 40 " + ll.indexOf(40)); 206 | 207 | // insert 60 at second position 208 | // ll contains 10 20 60 30 40 209 | ll.insertAt(60, 2); 210 | 211 | ll.printList(); 212 | 213 | // returns false 214 | console.log("is List Empty ? " + ll.isEmpty()); 215 | 216 | // remove 3rd element from the list 217 | console.log(ll.removeFrom(3)); 218 | 219 | // prints 10 20 60 40 220 | ll.printList(); --------------------------------------------------------------------------------