├── .gitignore ├── Arrays ├── Extras │ ├── combination-sum.js │ ├── Shuffle-the-array.js │ ├── binary-search.js │ ├── count-of-matches-in-a-tournament.js │ ├── Number-of-good-pairs.js │ ├── Kids-with0greatest-number-of-candies.js │ ├── max-consecutive-ones-in-array.js │ ├── minimum-size-subarray-with-sum.js │ ├── remove-duplicates-from-sorted-array.js │ ├── position-to-insert.js │ ├── find-all-numbers-disappeared-in-array.js │ ├── move-zeroes-to-the-end.js │ ├── largest-continuous-increasing-subsequence.js │ ├── container-with-most-water.js │ ├── first-negative-integer-in-subarray-of-size-k.js │ ├── three-sum-closest.js │ ├── ranges-array.js │ ├── fibonacci-sequence-at-n.js │ ├── first-and-last-position-of-target-in-sorted-array.js │ ├── number-of-teams.js │ ├── reveal-cards-in-inreasing-order.js │ ├── minimum-number-operations-to-all-balls-to-each-box.js │ └── majority-element.js ├── tempCodeRunnerFile.js ├── largest-sum-contiguous-subarray.js ├── sum-of-subarray-is-0.js ├── palindrome-min-swaps.js ├── elements-occuring-more-than-n-by-k-times.js ├── check-if-array2-is-subset-of-array1.js ├── smallest-sum-subarray.js ├── longest-consecutive-subsequence.js ├── factorial-of-a-large-number.js ├── count-pairs-with-given-sum.js ├── triplet-sum-in-array.js ├── chocolate-distribution-problem.js ├── three-way-partitioning.js ├── maximum-product-subarray.js ├── reverse_an_array.js ├── move-negative-to-one-side.js ├── rearrange-array-in-alternating-positive-and-negative-items.js ├── minimum-number-of-swaps-to-bring-together.js ├── count-inversions.js ├── common-elements-in-three-sorted-arrays.js ├── merge-overlapping-intervals.js ├── minimize-maximum-difference-between-heights.js ├── duplicate-in-an-array.js ├── sort-array-of-0-1-2.js ├── buy-and-sell-stocks-to-maximize-profit.js └── next-larger-permutation.js ├── .vscode └── settings.json ├── README.md ├── last-return.js ├── contest ├── biweekly │ └── constest-51 │ │ ├── replace-all-digits-with-characters.js │ │ ├── seat-reservation-manager.js │ │ ├── closest-room.js │ │ └── max-element-after-decreasing-and-rearranging.js ├── check-if-string-is-pangram.js ├── sum-of-digits-in-base-k.js ├── weekly │ ├── contest-240 │ │ ├── maximum-subarray-min-product.js │ │ ├── maximum-distance-between-pair-of-values.js │ │ └── max-population-year.js │ └── contest-239 │ │ ├── minimum-distance-to-target-element.js │ │ ├── split-string-into-ddescending-consecutive-values.js │ │ └── minimum-adjacent-swaps-to-reach-kth-smallest.js ├── xor-sum-of-bitwise-and-pairs.js ├── find-winner-of-circular-game.js ├── integers-in-a-string.js ├── longest-substring-containing-all-vowels-in-order.js ├── minimum-ops-to-reinitialize-perm.js ├── max-icecream-bars.js └── evaluate-bracket-pairs-of-string.js ├── maychallenge ├── running-sum-of-1d-array.js ├── partitioning-into-minimum-number-of-deci-binary-numbers.js ├── to-lower-case.js ├── maximum-gap.js ├── delete-operations-on-string.js ├── coun-primes.js ├── N-queens-2.js ├── jumping-game-2.js ├── maximum-erasure-value.js ├── binary-tree-level-order-traversal.js ├── ambiguous-coordinates.js ├── binary-tree-cameras.js ├── non-decreasing-array.js ├── search-suggestion-system.js ├── evaluate-reverse-polish-notation.js ├── flatten-binary-tree-to-linkedlist.js ├── course-schedule-3.js ├── min-moves-to-equal-array-elements-2.js ├── find-and-replace-pattern.js ├── convert-sorted-list-to-balance-bst.js ├── longest-string-chain.js ├── n-queens.js ├── range-sum-query-2d.js ├── maximum-product-of-word-length.js ├── valid-number.js ├── find-duplicate-file-in-system.js ├── prefix-suffix-search.js ├── construct-array-with-multiple-sums.js └── super-palindromes.js ├── string ├── extras │ ├── minimum-swaps-to-make-strings-anagram.js │ ├── reverse-vowels.js │ ├── valid-palindrome.js │ ├── make-the-string-great.js │ ├── multiply-strings.js │ ├── delete-operations-on-strings.js │ ├── max-number-of-vowels-in-substring-of-given-length.js │ ├── decrypt-string-from-alphabet-to-integer-mapping.js │ ├── Check-if-word-equals-summation-of-two-words.js │ ├── valid-parentheses.js │ ├── Longest-Substring-Without-Repeating-Characters.js │ ├── determine-if-string-halves-are-alike.js │ ├── count-the-number-of-consistent-strings.js │ ├── destination-city.js │ ├── search-suggestion-system.js │ ├── custom-sort-string.js │ ├── group-anagrams.js │ ├── add-binary.js │ ├── valid-palindrome-2.js │ └── rearrange-words-in-string.js ├── check-if-string-is-palindrome.js ├── duplicates-in-string.js ├── print-all-subsequences-of-a-string.js ├── string-is-a-shuffle-of-2-strings-or-not.js ├── longest-repeating-subsequence.js └── check-if-strings-are-rotations-of-each-other.js ├── linked-list ├── merge-two-sorted-linked-list.js ├── remove-duplicates-from-sorted-list.js ├── swap-nodes-in-pairs.js ├── convert-binary-number-in-a-linked-list-to-integer.js ├── remove-linked-list-elements.js ├── odd-even-linked-list.js ├── linked-list-cycle.js ├── reverse-linked-list.js ├── reverse-linked-list-2.js ├── partition-list.js ├── swapping-nodes-in-linked-list.js ├── remove-duplicates-from-sorted-list-2.js ├── add-two-numbers.js ├── middle-of-the-linked-list.js ├── intersection-of-two-linked-lists.js ├── insertion-sort-list.js ├── next-greater-node-in-linked-list.js └── merge-in-between-lists.js ├── matrices ├── median-of-rowwise-sorted-matrix.js ├── max-area-rectangle-in-binary-matrix.js ├── rotate-matrix-by-90deg-clockwise.js ├── sort-matrix-row-column-wise.js ├── extras │ └── transpose-of-matrix.js ├── search-element-in-matrix.js ├── spiral-traversal-of-matrix.js └── common-elements-of-all-rows.js ├── sorting-searching ├── largest-number.js ├── sort-matrix-diagonally.js ├── intersection-of-2-arrays-2.js ├── sort-array-by-increasing-frequency.js ├── kth-strongest-values-in-an-array.js ├── range-sum-of-sorted-arrays.js ├── valid-anagram.js ├── sort-array-by-parity-2.js ├── remove-closed-intervals.js ├── largest-perimeter-triangle.js ├── least-number-of-unique-integers-after-k-removals.js ├── sort-integers-by-power-value.js └── shuffle-string.js └── most-liked-questions └── product-of-array-except-self.js /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules -------------------------------------------------------------------------------- /Arrays/Extras/combination-sum.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "better-comments.highlightPlainText": true, 3 | "codesnap.backgroundColor": "none" 4 | } -------------------------------------------------------------------------------- /Arrays/tempCodeRunnerFile.js: -------------------------------------------------------------------------------- 1 | // else { 2 | // count +=2; 3 | // prev = nums1[i]; 4 | // curr = nums1[i]; 5 | // i++;j++; 6 | // } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DSA-Javascript 2 | JavaScript based solutions for Data Structure and Algorithms based questions 3 | 4 | 5 | ### Directories are based on Data Structures and Algorithms. 6 | 7 | **There might be some common questions** 8 | -------------------------------------------------------------------------------- /last-return.js: -------------------------------------------------------------------------------- 1 | function check(n){ 2 | try { 3 | if(n.length>0) 4 | throw Error("wrong length") 5 | } 6 | finally { 7 | return "three" 8 | } 9 | } 10 | 11 | 12 | console.log(check("vinit")); 13 | console.log(check(5)); -------------------------------------------------------------------------------- /contest/biweekly/constest-51/replace-all-digits-with-characters.js: -------------------------------------------------------------------------------- 1 | var replaceDigits = function(s) { 2 | let charMap = "abcdefghijklmnopqrstuvwxyz" 3 | 4 | let i = 0,str=""; 5 | for(let i =0;inums[i] ? currSum+nums[i] : nums[i]; 7 | max = max=65 && curr<=90){ 17 | s[i] = String.fromCharCode(curr+32); 18 | } 19 | } 20 | return s.join(""); 21 | }; -------------------------------------------------------------------------------- /contest/check-if-string-is-pangram.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A pangram is a sentence where every letter of the English alphabet appears at least once. 3 | 4 | Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. 5 | */ 6 | 7 | var checkIfPangram = function(sentence) { 8 | let letterMap = {}; 9 | for(let i=0;i false 16 | console.log(FindSubArray.withSumZero(2,[10,-10]));//output -> true 17 | console.log(FindSubArray.withSumZero(5,[4 ,2 ,-3, 1, 6]));//output -> true -------------------------------------------------------------------------------- /maychallenge/maximum-gap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. 3 | 4 | You must write an algorithm that runs in linear time and uses linear extra space. 5 | */ 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number} 10 | */ 11 | var maximumGap = function(nums) { 12 | if(nums.length<=1) return 0; 13 | nums.sort((a,b)=>a-b); 14 | let max = 0,diff = 0; 15 | for(let i=1;i0){ 14 | let d = dup%10; 15 | rev = rev*10 + d; 16 | dup = parseInt(dup/10); 17 | } 18 | if(rev===num) return 1; 19 | else return 0; 20 | } 21 | } 22 | console.log(MinSwaps.toCheckPalindrome([111,222,333,444,555,666],6)); 23 | console.log(MinSwaps.toCheckPalindrome([1110,222,333,444,555,666],6)); -------------------------------------------------------------------------------- /linked-list/merge-two-sorted-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. 3 | */ 4 | 5 | 6 | var mergeTwoLists = function(l1, l2) { 7 | let dummyHead = new ListNode(); 8 | let curr = dummyHead; 9 | while(l1 && l2){ 10 | if(l1.val<=l2.val){ 11 | curr.next = l1; 12 | l1=l1.next; 13 | } 14 | else { 15 | curr.next = l2; 16 | l2=l2.next; 17 | } 18 | curr = curr.next; 19 | } 20 | if(l1===null){ 21 | curr.next = l2; 22 | } 23 | if(l2===null){ 24 | curr.next = l1; 25 | } 26 | 27 | return dummyHead.next 28 | }; -------------------------------------------------------------------------------- /matrices/median-of-rowwise-sorted-matrix.js: -------------------------------------------------------------------------------- 1 | class MedianRowSortedMatrix{ 2 | static quickSortMethod(matrix,r,c){ 3 | let i=1; 4 | let k=0,l=0; 5 | let len = r*c; 6 | let arr = []; 7 | while(i<=len){ 8 | arr.push(matrix[k][l]); 9 | if(i%r == 0){ 10 | k = i/r; 11 | l=0; 12 | } 13 | else { 14 | l++; 15 | } 16 | i++; 17 | } 18 | for(i=0;i a-b); 23 | return arr[(len-1)/2]; 24 | } 25 | } 26 | 27 | console.log("Median :",MedianRowSortedMatrix.quickSortMethod([[1, 3, 5],[2, 6, 9],[3, 6, 9]],3,3)); -------------------------------------------------------------------------------- /Arrays/Extras/count-of-matches-in-a-tournament.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *You are given an integer n, the number of teams in a tournament that has strange rules: 3 | 4 | *!If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. 5 | 6 | *!If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. 7 | 8 | *?Return the number of matches played in the tournament until a winner is decided. 9 | */ 10 | 11 | class CountMatches { 12 | static inTournament(n){ 13 | return n-1; 14 | } 15 | } 16 | 17 | console.log(CountMatches.inTournament(3)); -------------------------------------------------------------------------------- /contest/sum-of-digits-in-base-k.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. 4 | 5 | After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. 6 | */ 7 | 8 | var sumBase = function(n, k) { 9 | let num = 0; 10 | if(k!==10){ 11 | let num = 0; 12 | while(n>0){ 13 | let dig = n%k; 14 | num = num *10 + dig; 15 | n = parseInt(n / k); 16 | } 17 | num = num*10 + n; 18 | n=num; 19 | } 20 | 21 | let sum = 0; 22 | while(n>0){ 23 | let dig = n%10; 24 | sum = sum +dig; 25 | n = parseInt(n/10) 26 | } 27 | return sum; 28 | 29 | }; -------------------------------------------------------------------------------- /maychallenge/delete-operations-on-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} word1 3 | * @param {string} word2 4 | * @return {number} 5 | */ 6 | var minDistance = function(word1, word2) { 7 | let m = word1.length, n = word2.length 8 | if (m < n) [word1, word2, m, n] = [word2, word1, n, m] 9 | let WA1 = word1.split(""), WA2 = word2.split(""), 10 | dpLast = new Uint16Array(n + 1), 11 | dpCurr = new Uint16Array(n + 1) 12 | for (let i = 0; i < m; i++) { 13 | for (let j = 0; j < n; j++) 14 | dpCurr[j+1] = WA1[i] === WA2[j] 15 | ? dpLast[j] + 1 16 | : Math.max(dpCurr[j], dpLast[j+1]); 17 | [dpLast, dpCurr] = [dpCurr, dpLast] 18 | } 19 | return m + n - 2 * dpLast[n] 20 | }; 21 | 22 | minDistance("leetcode","detco"); -------------------------------------------------------------------------------- /maychallenge/coun-primes.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /** 5 | * @param {number} n 6 | * @return {number} 7 | */ 8 | var countPrimes = function(n) { 9 | let tot =0; 10 | let nums = new Array(n).fill(true); 11 | nums[0] = null; 12 | nums[1] = null; 13 | for(let i=2;i<=parseInt(Math.sqrt(n));i++){ 14 | if(nums[i]===true){ 15 | for(let j= i+i;j<=n;j += i){ 16 | if(nums[j]) nums[j] = false; 17 | } 18 | } 19 | } 20 | nums.forEach((num)=>{ 21 | if(num===true) tot++; 22 | }) 23 | return tot; 24 | }; 25 | 26 | function isPrime(num){ 27 | for(let i=2;i*i<=num;i++){ 28 | if(num%i===0) return false; 29 | } 30 | return true; 31 | } 32 | 33 | console.log(countPrimes(10)) 34 | console.log(countPrimes(2)) 35 | -------------------------------------------------------------------------------- /maychallenge/N-queens-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. 3 | 4 | Given an integer n, return the number of distinct solutions to the n-queens puzzle. 5 | */ 6 | 7 | /** 8 | * @param {number} n 9 | * @return {number} 10 | */ 11 | var totalNQueens = function(N) { 12 | let ans = 0 13 | 14 | const place = (i, vert, ldiag, rdiag) => { 15 | if (i === N) ans++ 16 | else for (let j = 0; j < N; j++) { 17 | let vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j) 18 | if (vert & vmask || ldiag & lmask || rdiag & rmask) continue 19 | place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask) 20 | } 21 | } 22 | 23 | place(0,0,0,0) 24 | return ans 25 | }; -------------------------------------------------------------------------------- /Arrays/elements-occuring-more-than-n-by-k-times.js: -------------------------------------------------------------------------------- 1 | const Sort = require("../Extras/sorting-algorithms"); 2 | 3 | class ElementsOccuring{ 4 | static moreThanNdK(arr,N,k){ 5 | let count = 0; 6 | arr = Sort.quickSort(arr); 7 | let comp = arr[0],prevPrinted; 8 | for(let i=0;iMath.floor(N/k)){ 12 | console.log("Element : ",comp); 13 | comp = null; 14 | count=0; 15 | } 16 | } 17 | else { 18 | comp = arr[i]; 19 | count=1; 20 | } 21 | } 22 | } 23 | } 24 | 25 | ElementsOccuring.moreThanNdK([2,3, 1, 2, 2, 1,6,7,7,7, 2, 3, 3,3],14,7) 26 | //[1, 1, 2, 2, 2, 2, 3, 3, 3, 3] -------------------------------------------------------------------------------- /sorting-searching/largest-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list of non-negative integers nums, arrange them such that they form the largest number. 3 | Note: The result may be very large, so you need to return a string instead of an integer. 4 | 5 | Example 1: 6 | Input: nums = [10,2] 7 | Output: "210" 8 | */ 9 | 10 | 11 | /** 12 | * @param {number[]} nums 13 | * @return {string} 14 | */ 15 | var largestNumber = function(nums) { 16 | let rst = ""; 17 | nums.sort(comparator); 18 | for (const num of nums) { 19 | rst += num; 20 | } 21 | return rst == 0 ? "0" : rst; 22 | }; 23 | 24 | var comparator = function(a, b) { 25 | const s1 = "" + a + b, 26 | s2 = "" + b + a; 27 | console.log(s1,s2); 28 | console.log(s1-s2); 29 | return s2 - s1; 30 | }; 31 | 32 | 33 | console.log(largestNumber([3,30,34,9,5])) -------------------------------------------------------------------------------- /string/extras/reverse-vowels.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string s, reverse only all the vowels in the string and return it. 3 | 4 | The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. 5 | */ 6 | 7 | /** 8 | * @param {string} s 9 | * @return {string} 10 | */ 11 | var reverseVowels = function(s) { 12 | let i=0,j=s.length - 1; 13 | s = s.split("") 14 | while(i { 17 | nums[i] = [val,i]; 18 | return; 19 | }) 20 | nums.sort((a,b)=>{ 21 | if(a[0]===b[0]) return a[1] - b[1]; 22 | else return a[0] - b[0]; 23 | }) 24 | let i=0,j=1,count =0; 25 | while(i count = ",dup[prop]); 20 | } 21 | } 22 | return dup; 23 | } 24 | } 25 | 26 | Duplicates.inString("geeksforgeeks"); 27 | Duplicates.inString("g"); -------------------------------------------------------------------------------- /contest/biweekly/constest-51/seat-reservation-manager.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | */ 4 | var SeatManager = function(n) { 5 | this.seats = new Array(n+1).fill("u"); 6 | this.seats[0] = null; 7 | }; 8 | 9 | /** 10 | * @return {number} 11 | */ 12 | SeatManager.prototype.reserve = function() { 13 | for(let i=1;ie) ub=mid-1; 20 | else lb=mid+1; 21 | } 22 | return -1; 23 | } 24 | } 25 | 26 | console.log(Subset.ofArray([11, 1, 13, 21, 3, 7],[11, 3, 7, 1])) 27 | console.log(Subset.binarySearch(3,[0,1,2,3,4,6,8,9,11],0,8)) -------------------------------------------------------------------------------- /maychallenge/jumping-game-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Your goal is to reach the last index in the minimum number of jumps. 7 | 8 | You can assume that you can always reach the last index. 9 | */ 10 | 11 | 12 | /** 13 | * @param {number[]} nums 14 | * @return {number} 15 | */ 16 | var jump = function(nums) { 17 | let currReach = 0,maxReach = 0,jumps = 0; 18 | for(let i =0;i maxReach){ 20 | maxReach = i+nums[i]; 21 | } 22 | if(i===currReach){ 23 | jumps++; 24 | currReach = maxReach; 25 | } 26 | } 27 | return jumps; 28 | }; 29 | 30 | console.log(jump([2,3,1,1,4])) 31 | console.log(jump([2,3,0,1,4])) 32 | console.log(jump([1,1,1,1])) -------------------------------------------------------------------------------- /Arrays/smallest-sum-subarray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | **Input: 4 | **nums[] = {1, 4, 45, 6, 0, 19} 5 | **target = 51 6 | *!Output: 3 7 | *?Explanation: 8 | *?Minimum length subarray is 9 | *?{4, 45, 6} 10 | */ 11 | 12 | class SmallestSum { 13 | static subArray(nums,target){ 14 | let minSize = Number.MAX_VALUE; 15 | let start = 0; 16 | let currentSum = 0; 17 | for(let end = 0;endtarget) { 20 | minSize = Math.min(minSize,end-start+1); 21 | currentSum = currentSum-nums[start]; 22 | start++; 23 | } 24 | } 25 | return minSize>nums.length?0 : minSize; 26 | } 27 | } 28 | 29 | 30 | console.log(SmallestSum.subArray([1, 4, 45, 6, 0, 19],51)); 31 | console.log(SmallestSum.subArray([1, 10, 5, 2, 7],9)); 32 | console.log(SmallestSum.subArray([2,3,1,2,4,3],7)); -------------------------------------------------------------------------------- /Arrays/Extras/Kids-with0greatest-number-of-candies.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. 3 | 4 | For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. 5 | */ 6 | 7 | /** 8 | * @param {number[]} candies 9 | * @param {number} extraCandies 10 | * @return {boolean[]} 11 | */ 12 | 13 | //*O(N) solution 14 | var kidsWithCandies = function(candies, extraCandies) { 15 | let max = 0; 16 | for(let i=0;icandies[i] ? max : candies[i]; 18 | } 19 | let bool = []; 20 | for(let i=0;i= max) bool.push(true); 22 | else bool.push(false); 23 | } 24 | return bool; 25 | }; -------------------------------------------------------------------------------- /Arrays/longest-consecutive-subsequence.js: -------------------------------------------------------------------------------- 1 | const Sort = require("../Extras/sorting-algorithms") 2 | class Solution { 3 | static findLongestConseqSubseq(arr, N){ 4 | let prevVal =arr[0],count=1,maxCount=1; 5 | arr = [...new Set(arr)] 6 | N=arr.length; 7 | arr = Sort.mergeSort(arr,"i"); 8 | for(let i=0;i 1) 18 | nmap[nums[left]]--, total -= nums[left++] 19 | best = Math.max(best, total) 20 | } 21 | return best 22 | }; -------------------------------------------------------------------------------- /string/extras/make-the-string-great.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static makeGood(s) { 3 | let len = s.length; 4 | do{ 5 | len = s.length; 6 | for(let i=0;i=65 && iCode<=90){ 11 | if(s[i+1]===sLower){ 12 | s = s.substring(0,i)+""+s.substring(i+2,s.length) 13 | } 14 | } 15 | 16 | else if(s[i+1]===sUpper){ 17 | s = s.substring(0,i)+""+s.substring(i+2,s.length) 18 | } 19 | } 20 | 21 | }while(s.length!==len) 22 | 23 | return s; 24 | } 25 | } 26 | 27 | console.log(Solution.makeGood("leEeetcode")) 28 | console.log(Solution.makeGood("aBbAcC")) 29 | console.log(Solution.makeGood("s")) -------------------------------------------------------------------------------- /Arrays/Extras/minimum-size-subarray-with-sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. 3 | */ 4 | 5 | class MinSubArray { 6 | static withSumGreaterOrEqual(target, nums){ 7 | let minSize = Number.MAX_VALUE; 8 | let start = 0; 9 | let currentSum = 0; 10 | for(let end = 0;end=target) { 13 | minSize = MinSubArray.min(minSize,end-start+1); 14 | currentSum = currentSum-nums[start]; 15 | start++; 16 | } 17 | } 18 | return minSize>nums.length?0 : minSize; 19 | } 20 | static min(a,b){ 21 | return aprevMin){ 20 | 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /maychallenge/binary-tree-level-order-traversal.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 3 | */ 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * function TreeNode(val, left, right) { 8 | * this.val = (val===undefined ? 0 : val) 9 | * this.left = (left===undefined ? null : left) 10 | * this.right = (right===undefined ? null : right) 11 | * } 12 | */ 13 | /** 14 | * @param {TreeNode} root 15 | * @return {number[][]} 16 | */ 17 | var levelOrder = function(root) { 18 | let q = [root], ans = [] 19 | while (q[0]) { 20 | let qlen = q.length, row = [] 21 | for (let i = 0; i < qlen; i++) { 22 | let curr = q.shift() 23 | row.push(curr.val) 24 | if (curr.left) q.push(curr.left) 25 | if (curr.right) q.push(curr.right) 26 | } 27 | ans.push(row) 28 | } 29 | return ans 30 | }; -------------------------------------------------------------------------------- /sorting-searching/sort-matrix-diagonally.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} mat 3 | * @return {number[][]} 4 | */ 5 | 6 | 7 | var diagonalSort = function(mat) { 8 | let m = mat[0].length,n=mat.length; 9 | console.log("Original Matrix : "); 10 | console.table(mat) 11 | const sort = function(i,j){ 12 | let a=i,b=j; 13 | let diag = []; 14 | while(aa-b); 19 | a=i;b=j; 20 | let count = 0; 21 | while(a O(N) solution 6 | /** 7 | * Definition for singly-linked list. 8 | * function ListNode(val, next) { 9 | * this.val = (val===undefined ? 0 : val) 10 | * this.next = (next===undefined ? null : next) 11 | * } 12 | */ 13 | /** 14 | * @param {ListNode} head 15 | * @return {ListNode} 16 | */ 17 | var swapPairs = function(head) { 18 | let temp = new ListNode(0); 19 | temp.next = head; 20 | let curr = temp; 21 | while(curr.next && curr.next.next){ 22 | let first = curr.next; 23 | let second = curr.next.next; 24 | first.next = second.next; 25 | curr.next = second; 26 | curr.next.next = first; 27 | curr = curr.next.next; 28 | } 29 | return temp.next; 30 | }; -------------------------------------------------------------------------------- /matrices/rotate-matrix-by-90deg-clockwise.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Matrix{ 4 | 5 | //*Time -> O(n^2),Space -> O(1) 6 | static rotate(matrix) { 7 | let N = matrix.length; 8 | 9 | //!transpose of the matrix 10 | for(let i =0;i { 8 | let n = str.length 9 | if (dec && str[n-1] === "0") return false 10 | if (n !== 1 && dec !== 1 && str[0] === "0") return false 11 | return true 12 | } 13 | for (let i = 2; i < S.length - 1; i++) { 14 | let xStr = S.slice(1,i), yStr = S.slice(i, S.length - 1), 15 | xPoss = [] 16 | for (let j = 0; j < xStr.length; j++) 17 | if (isValid(xStr, j)) 18 | xPoss.push(xStr.slice(0,j) + (j ? "." : "") + xStr.slice(j)) 19 | for (let j = 0; j < yStr.length; j++) 20 | if (isValid(yStr, j)) { 21 | let y = yStr.slice(0,j) + (j ? "." : "") + yStr.slice(j) 22 | for (let x of xPoss) 23 | ans.push(`(${x}, ${y})`) 24 | } 25 | } 26 | return ans 27 | }; -------------------------------------------------------------------------------- /maychallenge/binary-tree-cameras.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a binary tree, we install cameras on the nodes of the tree. 3 | 4 | Each camera at a node can monitor its parent, itself, and its immediate children. 5 | 6 | Calculate the minimum number of cameras needed to monitor all nodes of the tree. 7 | */ 8 | 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * function TreeNode(val, left, right) { 13 | * this.val = (val===undefined ? 0 : val) 14 | * this.left = (left===undefined ? null : left) 15 | * this.right = (right===undefined ? null : right) 16 | * } 17 | */ 18 | /** 19 | * @param {TreeNode} root 20 | * @return {number} 21 | */ 22 | var minCameraCover = function(root) { 23 | let ans = 0 24 | const dfs = node => { 25 | if (!node) return 0 26 | let val = dfs(node.left) + dfs(node.right) 27 | if (val === 0) return 3 28 | if (val < 3) return 0 29 | ans++ 30 | return 1 31 | } 32 | return dfs(root) > 2 ? ans + 1 : ans 33 | }; -------------------------------------------------------------------------------- /maychallenge/non-decreasing-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. 3 | 4 | We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). 5 | 6 | 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {boolean} 12 | */ 13 | var checkPossibility = function(nums) { 14 | for (let i = 1, err = 0; i < nums.length; i++) 15 | if (nums[i] < nums[i-1]) 16 | if (err++ || (i > 1 && i < nums.length - 1 && nums[i-2] > nums[i] && nums[i+1] < nums[i-1])) 17 | return false 18 | return true 19 | }; 20 | 21 | console.log(checkPossibility([1])) 22 | console.log(checkPossibility([1,3])) 23 | console.log(checkPossibility([8,7,6,5,4,3,2,1,0])) 24 | console.log(checkPossibility([8,2,7])) 25 | console.log(checkPossibility([8,2,7,6])) 26 | console.log(checkPossibility([-1,4,2,3])) 27 | console.log(checkPossibility([3,4,2,3])) -------------------------------------------------------------------------------- /contest/xor-sum-of-bitwise-and-pairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. 3 | 4 | For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3. 5 | You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. 6 | 7 | Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length. 8 | 9 | Return the XOR sum of the aforementioned list. 10 | */ 11 | 12 | 13 | /** 14 | * @param {number[]} arr1 15 | * @param {number[]} arr2 16 | * @return {number} 17 | */ 18 | var getXORSum = function(arr1, arr2) { 19 | let xor1=0,xor2=0; 20 | for(let i=0;i slow, faster than 6% 20 | var getDecimalValue = function(head) { 21 | let binary = []; 22 | while(head.next!==null){ 23 | binary = [head.val,...binary]; 24 | head = head.next; 25 | } 26 | binary = [head.val,...binary]; 27 | let dec = 0; 28 | for(let i=0;i0){ 29 | for(let j=i+1;j c) right-- 17 | for (let j = 0; j < 3 && left + j <= right; j++) 18 | res.push(P[left+j]) 19 | ans.push(res) 20 | } 21 | return ans 22 | }; -------------------------------------------------------------------------------- /linked-list/remove-linked-list-elements.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val, next) { 8 | * this.val = (val===undefined ? 0 : val) 9 | * this.next = (next===undefined ? null : next) 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @param {number} val 15 | * @return {ListNode} 16 | */ 17 | var removeElements = function(head, val) { 18 | if(!head) return head; 19 | let curr = head, prev = null; 20 | while(curr && head){ 21 | if(curr.val===val){ 22 | if(prev===null) { 23 | head = head.next; 24 | curr = head; 25 | } 26 | else { 27 | prev.next = curr.next; 28 | curr = prev.next; 29 | } 30 | } 31 | else { 32 | prev = curr; 33 | curr = curr.next; 34 | } 35 | } 36 | return head; 37 | };git -------------------------------------------------------------------------------- /maychallenge/evaluate-reverse-polish-notation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | Valid operators are +, -, *, and /. Each operand may be an integer or another expression. 4 | 5 | Note that division between two integers should truncate toward zero. 6 | 7 | It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. 8 | 9 | Example 1: 10 | Input: tokens = ["2","1","+","3","*"] 11 | Output: 9 12 | Explanation: ((2 + 1) * 3) = 9 13 | */ 14 | 15 | 16 | /** 17 | * @param {string[]} tokens 18 | * @return {number} 19 | */ 20 | let a, b 21 | const evaluate = {"+": ()=>a+b, "-": ()=>a-b, "*": ()=>a*b, "/": ()=>~~(a/b)} 22 | 23 | var evalRPN = function(tokens) { 24 | let stack = [] 25 | for (let t of tokens) { 26 | if (evaluate[t]) { 27 | b = stack.pop(), a = stack.pop() 28 | stack.push(evaluate[t]()) 29 | } else stack.push(~~t) 30 | } 31 | return stack[0] 32 | }; -------------------------------------------------------------------------------- /sorting-searching/sort-array-by-increasing-frequency.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. 3 | 4 | Return the sorted array. 5 | */ 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number[]} 10 | */ 11 | var frequencySort = function(nums) { 12 | let freq = {}; 13 | for(let i=0;i { 19 | if(a[1]===b[1]){ 20 | return b[0]-a[0] 21 | } 22 | else return a[1]-b[1]; 23 | }) 24 | console.log(freq) 25 | let res = []; 26 | for(let i=0;i O(n) 20 | static numbersInArray(nums){ 21 | let missing=[]; 22 | let length = nums.length; 23 | for(let i =0;i0) missing.push(i+1); 29 | } 30 | return missing; 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /linked-list/odd-even-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. 3 | 4 | The first node is considered odd, and the second node is even, and so on. 5 | 6 | Note that the relative order inside both the even and odd groups should remain as it was in the input. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * function ListNode(val, next) { 12 | * this.val = (val===undefined ? 0 : val) 13 | * this.next = (next===undefined ? null : next) 14 | * } 15 | */ 16 | /** 17 | * @param {ListNode} head 18 | * @return {ListNode} 19 | */ 20 | var oddEvenList = function(head) { 21 | if (!head) return head; 22 | 23 | let odd = head,oddHead = head, 24 | even = head.next,evenHead = head.next; 25 | while(even && even.next){ 26 | odd.next = odd.next.next; 27 | even.next = even.next.next; 28 | odd = odd.next; 29 | even = even.next; 30 | } 31 | odd.next = evenHead; 32 | return oddHead; 33 | }; -------------------------------------------------------------------------------- /Arrays/Extras/move-zeroes-to-the-end.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | */ 4 | /** 5 | * Input: [0,1,0,3,12] -> [12,3,0,1,0] -> [1,0,3,12,0] -> [1,12,3,0,0] -> [1,3,12,0,0] 6 | Output: [1,3,12,0,0] 7 | */ 8 | 9 | class MoveZeroes{ 10 | static toEnd(nums){ 11 | let start=0,end=nums.length-1; 12 | while(startmax ? r-l+1 : max; 24 | if(nums[i]>=nums[i+1]) {l=i+1;r=i+1;} 25 | } 26 | return max; 27 | } 28 | } -------------------------------------------------------------------------------- /linked-list/reverse-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list, reverse the list, and return the reversed list. 3 | 4 | 5 | */ 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * function ListNode(val, next) { 10 | * this.val = (val===undefined ? 0 : val) 11 | * this.next = (next===undefined ? null : next) 12 | * } 13 | */ 14 | /** 15 | * @param {ListNode} head 16 | * @return {ListNode} 17 | */ 18 | 19 | //? faster than 29% and memory efficient more than 95%g 20 | var reverseList = function(head) { 21 | let prev = null,next; 22 | while(head!==null){ 23 | next = head.next; 24 | head.next = prev; 25 | prev = head; 26 | head = next; 27 | } 28 | head = prev; 29 | return head; 30 | }; 31 | 32 | //* faster than 84% 33 | var reverseList = function(head){ 34 | if(!head) return null; 35 | let current = head; 36 | let prev = null; 37 | let next = null; 38 | 39 | while(current) 40 | { 41 | next = current.next; 42 | current.next = prev; 43 | prev = current; 44 | current = next; 45 | } 46 | head = prev; 47 | return head; 48 | } -------------------------------------------------------------------------------- /linked-list/reverse-linked-list-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val, next) { 8 | * this.val = (val===undefined ? 0 : val) 9 | * this.next = (next===undefined ? null : next) 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @param {number} left 15 | * @param {number} right 16 | * @return {ListNode} 17 | */ 18 | 19 | //* O(N) time -> faster than 79% 20 | //* O(1) space -> faster than 90% 21 | var reverseBetween = function(head, m, n) { 22 | let start = head, cur = head; 23 | let i = 1; 24 | while (i < m) { 25 | start = cur; 26 | cur = cur.next; 27 | i++; 28 | } 29 | let prev = null, tail = cur; 30 | while (i <= n) { 31 | let next = cur.next; 32 | cur.next = prev; 33 | prev = cur; 34 | cur = next; 35 | i++; 36 | } 37 | start.next = prev; 38 | tail.next = cur; 39 | return m == 1 ? prev : head; 40 | 41 | }; -------------------------------------------------------------------------------- /contest/find-winner-of-circular-game.js: -------------------------------------------------------------------------------- 1 | // function findTheWinner(n, k) { 2 | // let nums = [] 3 | // for(let i=1;i<=n;i++){ 4 | // nums[i-1]=i; 5 | // } 6 | // console.log(nums); 7 | // let head = 0; 8 | // let count =0; 9 | // while(nums.length!==1){ 10 | // console.log(nums) 11 | // count = head + k-1; 12 | // while(count>=nums.length){ 13 | // console.log("Before ->",count) 14 | // count = count - nums.length; 15 | // console.log(count) 16 | // } 17 | // nums.splice(count,1); 18 | // head = count; 19 | // } 20 | // console.log(nums[0]); 21 | // } 22 | 23 | //?Topper solution 24 | function findTheWinner(n,k){ 25 | let friends = [] 26 | for(let i=0;i O(N) , faster than 75% 21 | var partition = function(head, x) { 22 | let slowHead = new ListNode(0); 23 | let fastHead = new ListNode(0); 24 | let slow = slowHead,fast =fastHead; 25 | while(head!==null){ 26 | if(head.val |arr[j] - m| where m is the median of the array. 5 | If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j]. 6 | 7 | Return a list of the strongest k values in the array. return the answer in any arbitrary order. 8 | */ 9 | 10 | /** 11 | * @param {number[]} arr 12 | * @param {number} k 13 | * @return {number[]} 14 | */ 15 | 16 | //?Faster than 62% -> O(N) solution 17 | var getStrongest = function(arr, k) { 18 | let n = arr.length; 19 | arr.sort((a,b)=>a-b); 20 | let m = arr[parseInt((n-1)/2)]; 21 | arr.sort((a,b)=>{ 22 | if(Math.abs(a-m)===Math.abs(b-m)){ 23 | return b-a; 24 | } 25 | else return Math.abs(b-m)-Math.abs(a-m) 26 | }) 27 | return arr.slice(0,k); 28 | }; 29 | 30 | 31 | console.log(getStrongest([1,2,3,4,5],2)) 32 | console.log(getStrongest([1,1,3,5,5],2)) 33 | console.log(getStrongest([6,7,11,7,6,8],5)) 34 | console.log(getStrongest([6,-3,7,2,11],3)) 35 | console.log(getStrongest([-7,22,17,3],2)) -------------------------------------------------------------------------------- /Arrays/triplet-sum-in-array.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //Function to find if there exists a triplet in the 3 | //array arr[] which sums up to X. 4 | find3Numbers(arr, N, X) 5 | { 6 | //your code here 7 | arr.sort((a,b) => a-b); 8 | 9 | const res = []; 10 | 11 | for (let i = 0; i < arr.length -2; i+= 1){ 12 | if (i === 0 || arr[i] !== arr[i - 1]){ 13 | twoSum(arr, i + 1, res, X-arr[i]); 14 | } 15 | } 16 | 17 | return res.length>=1?1 : 0; 18 | } 19 | } 20 | var twoSum = function(nums, left, res, target) { 21 | let right = nums.length -1; 22 | 23 | while(left < right){ 24 | const low = nums[left], high = nums[right]; 25 | if (low + high < target){ 26 | left+= 1; 27 | } else if (low + high > target){ 28 | right-= 1; 29 | } else { 30 | res.push([low, high , -target]); 31 | // avoid duplicates 32 | while(left < right && low === nums[left +1]) left+= 1; 33 | while (left < right && high === nums[right - 1]) right-= 1; 34 | left+= 1; 35 | right-= 1; 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /string/extras/multiply-strings.js: -------------------------------------------------------------------------------- 1 | //?accepted but slow 2 | // function multiplyStrings(num1,num2){ 3 | // let m=num1.length,n=num2.length; 4 | // let vals = new Array(n+m).fill(0); 5 | // for(let i=m-1;i>=0;i--){ 6 | // for(let j=n-1;j>=0;j--){ 7 | // let curr = ((num1[i]-0) * (num2[j]-0)); 8 | // let sum = vals[i+j+1] + curr; 9 | // vals[i+j] += parseInt(sum/10); 10 | // vals[i+j+1] = sum%10; 11 | // } 12 | // } 13 | // return vals.join('').replace(/^0+/, ''); 14 | // } 15 | //*accepted and faster than 97% 16 | function multiplyStrings(num1,num2){ 17 | if(!+num1 || !+num2) return '0' 18 | const prod = Array(num1.length + num2.length).fill(0); 19 | let currIdx = prod.length-1; 20 | 21 | for(let i = num1.length-1; i >= 0; i--) { 22 | let idx = currIdx--; 23 | 24 | for(let j = num2.length-1; j >= 0; j--) { 25 | const res = +num1[i] * +num2[j] + prod[idx]; 26 | prod[idx] = res % 10; 27 | prod[--idx] += Math.floor(res / 10); 28 | } 29 | } 30 | return prod.join('').replace(/^0+/, '') 31 | } 32 | 33 | console.log(multiplyStrings("3467","3456235")); -------------------------------------------------------------------------------- /sorting-searching/range-sum-of-sorted-arrays.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the array nums consisting of n positive integers. You computed the sum of all non-empty continous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. 3 | 4 | Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7. 5 | */ 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @param {number} n 10 | * @param {number} left 11 | * @param {number} right 12 | * @return {number} 13 | */ 14 | 15 | //?faster than 75% 16 | var rangeSum = function(nums, n, left, right) { 17 | let sums = []; 18 | for(let i=0;ia-b) 25 | let sum = 0; 26 | for(let i=left-1;i a[0]-b[0]); 4 | for(let i =0;i=rooms[j][1]) found = j; 9 | prevDiff =Math.abs(queries[i][0]-rooms[j][0]); 10 | } 11 | if(found===null) res.push(-1); 12 | else res.push(found); 13 | rooms.splice(found,1); 14 | } 15 | } 16 | console.log(res); 17 | }; 18 | 19 | 20 | class Search{ 21 | static binarySearch(arr,lo,hi,tar){ 22 | while(lo<=hi){ 23 | let mid = parseInt((lo+hi)/2); 24 | if(tar===arr[mid][0]){ 25 | return mid; 26 | } 27 | else if(tarn) return -1; 14 | a = Sort.quickSort(a); 15 | let diff = 0,minDiff = Number.MAX_VALUE; 16 | for(let i =0;i= k) { // remove window's first item 20 | if (vowels.indexOf(s[i - k]) > -1) { 21 | count--; 22 | } 23 | } 24 | // add current char to window 25 | if (vowels.indexOf(s[i]) > -1) { 26 | count++; 27 | max = Math.max(max, count); 28 | if (max === k) return k; 29 | } 30 | } 31 | return max; 32 | } 33 | } 34 | 35 | 36 | console.log(Solution.maxVowels("weallloveyou",7)) -------------------------------------------------------------------------------- /string/print-all-subsequences-of-a-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *Given a string, we have to find out all subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. 3 | **Examples: 4 | 5 | *?Input : abc 6 | *?Output : a, b, c, ab, bc, ac, abc 7 | *? 8 | *?Input : aaa 9 | *?Output : a, aa, aaa 10 | */ 11 | 12 | class Solution { 13 | static printSubsequences(s){ 14 | let l = s.length; 15 | let subsequences = []; 16 | for(let i=0;i0)){ 23 | prevNeg++; 24 | } 25 | if(arr[prevNeg]<0){ 26 | firstNegative = arr[prevNeg]; 27 | } 28 | else { 29 | firstNegative=0; 30 | } 31 | console.log(firstNegative); 32 | } 33 | } 34 | } 35 | 36 | FirstNegativeInteger.inSubArray( 5,[-8, 2, 3, -6, 10],2); -------------------------------------------------------------------------------- /Arrays/three-way-partitioning.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** Given an array of size N and a range [a, b]. The task is to partition the array around the range such that array is divided into three parts. 3 | **1) All elements smaller than a come first. 4 | **2) All elements in range a to b come next. 5 | **3) All elements greater than b appear in the end. 6 | **The individual elements of three sets can appear in any order. You are required to return the modified array. 7 | 8 | 9 | */ 10 | 11 | const Sort = require("../Extras/sorting-algorithms"); 12 | class Solution { 13 | //Function to partition the array around the range such 14 | //that array is divided into three parts. 15 | static threeWayPartition(array, a, b) 16 | { 17 | //your code here 18 | array = Sort.mergeSort(array,"i"); 19 | let parted = 1; 20 | for(let i =0;ia || array[i+1]b || array[i+1] { 25 | nArr[index] = parseInt(num); 26 | }); 27 | nArr = nArr.sort((a,b)=> a-b); 28 | let i =0; 29 | while(i= arr[i] for every 1 <= i < arr.length. 9 | 10 | */ 11 | 12 | /** 13 | * @param {number[]} nums1 14 | * @param {number[]} nums2 15 | * @return {number} 16 | */ 17 | var maxDistance = function(nums1, nums2) { 18 | let i=0,j=0,max=0; 19 | while(i overall =15;start=0,end=1; 4 | * at end=2 -> 0 ,so we make start=end; 5 | * [6,3] ->curr>overall -> overall = curr = 18 6 | * [6,3,-1] -> negative ,still curr=-18, waiting for another negative 7 | * at end=6 -> 0, so we make start =end; 8 | * [7,3] ->curr>overall -> overall=curr =21; 9 | * [7,3,-1] -> negative,still curr = -21 10 | * [7,3,-1,-2] -> negative, but curr>overall -> overall = curr = 42 11 | */ 12 | 13 | 14 | class Solution { 15 | static maxProduct(arr,n){ 16 | let max = arr[0]; 17 | let minProd = arr[0],maxProd = arr[0],choice1,choice2; 18 | for(let i=1;i [ 'Grapes', 'Apple', 'Orange' ] 40 | console.log(Reverse.reverseArray([4, 5, 1, 2]) );//output -> [ 2, 1, 5, 4 ] 41 | console.log(Reverse.reverseArray([4, 5, 1, 2,11,25,4]));//output -> [ 4, 25, 11, 2, 1 , 5, 4] -------------------------------------------------------------------------------- /linked-list/remove-duplicates-from-sorted-list-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * function ListNode(val, next) { 8 | * this.val = (val===undefined ? 0 : val) 9 | * this.next = (next===undefined ? null : next) 10 | * } 11 | */ 12 | /** 13 | * @param {ListNode} head 14 | * @return {ListNode} 15 | */ 16 | 17 | //[1,2,4,4,4,4,5,6] 18 | var deleteDuplicates = function(head) { 19 | let curr = head, arr = []; 20 | while(curr){ 21 | arr.push(curr.val); 22 | curr = curr.next; 23 | } 24 | let i=0,j=1; 25 | while(i O(max(M,N)) solution 18 | var addTwoNumbers = function(l1, l2) { 19 | let carry = 0; 20 | let head = new ListNode(0); 21 | let l3 = head; 22 | while(l2!==null || l1!==null){ 23 | let sum=0; 24 | let l1Val = l1 ?l1.val : 0; 25 | let l2Val = l2 ? l2.val :0; 26 | sum = l1Val+l2Val+carry; 27 | carry = parseInt(sum/10); 28 | let dig = sum%10; 29 | let newNode = new ListNode(dig); 30 | l3.next = newNode; 31 | l3 = l3.next; 32 | l1 = l1 &&l1.next; 33 | l2 = l2 && l2.next; 34 | } 35 | if(carry){ 36 | let newNode = new ListNode(carry); 37 | l3.next = newNode; 38 | l3 = l3.next; 39 | } 40 | return head.next; 41 | }; -------------------------------------------------------------------------------- /Arrays/Extras/three-sum-closest.js: -------------------------------------------------------------------------------- 1 | /** 2 | *! Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 3 | 4 | **Example 1: 5 | 6 | **Input: nums = [-1,2,1,-4], target = 1 7 | **Output: 2 8 | **Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 9 | */ 10 | 11 | class ThreeSum { 12 | static closest(nums,target) { 13 | let len = nums.length; 14 | if(len<3) return undefined; 15 | let sum = nums[0] + nums[1] + nums[len-1]; 16 | nums = nums.sort((a,b) => a-b); 17 | for(let i=0;itarget){ 22 | b--; 23 | } 24 | else { 25 | a++; 26 | } 27 | if(Math.abs(sum-target)>Math.abs(currSum-target)) sum = currSum; 28 | } 29 | } 30 | return sum; 31 | } 32 | } 33 | 34 | console.log(ThreeSum.closest([-1,2,1,-4],1)); 35 | console.log(ThreeSum.closest([-1,3,6,3,-5,0],1)); 36 | console.log(ThreeSum.closest([0,2,1,-3],1)); -------------------------------------------------------------------------------- /string/extras/decrypt-string-from-alphabet-to-integer-mapping.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows: 3 | 4 | *?Characters ('a' to 'i') are represented by ('1' to '9') respectively. 5 | *?Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. 6 | **Return the string formed after mapping. 7 | 8 | *!It's guaranteed that a unique mapping will always exist. 9 | */ 10 | 11 | class Solution { 12 | 13 | //?Time -> O(n) : 84.05% ,space -> O(n) : 82.06% 14 | static freqAlphabets(s){ 15 | let encryption = " abcdefghijklmnopqrstuvwxyz"; 16 | let decrypted = ""; 17 | let i=0; 18 | while(i ",Number(s.substr(i,2)),", value -> ",encryption[Number(s.substr(i,2))]) 21 | decrypted += encryption[Number(s.substr(i,2))]; 22 | i +=3; 23 | } 24 | else { 25 | console.log("index -> ",Number(s.substr(i,1)),", value -> ",encryption[Number(s.substr(i,1))]) 26 | decrypted += encryption[Number(s.substr(i,1))]; 27 | i++; 28 | } 29 | } 30 | console.log(decrypted); 31 | return decrypted; 32 | } 33 | } 34 | 35 | 36 | console.log(Solution.freqAlphabets("2711#5315#1")); -------------------------------------------------------------------------------- /matrices/extras/transpose-of-matrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | *! Given a 2D integer array matrix, return the transpose of matrix. 3 | **The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. 4 | */ 5 | 6 | class Matrix{ 7 | static transpose(matrix){ 8 | let m = matrix.length; 9 | let n = matrix[0].length; 10 | console.log("Original matrix :"); 11 | Matrix.printMatrix(matrix,m,n); 12 | let transpose = []; 13 | 14 | //!slow solution 15 | for(let i =0;i matrix.map(b => b[i])); 28 | 29 | } 30 | static printMatrix(mat,n,m){ 31 | for(let i=0;i npm install --save @datastructures-js/priority-queue 17 | const { MinPriorityQueue, MaxPriorityQueue } = require('@datastructures-js/priority-queue'); 18 | var scheduleCourse = function(courses) { 19 | courses.sort((a,b) => a[1] - b[1]) 20 | let total = 0, pq = new MaxPriorityQueue({priority: x => x}) 21 | console.log(pq) 22 | for (let [dur, end] of courses) 23 | if (dur + total <= end) 24 | total += dur, pq.enqueue(dur) 25 | else if (pq.front() && pq.front().element > dur) 26 | total += dur - pq.dequeue().element, pq.enqueue(dur) 27 | return pq.size() 28 | }; 29 | 30 | 31 | 32 | 33 | 34 | console.log(scheduleCourse([[5,5],[4,6],[2,6]])); 35 | console.log(scheduleCourse([[100,200],[200,1300],[1000,1250],[2000,3200]])); -------------------------------------------------------------------------------- /maychallenge/min-moves-to-equal-array-elements-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. 3 | 4 | In one move, you can increment or decrement an element of the array by 1. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,2,3] 11 | Output: 2 12 | Explanation: 13 | Only two moves are needed (remember each move increments or decrements one element): 14 | [1,2,3] => [2,2,3] => [2,2,2] 15 | */ 16 | 17 | /** 18 | * @param {number[]} nums 19 | * @return {number} 20 | */ 21 | 22 | //!wrong solution 23 | // var minMoves2 = function(nums) { 24 | // nums.sort((a,b)=> a-b); 25 | // let mid = Math.floor((nums[0]+nums[nums.length-1])/2); 26 | // let count=0; 27 | // for(let i=0;i faster than 82% 34 | var minMoves2 = function(nums) { 35 | nums.sort((a,b)=> a-b); 36 | 37 | //we need to find the value of the mid of array and not the avg of first and last elements of array(this is done in the above solution) 38 | let mid = nums[Math.floor(nums.length/2)]; 39 | let count=0; 40 | for(let i=0;i 0, 'b' -> 1, 'c' -> 2, etc.). 3 | 4 | The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. 5 | 6 | For example, if s = "acb", we concatenate each letter's letter value, resulting in "021". After converting it, we get 21. 7 | You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. 8 | 9 | Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise. 10 | */ 11 | 12 | //? O(N) -> faster than 58.32% 13 | /** 14 | * @param {string} firstWord 15 | * @param {string} secondWord 16 | * @param {string} targetWord 17 | * @return {boolean} 18 | */ 19 | var isSumEqual = function(firstWord, secondWord, targetWord) { 20 | if((sum(firstWord)+sum(secondWord))=== sum(targetWord)) return true; 21 | return false; 22 | }; 23 | 24 | var sum = function(str){ 25 | let tot = ""; 26 | for(let i=0;i { 19 | if (!codex.has(char)) 20 | codex.set(char, String.fromCharCode(97 + codex.size)) 21 | return codex.get(char) 22 | } 23 | const compare = word => { 24 | codex.clear() 25 | for (let i = 0; i < word.length; i++) 26 | if (translate(word[i]) !== cipher[i]) 27 | return 28 | ans.push(word) 29 | } 30 | let cipher = new Array(pattern.length) 31 | for (let i = 0; i < pattern.length; i++) 32 | cipher[i] = translate(pattern.charAt(i)) 33 | words.forEach(compare) 34 | return ans 35 | }; -------------------------------------------------------------------------------- /linked-list/middle-of-the-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-empty, singly linked list with head node head, return a middle node of linked list. 3 | If there are two middle nodes, return the second middle node. 4 | 5 | Example 1: 6 | Input: [1,2,3,4,5] 7 | Output: Node 3 from this list (Serialization: [3,4,5]) 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * function ListNode(val, next) { 13 | * this.val = (val===undefined ? 0 : val) 14 | * this.next = (next===undefined ? null : next) 15 | * } 16 | */ 17 | /** 18 | * @param {ListNode} head 19 | * @return {ListNode} 20 | */ 21 | 22 | //?linear -> Time O(N),space O(1) -> faster than 34% 23 | // var middleNode = function(head) { 24 | // let len = 0; 25 | // let slow = head; 26 | // let fast = head 27 | // while(fast&& fast.next){ 28 | // slow = slow.next; 29 | // fast = fast.next.next; 30 | // } 31 | 32 | // return slow; 33 | // }; 34 | //*linear solution -> Time O(N),space O(N) -> faster than 86% 35 | var middleNode = function(head) { 36 | let len = 0; 37 | let headCopy = head; 38 | while(headCopy.next!==null){ 39 | len++; 40 | headCopy = headCopy.next; 41 | } 42 | len++; 43 | let mid = parseInt(len/2) 44 | for(let i=0;i",hash); 15 | hash[s[bPoint]] =1; 16 | console.log("hash after adding ->",hash); 17 | hashLen++; 18 | console.log("hash length ->",hashLen); 19 | bPoint++; 20 | console.log("max before ->",max); 21 | max = Math.max(max,hashLen); 22 | console.log("max after ->",max); 23 | } 24 | else { 25 | console.log("hash before deleting ->",hash); 26 | hash[s[aPoint]] = undefined; 27 | console.log("hash after deleting ->",hash); 28 | aPoint++; 29 | hashLen--; 30 | console.log("hash length ->",hashLen); 31 | } 32 | } 33 | return max; 34 | } 35 | } 36 | 37 | console.log(NonRepeating.lengthOfLongestSubstring("abcabcbb")) -------------------------------------------------------------------------------- /string/extras/determine-if-string-halves-are-alike.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | //slowest solution with most efficient space 4 | static halvesAreAlike(s){ 5 | let vowels = "aeiouAEIOU"; 6 | let mid = s.length / 2, ans = 0 7 | for (let i = 0, j = mid; i < mid; i++, j++) 8 | ans += vowels.includes(s.charAt(i)) - vowels.includes(s.charAt(j)) 9 | return ans === 0 10 | } 11 | 12 | 13 | // static halvesAreAlike(s){ 14 | // let mid = (s.length)/2; 15 | // let a = s.substr(0,mid); 16 | // let b = s.substr(mid,mid); 17 | // let reg = /[aeiou]/gi; 18 | // a = a.match(reg); 19 | // b = b.match(reg); 20 | 21 | //?faster than O(n^2) 22 | //? return (a&&b) ? a.length === b.length : a==null && b===null; 23 | 24 | 25 | //!slowest approach -> O(n^2) 26 | //! for(let i=0;i { 30 | if (j < i) return null 31 | let mid = i + j >> 1, node = new TreeNode() 32 | node.left = treeify(i, mid - 1) 33 | node.val = curr.val, curr = curr.next 34 | node.right = treeify(mid + 1, j) 35 | return node 36 | } 37 | curr = head 38 | return treeify(1, count) 39 | }; -------------------------------------------------------------------------------- /sorting-searching/valid-anagram.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two strings s and t, return true if t is an anagram of s, and false otherwise. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: s = "anagram", t = "nagaram" 9 | Output: true 10 | */ 11 | 12 | 13 | /** 14 | * @param {string} s 15 | * @param {string} t 16 | * @return {boolean} 17 | */ 18 | 19 | //*faster than 65%, efficient than 73% 20 | var isAnagram = function(s, t) { 21 | if(s.length!==t.length) return false; 22 | let map = {}; 23 | for(let i=0;i0) return false; 34 | } 35 | return true; 36 | }; 37 | //?slower solution 38 | // var isAnagram = function(s,t){ 39 | // if(s.length!==t.length) return false; 40 | // s = s.split("").sort().join(""); 41 | // t = t.split("").sort().join(""); 42 | // return s===t; 43 | // } 44 | 45 | console.log(`\n\n"anagram" and "nagaram" are ANAGRAM STRINGS ->`,isAnagram("anagram","nagaram"),"\n\n\n"); 46 | console.log(`"anagram" and "magaram" are ANAGRAM STRINGS ->`,isAnagram("anagram","magaram"),"\n\n\n"); -------------------------------------------------------------------------------- /string/string-is-a-shuffle-of-2-strings-or-not.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** 1XY2 is a valid shuffle of XY and 12 3 | ** Y12X is not a valid shuffle of XY and 12 4 | *?In the above example, we have a string array named results. It contains two strings: 1XY2 and Y12X. We are checking if these two strings are valid shuffle of strings first(XY) and second(12). 5 | 6 | *?Here, the program says 1XY2 is a valid shuffle of XY and 12. However, Y12X is not a valid shuffle. 7 | 8 | *!This is because Y12X has altered the order of string XY. Here, Y is used before X. Hence, to be a valid shuffle, the order of string should be maintained. 9 | */ 10 | 11 | class Shuffle { 12 | static checker(s1,s2,res){ 13 | let l1 = s1.length; 14 | let l2 = s2.length; 15 | let l = res.length; 16 | if((l1+l2)!==l) return false; 17 | let i=0,j=0,k=0; 18 | while(k true 29 | console.log(Shuffle.checker("XY","12","1XY2"))// RETURNS -> true 30 | console.log(Shuffle.checker("XY","12","1X2Y"))// RETURNS -> true 31 | console.log(Shuffle.checker("XY","12","Y12X"))// RETURNS -> false 32 | console.log(Shuffle.checker("XY","12","2X1Y"))// RETURNS -> false -------------------------------------------------------------------------------- /Arrays/Extras/ranges-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given a sorted unique integer array nums. 3 | 4 | Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. 5 | 6 | Each range [a,b] in the list should be output as: 7 | "a->b" if a != b 8 | "a" if a == b 9 | 10 | Example 1: 11 | Input: nums = [0,1,2,4,5,7] 12 | Output: ["0->2","4->5","7"] 13 | */ 14 | 15 | class ArraySummary { 16 | static ranges(nums) { 17 | let len = nums.length; 18 | if(len===0) return nums; 19 | if(len===1) return [`${nums[0]}`] 20 | let rangesArr = []; 21 | for(let i=0;i"+nums[i]); 28 | }else{ 29 | rangesArr.push(a+""); 30 | } 31 | } 32 | return rangesArr; 33 | } 34 | } 35 | 36 | console.log(ArraySummary.ranges([0,1,2,4,5,7]))//[ '0->2', '4->5', '7' ] 37 | console.log(ArraySummary.ranges([0,2,3,4,6,8,9]))//[ '0', '2->4', '6', '8->9' ] 38 | console.log(ArraySummary.ranges([]))//[] 39 | console.log(ArraySummary.ranges([-1]))//["-1"] 40 | console.log(ArraySummary.ranges([0]))//["0"] -------------------------------------------------------------------------------- /Arrays/Extras/fibonacci-sequence-at-n.js: -------------------------------------------------------------------------------- 1 | /** 2 | * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 3 | 4 | F(0) = 0, F(1) = 1 5 | F(n) = F(n - 1) + F(n - 2), for n > 1. 6 | Given n, calculate F(n). 7 | */ 8 | 9 | class GetFibonacci { 10 | 11 | //Time Complexity -> O(n) , Space Complexity -> O(n) 12 | static withLinearApproach(n){ 13 | let fibSeq = [0,1]; 14 | for(let i=2;i<=n;i++){ 15 | fibSeq.push(fibSeq[i-1]+fibSeq[i-2]); 16 | } 17 | return fibSeq[n]; 18 | } 19 | 20 | //Time Complexity -> O(n) , Space Complexity -> O(1) 21 | static withIterativeTopDownApproach(n){ 22 | if(n<=1) return n; 23 | if(n===2) return 1; 24 | let fib1=1,fib2=1, fibCurr = 0,i=3; 25 | while(i<=n){ 26 | fibCurr = fib1+fib2; 27 | fib1 = fib2; 28 | fib2=fibCurr; 29 | i++; 30 | } 31 | return fibCurr; 32 | } 33 | 34 | //Time Complexity -> O(1) , Space Complexity -> O(1) 35 | static withGoldenRatio(n){ 36 | let goldenRatio = (1 + Math.sqrt(5)) / 2; 37 | return parseInt(Math.round(Math.pow(goldenRatio, n)/ Math.sqrt(5))); 38 | } 39 | } 40 | 41 | console.log(GetFibonacci.withIterativeTopDownApproach(4)); 42 | console.log(GetFibonacci.withGoldenRatio(5)); -------------------------------------------------------------------------------- /contest/weekly/contest-239/split-string-into-ddescending-consecutive-values.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given a string s that consists of only digits. 3 | 4 | Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. 5 | 6 | For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid. 7 | Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order. 8 | Return true if it is possible to split s​​​​​​ as described above, or false otherwise. 9 | 10 | A substring is a contiguous sequence of characters in a string. 11 | */ 12 | 13 | 14 | /** 15 | * @param {string} s 16 | * @return {boolean} 17 | */ 18 | var splitString = function(s) { 19 | let split=[]; 20 | while(split.length===0){ 21 | let i=0,j=1,prev; 22 | while((i+j)<=s.length){ 23 | let curr = parseInt(s.substr(i,j)); 24 | split.push(curr); 25 | prev = curr; 26 | } 27 | for(let k=0;k= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on. 7 | 8 | Return the longest possible length of a word chain with words chosen from the given list of words. 9 | 10 | 11 | */ 12 | 13 | 14 | /** 15 | * @param {string[]} words 16 | * @return {number} 17 | */ 18 | var longestStrChain = function(words) { 19 | let W = Array.from({length: 17}, _ => new Set()) 20 | for (let i = 0; i < words.length; i++) 21 | W[words[i].length].add(words[i]) 22 | let dp = new Map(), best = 1 23 | for (let i = 16; i; i--) { 24 | if (!W[i-1].size) continue 25 | for (let word of W[i]) { 26 | let wVal = dp.get(word) || 1 27 | for (let j = 0; j < word.length; j++) { 28 | let pred = word.slice(0,j) + word.slice(j+1) 29 | if (W[i-1].has(pred) && wVal >= (dp.get(pred) || 1)) { 30 | dp.set(pred, wVal + 1) 31 | best = Math.max(best, wVal + 1) 32 | } 33 | } 34 | } 35 | } 36 | return best 37 | }; -------------------------------------------------------------------------------- /sorting-searching/sort-array-by-parity-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers nums, half of the integers in nums are odd, and the other half are even. 3 | 4 | Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. 5 | 6 | Return any answer array that satisfies this condition. 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {number[]} 12 | */ 13 | 14 | //*accepted -> O(N), O(N) 15 | var sortArrayByParityII = function(nums) { 16 | let k=0,j=1; 17 | let copy = new Array(j+1).fill(0); 18 | for(let i=0;i O(N), less space than 99% -> O(1) 32 | var sortArrayByParityII = function(nums) { 33 | let k=0,j=1; 34 | while(k=0 && arr[end]>0){ 21 | end--; 22 | } 23 | else if(arr[start]>=0 && arr[end]<0){ 24 | let temp = arr[start]; 25 | arr[start] = arr[end]; 26 | arr[end] = temp; 27 | start++; 28 | end--; 29 | } 30 | else if(arr[start]<0 && arr[end]<0){ 31 | start++; 32 | } 33 | else{ 34 | start++; 35 | end--; 36 | } 37 | 38 | } 39 | return arr; 40 | } 41 | } 42 | console.log(moveNegative([-12, 11, -13, -5, 6, -7, 5, -3, -6]));//[-12, -13, -5, -7, -3,-6, 11, 6, 5] 43 | console.log(Negative.moveToBeginning([-12, 11, -13, -5, 6, -7, 5, -3,11, -6]));//[-12, -6, -13, -5, -3,-7, 5, 6, 11, 11] 44 | console.log(Negative.moveToBeginning([]));//[] 45 | console.log(Negative.moveToBeginning([0,-1,0,-10]));//[ -10, -1, 0, 0 ] -------------------------------------------------------------------------------- /linked-list/intersection-of-two-linked-lists.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. 3 | 4 | For example, the following two linked lists begin to intersect at node c1: 5 | 6 | 7 | It is guaranteed that there are no cycles anywhere in the entire linked structure. 8 | 9 | Note that the linked lists must retain their original structure after the function returns. 10 | 11 | */ 12 | 13 | //*approach -> when a pointer reaches the end of listA, we change it to headB and similarly we do this to b pointer. This is conitnued until the value of a pointer and b pointer becomes same and then return the value of a pointer. 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * function ListNode(val) { 18 | * this.val = val; 19 | * this.next = null; 20 | * } 21 | */ 22 | 23 | /** 24 | * @param {ListNode} headA 25 | * @param {ListNode} headB 26 | * @return {ListNode} 27 | */ 28 | var getIntersectionNode = function(headA, headB) { 29 | if(headA===null || headB===null) return null; 30 | let a=headA; 31 | let b = headB; 32 | while(a!==b){ 33 | if(a===null){ 34 | a = headB; 35 | } 36 | else { 37 | a = a.next; 38 | } 39 | if(b===null){ 40 | b = headA; 41 | } 42 | else { 43 | b = b.next; 44 | } 45 | } 46 | return a; 47 | }; -------------------------------------------------------------------------------- /string/extras/count-the-number-of-consistent-strings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. 3 | 4 | Return the number of consistent strings in the array words. 5 | */ 6 | 7 | class Solution { 8 | //O(n^2) time, O(1) space 9 | static bruteForce(allowed,words){ 10 | allowed = "["+allowed+"]"; 11 | let reg = new RegExp(allowed,"g"); 12 | let count=0; 13 | for(let i=0;i [[1,4],[2,8],[3,6]] 11 | Output: 2 12 | Explanation: Interval [3,6] is covered by [2,8], therefore it is removed. 13 | */ 14 | 15 | /** 16 | * @param {number[][]} intervals 17 | * @return {number} 18 | */ 19 | 20 | //!Faster than 62% -> O(N) solution 21 | var removeCoveredIntervals = function(intervals) { 22 | intervals.sort((a,b)=> { 23 | if(a[0]===b[0]){ 24 | return b[1]-a[1] 25 | } 26 | else return a[0]-b[0]; 27 | }); 28 | console.log("intervals->",intervals) 29 | let i=0,j=1; 30 | while(i new Array(N).fill('.')) 19 | 20 | const place = (i, vert, ldiag, rdiag) => { 21 | if (i === N) { 22 | let res = new Array(N) 23 | for (let row = 0; row < N; row++) 24 | res[row] = board[row].join("") 25 | ans.push(res) 26 | return 27 | } 28 | for (let j = 0; j < N; j++) { 29 | let vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j) 30 | if (vert & vmask || ldiag & lmask || rdiag & rmask) continue 31 | board[i][j] = 'Q' 32 | place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask) 33 | board[i][j] = '.' 34 | } 35 | } 36 | 37 | place(0,0,0,0) 38 | return ans; 39 | }; 40 | 41 | console.log("For n=5, N-Queens solution : "); 42 | console.table(solveNQueens(5)); 43 | console.log("\n\n"); 44 | console.log("For n=4, N-Queens solution : "); 45 | console.table(solveNQueens(4)); 46 | console.log("\n\n"); 47 | -------------------------------------------------------------------------------- /maychallenge/range-sum-query-2d.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a 2D matrix matrix, handle multiple queries of the following type: 3 | 4 | Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). 5 | Implement the NumMatrix class: 6 | 7 | NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix. 8 | int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). 9 | */ 10 | 11 | /** 12 | * @param {number[][]} matrix 13 | */ 14 | var NumMatrix = function(matrix) { 15 | let ylen = matrix.length + 1, xlen = matrix[0].length + 1 16 | this.dp = Array.from({length: ylen}, () => new Array(xlen).fill(0)) 17 | for (let i = 1; i < ylen; i++) 18 | for (let j = 1; j < xlen; j++) 19 | this.dp[i][j] = matrix[i-1][j-1] + this.dp[i-1][j] + this.dp[i][j-1] - this.dp[i-1][j-1] 20 | }; 21 | 22 | /** 23 | * @param {number} row1 24 | * @param {number} col1 25 | * @param {number} row2 26 | * @param {number} col2 27 | * @return {number} 28 | */ 29 | NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) { 30 | return this.dp[row2+1][col2+1] - this.dp[row2+1][col1] - this.dp[row1][col2+1] + this.dp[row1][col1] 31 | }; 32 | 33 | /** 34 | * Your NumMatrix object will be instantiated and called as such: 35 | * var obj = new NumMatrix(matrix) 36 | * var param_1 = obj.sumRegion(row1,col1,row2,col2) 37 | */ -------------------------------------------------------------------------------- /matrices/search-element-in-matrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @param {number} target 4 | * @return {boolean} 5 | */ 6 | 7 | class Search{ 8 | static binarySearch(arr,lo,hi,tar){ 9 | console.log("Array :",arr); 10 | console.log("target :",tar); 11 | while(lo<=hi){ 12 | let mid = parseInt((lo+hi)/2); 13 | console.log("Lo :",lo," Hi :",hi," mid :",mid); 14 | if(tar===arr[mid]){ 15 | return mid; 16 | } 17 | else if(tartarget || matrix[m][n]=target){ 32 | return Search.binarySearch(matrix[i],0,n,target)===-1?false : true; 33 | } 34 | } 35 | return false; 36 | } 37 | } 38 | 39 | //console.log(Search.inMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]],11)); 40 | //console.log(Search.inMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]],80)); 41 | //console.log(Search.inMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]],21)); 42 | console.log(Search.inMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]],1)); 43 | //console.log(Search.binarySearch([2,5,6,9,12],0,4,2)); 44 | //console.log(Search.binarySearch([2,5,6,9,12],0,4,13)); -------------------------------------------------------------------------------- /sorting-searching/largest-perimeter-triangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. 3 | 4 | *?Example : 5 | **Input: nums = [3,2,3,4] -> [2,3,3,4] 6 | *?Output: 10 7 | */ 8 | 9 | 10 | 11 | function isPossible(a,b,c){ 12 | if(a+b > c && b+c>a && a+c>b) return true; 13 | else false; 14 | } 15 | 16 | /** 17 | * @param {number[]} nums 18 | * @return {number} 19 | */ 20 | 21 | //!very slow solution 22 | // var largestPerimeter = function(nums) { 23 | // nums.sort((a,b)=> a-b); 24 | // console.log(nums) 25 | // let i=nums.length-1; 26 | 27 | // while(i>=0){ 28 | // let j=i-1; 29 | // while(j>=0){ 30 | // let k=j-1; 31 | // while(k>=0){ 32 | // if(isPossible(nums[i],nums[j],nums[k])) { 33 | // return nums[i]+nums[j]+nums[k]; 34 | // } 35 | // else k--; 36 | // } 37 | // j--; 38 | // } 39 | // i-- 40 | // } 41 | 42 | // return 0; 43 | // }; 44 | 45 | 46 | //* faster solution -> O(N) time 47 | var largestPerimeter = function(nums){ 48 | nums.sort((a,b)=> a-b); 49 | for (let i = nums.length - 3; i >= 0; --i) 50 | if (nums[i] + nums[i+1] > nums[i+2]) 51 | return nums[i] + nums[i+1] + nums[i+2]; 52 | return 0; 53 | } 54 | 55 | 56 | console.log(largestPerimeter([3,2,3,4])) 57 | console.log(largestPerimeter([3,6,2,3])) -------------------------------------------------------------------------------- /linked-list/insertion-sort-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. 3 | 4 | The steps of the insertion sort algorithm: 5 | Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 6 | At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 7 | It repeats until no input elements remain. 8 | The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * function ListNode(val, next) { 14 | * this.val = (val===undefined ? 0 : val) 15 | * this.next = (next===undefined ? null : next) 16 | * } 17 | */ 18 | /** 19 | * @param {ListNode} head 20 | * @return {ListNode} 21 | */ 22 | 23 | //* O(N^2) solution -> faster than 56% 24 | var insertionSortList = function(head) { 25 | let dHead = new ListNode(0); 26 | let curr = dHead,prev = dHead; 27 | while(head!=null){ 28 | curr = dHead; 29 | while(curr.next!==null && curr.next.val<=head.val){ 30 | curr = curr.next; 31 | } 32 | let newNode = new ListNode(head.val); 33 | newNode.next = curr? curr.next : null; 34 | curr.next = newNode; 35 | head = head.next; 36 | } 37 | return dHead.next; 38 | }; -------------------------------------------------------------------------------- /sorting-searching/least-number-of-unique-integers-after-k-removals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements. 3 | 4 | Example 1: 5 | Input: arr = [5,5,4], k = 1 6 | Output: 1 7 | Explanation: Remove the single 4, only 5 is left. 8 | */ 9 | 10 | /** 11 | * @param {number[]} arr 12 | * @param {number} k 13 | * @return {number} 14 | */ 15 | 16 | //ascending order of frequencies 17 | var frequencySort = function(nums) { 18 | let freq = {}; 19 | for(let i=0;i { 25 | if(a[1]===b[1]){ 26 | return b[0]-a[0] 27 | } 28 | else return a[1]-b[1]; 29 | }) 30 | let res = []; 31 | for(let i=0;i faster 17% 38 | var findLeastNumOfUniqueInts = function(arr, k) { 39 | arr = frequencySort(arr); 40 | let freq = {}; 41 | for(let i=0;ia[0]-b[0]); 7 | let prevLow=logs[0][0],prevHigh=logs[0][1],currLow=0,currHigh=0,currMax=1,max=1,maxYear=logs[0][0]; 8 | let i=1; 9 | while(i",prevHigh) 14 | console.log(logs[i]) 15 | currMax++; 16 | if(currMax>max){ 17 | max=currMax; 18 | maxYear = currLow; 19 | } 20 | 21 | if(logs[i][0]>prevHigh) break; 22 | i++; 23 | currLow = logs[i][0]; 24 | currHigh = logs[i][1]; 25 | } 26 | currMax=1; 27 | prevHigh = logs[i][1]; 28 | prevLow = logs[i][0]; 29 | i++; 30 | } 31 | return maxYear; 32 | }; 33 | 34 | 35 | //?Input: logs = [[1950,1961],[1960,1971],[1970,1981]] 36 | //*Output: 1960 cL,cH 37 | 38 | console.log(maximumPopulation([[1950,1961],[1960,1971],[1970,1981]])) 39 | console.log(maximumPopulation([[1993,1999],[2000,2010]])) 40 | console.log(maximumPopulation([[1982,1998],[2013,2042],[2010,2035],[2022,2050],[2047,2048]])) 41 | console.log(maximumPopulation([[2033,2034],[2039,2047],[1998,2042],[2047,2048],[2025,2029],[2005,2044],[1990,1992],[1952,1956],[1984,2014]])) 42 | console.log(maximumPopulation([[2025,2041],[1988,2007],[2003,2046],[2045,2049],[2025,2027],[2014,2040],[2014,2027],[2011,2027],[1972,2019]])) -------------------------------------------------------------------------------- /contest/biweekly/constest-51/max-element-after-decreasing-and-rearranging.js: -------------------------------------------------------------------------------- 1 | /** 2 | * ou are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: 3 | 4 | The value of the first element in arr must be 1. 5 | The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x. 6 | There are 2 types of operations that you can perform any number of times: 7 | 8 | Decrease the value of any element of arr to a smaller positive integer. 9 | Rearrange the elements of arr to be in any order. 10 | Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions. 11 | */ 12 | 13 | 14 | /** 15 | * @param {number[]} arr 16 | * @return {number} 17 | */ 18 | 19 | 20 | var maximumElementAfterDecrementingAndRearranging = function(arr) { 21 | arr.sort((a,b)=> a-b); 22 | if(arr[0]!==1) arr[0] = 1; 23 | let prev = arr[0],curr; 24 | for(let i=1;ilongest.length) longest = prev; 38 | } 39 | else prev = reps[i][j] 40 | } 41 | } 42 | console.log("Longest -> ",longest?longest : "none repeating") 43 | } 44 | } 45 | 46 | //Longest.subsequenceInString("axxxy") 47 | //Longest.subsequenceInString("aab") 48 | //Longest.subsequenceInString("ab")//should give 1 49 | Longest.subsequenceInString("aabebcdd")//should give 1 as a/y is repeating over the string -------------------------------------------------------------------------------- /maychallenge/maximum-product-of-word-length.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0. 3 | */ 4 | 5 | /** 6 | * @param {string[]} words 7 | * @return {number} 8 | */ 9 | var maxProduct = function(words) { 10 | words.sort((a,b) => b.length - a.length) 11 | let best = 0, bitsets = new Uint32Array(words.length) 12 | for (let i = 0; i < words.length; i++) { 13 | let word = words[i], wlen = word.length, bitset = 0 14 | if (wlen * words[0].length < best) 15 | return best 16 | for (let j = 0; j < wlen; j++) 17 | bitset |= 1 << (word.charCodeAt(j) - 97) 18 | for (let j = 0; j < i; j++) 19 | if ((bitsets[j] & bitset) === 0) 20 | best = Math.max(best, wlen * words[j].length) 21 | bitsets[i] = bitset 22 | } 23 | return best 24 | }; 25 | 26 | //* faster than 45% 27 | 28 | const getAllData = (list) => { // linkedlist -> array 29 | let res = []; 30 | let current = list; 31 | while (current) { 32 | res.push(current.val); 33 | current = current.next; 34 | } 35 | return res; 36 | }; 37 | var nextLargerNodes = function(head) { 38 | let a = getAllData(head); 39 | let n = a.length; 40 | let res = []; 41 | for (let i = 0; i < n; i++) { 42 | let tmp = 0; 43 | for (let j = i + 1; j < n; j++) { 44 | if (a[j] > a[i]) { 45 | tmp = a[j]; 46 | break; 47 | } 48 | } 49 | res.push(tmp); 50 | } 51 | return res; 52 | }; -------------------------------------------------------------------------------- /Arrays/rearrange-array-in-alternating-positive-and-negative-items.js: -------------------------------------------------------------------------------- 1 | class Rearrange { 2 | 3 | static alternating(arr){ 4 | let i=0,len= arr.length; 5 | while(i=0){ 7 | let next; 8 | for(let j=i+1;j0) { 20 | next = j; 21 | break; 22 | } 23 | } 24 | arr = Rearrange.rotateRight(arr,i,next); 25 | } 26 | i++; 27 | } 28 | return arr; 29 | } 30 | static rotateRight(arr,low,high){ 31 | arr = Rearrange.reverse(arr,low,high); 32 | arr = Rearrange.reverse(arr,low+1,high); 33 | return arr; 34 | } 35 | static reverse(arr,start,end){ 36 | while(start72 ms, faster than 99.10%,space -> 39.5 MB, less than 92.33% 23 | static destCity(paths){ 24 | for(let i=0;ik) bad++; 23 | if(end===start+cnt-1){ 24 | console.log("for window ",start," : ",end); 25 | console.log("Bad : ",bad); 26 | console.log("Min swaps till now : ",minCnt); 27 | start =start+1; 28 | //console.log("bad Value :",bad); 29 | minCnt = Math.min(minCnt,bad); 30 | if(arr[start-1]>k) bad--; 31 | } 32 | end++; 33 | } 34 | return minCnt==Number.MAX_VALUE? 0 : minCnt; 35 | } 36 | } 37 | 38 | console.log("Min Swaps : ",MinimumNumber.ofSwaps([2, 1, 5, 6, 3],3)); 39 | console.log("Min Swaps : ",MinimumNumber.ofSwaps([2, 1, 5, 6, 3],5)); 40 | console.log("Min Swaps : ",MinimumNumber.ofSwaps([2, 7, 9, 5, 8, 7, 4],6)); 41 | console.log("Min Swaps : ",MinimumNumber.ofSwaps([2, 7, 9, 5, 8, 7, 4],9)); -------------------------------------------------------------------------------- /sorting-searching/sort-integers-by-power-value.js: -------------------------------------------------------------------------------- 1 | /** 2 | * The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: 3 | 4 | if x is even then x = x / 2 5 | if x is odd then x = 3 * x + 1 6 | For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). 7 | 8 | Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. 9 | 10 | Return the k-th integer in the range [lo, hi] sorted by the power value. 11 | 12 | Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer. 13 | */ 14 | 15 | /** 16 | * @param {number} lo 17 | * @param {number} hi 18 | * @param {number} k 19 | * @return {number} 20 | */ 21 | var getKth = function(lo, hi, k) { 22 | let vals = [] 23 | for(let i=lo;i<=hi;i++){ 24 | let pow = getPower(i); 25 | vals.push([i,pow]); 26 | } 27 | vals.sort((a,b)=> { 28 | if(a[1]===b[1]) return a[0]-b[0]; 29 | else return a[1]-b[1]; 30 | }) 31 | return vals[k-1][0]; 32 | }; 33 | 34 | function getPower(num){ 35 | let count =0; 36 | while(num!==1){ 37 | if(num%2===0) num = num/2; 38 | else num = num*3 + 1; 39 | count++; 40 | } 41 | return count; 42 | } 43 | 44 | console.log(getKth(12, 15, 2)) 45 | console.log(getKth( 1, 1,1)) 46 | console.log(getKth( 7, 11, 4)) 47 | console.log(getKth(10, 20, 5)) 48 | console.log(getKth(1, 1000, 777)) -------------------------------------------------------------------------------- /contest/longest-substring-containing-all-vowels-in-order.js: -------------------------------------------------------------------------------- 1 | //!fails test cases 2 | var longestBeautifulSubstring = function(word) { 3 | let max = 0,curr = 0; 4 | let i=0; 5 | let vowels = ["a","e","i","o","u"],vPoint =0; 6 | console.log("Word Length -> ",word.length) 7 | while(i=5?curr-1 : 0; 19 | max = Math.max(max,curr); 20 | vPoint = 0; 21 | curr = 0; 22 | } 23 | if(vowels[vPoint+1]===word[i]){ 24 | vPoint++; 25 | } 26 | console.log("i ->",word[i]); 27 | console.log("curr length -> ",word[curr]); 28 | 29 | } 30 | return max; 31 | } 32 | 33 | 34 | console.log(longestBeautifulSubstring("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooouuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuee")); -------------------------------------------------------------------------------- /maychallenge/valid-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A valid number can be split up into these components (in order): 3 | 4 | A decimal number or an integer. 5 | (Optional) An 'e' or 'E', followed by an integer. 6 | A decimal number can be split up into these components (in order): 7 | 8 | (Optional) A sign character (either '+' or '-'). 9 | One of the following formats: 10 | At least one digit, followed by a dot '.'. 11 | At least one digit, followed by a dot '.', followed by at least one digit. 12 | A dot '.', followed by at least one digit. 13 | An integer can be split up into these components (in order): 14 | 15 | (Optional) A sign character (either '+' or '-'). 16 | At least one digit. 17 | For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. 18 | 19 | Given a string s, return true if s is a valid number. 20 | */ 21 | 22 | /** 23 | * @param {string} s 24 | * @return {boolean} 25 | */ 26 | var isNumber = function(S) { 27 | let exp = false, sign = false, num = false, dec = false 28 | for (let c of S) 29 | if (c >= '0' && c <= '9') num = true 30 | else if (c === 'e' || c === 'E') 31 | if (exp || !num) return false 32 | else exp = true, sign = false, num = false, dec = false 33 | else if (c === '+' || c === '-') 34 | if (sign || num || dec) return false 35 | else sign = true 36 | else if (c === '.') 37 | if (dec || exp) return false 38 | else dec = true 39 | else return false 40 | return num 41 | }; -------------------------------------------------------------------------------- /string/extras/search-suggestion-system.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. 3 | 4 | Return list of lists of the suggested products after each character of searchWord is typed. 5 | */ 6 | 7 | 8 | class Solution { 9 | 10 | //!O(n^2) solution accepted 11 | // static suggestedProducts(products, searchWord) { 12 | // let suggestions = []; 13 | // products.sort(); 14 | // for(let i=0;i product[i] === searchWord[i]); 34 | result.push(sortedProducts.slice(0, 3)); 35 | } 36 | 37 | return result; 38 | } 39 | } 40 | 41 | console.log(Solution.suggestedProducts(["mobile","mouse","moneypot","monitor","mousepad"],"mouse")) -------------------------------------------------------------------------------- /Arrays/Extras/first-and-last-position-of-target-in-sorted-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. 3 | 4 | *!If target is not found in the array, return [-1, -1]. 5 | 6 | *?Follow up: Could you write an algorithm with O(log n) runtime complexity? 7 | */ 8 | 9 | const Search = require("./binary-search.js"); 10 | 11 | 12 | class FindIndex{ 13 | //!does not pass all the cases 14 | // static searchRange(nums,target){ 15 | // let found = Search.binarySearch(nums,0,nums.length-1,target); 16 | // if(found===-1) return [-1,-1]; 17 | // if(found===0){ 18 | // if(nums[found+1]===target) return [found,found+1]; 19 | // else return [-1,found] 20 | // } 21 | // if(found===nums.length-1){ 22 | // if(nums[found-1]===target) return [found-1,found] 23 | // else return [found,-1] 24 | // } 25 | // if(nums[found+1]===target) return [found,found+1]; 26 | // if(nums[found-1]===target) return [found-1,found] 27 | // } 28 | 29 | //* O(N) solution -> faster than 94.5% 30 | static searchRange(nums,target){ 31 | let i=0,j=nums.length-1; 32 | 33 | while(i<=j){ 34 | if(nums[i]===target && nums[j]===target) return [i,j]; 35 | if(nums[i]target)j--; 37 | } 38 | return [-1,-1] 39 | } 40 | } 41 | 42 | console.log(FindIndex.searchRange([5,7,7,8,8],8)) 43 | console.log(FindIndex.searchRange([5,7,7,8,8,10],7)) 44 | console.log(FindIndex.searchRange([5,6,7,7,8,8,10],5)) 45 | console.log(FindIndex.searchRange([5,6,7,7,8,8,10],10)) 46 | console.log(FindIndex.searchRange([3,3,3],3)) -------------------------------------------------------------------------------- /Arrays/Extras/number-of-teams.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *There are n soldiers standing in a line. Each soldier is assigned a unique rating value. 3 | **You have to form a team of 3 soldiers amongst them under the following rules: 4 | 5 | *?Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). 6 | *!A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n). 7 | *?Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). 8 | */ 9 | 10 | class CountNumber{ 11 | static bruteForce(rating){ 12 | let len = rating.length; 13 | if(len<3) return 0; 14 | let teams = 0; 15 | for(let i =0;i rating[j] && rating[j]> rating[k]) teams++; 20 | } 21 | } 22 | } 23 | return teams; 24 | } 25 | static optimalApproach(rating){ 26 | let len = rating.length; 27 | if(len<3) return 0; 28 | let teams = 0; 29 | for(let i =1;ii){ 38 | if(rating[j] A[j]. 6 | 7 | The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1]. 8 | 9 | Return true if and only if the number of global inversions is equal to the number of local inversions. 10 | */ 11 | 12 | //simple approach 13 | var isIdealPermutation = function(A) { 14 | let i=0; 15 | let N = A.length; 16 | let locInv=0,globInv=0; 17 | while(i< N-1){ 18 | for(let j=i+1;jA[j]){ 20 | globInv++; 21 | if(j===i+1) locInv++; 22 | } 23 | } 24 | i++; 25 | } 26 | if(locInv===globInv) return true; 27 | else return false; 28 | }; 29 | 30 | //time limit exceeds for the above solution, So we need to make it more efficient 31 | //So we can directly return false as soon as we find a global inversion that is not a local inversion 32 | 33 | class Permutation { 34 | static isIdeal(A){ 35 | let i=0; 36 | let N = A.length; 37 | while(i< N-1){ 38 | for(let j=i+1;jA[j]) return false; 40 | } 41 | i++; 42 | } 43 | return true; 44 | } 45 | //even faster solution 46 | static isIdealPermutation(A){ 47 | let max = -1; 48 | for(let i=0;iA[i]?max:A[i]; 50 | if(max>A[i+2]) return false; 51 | } 52 | return true; 53 | } 54 | } 55 | 56 | 57 | 58 | console.log(isIdealPermutation([1,2,0])) -------------------------------------------------------------------------------- /Arrays/common-elements-in-three-sorted-arrays.js: -------------------------------------------------------------------------------- 1 | //Given three arrays sorted in non-decreasing order, print all common elements in these arrays. 2 | // Input: 3 | // ar1[] = {1, 5, 10, 20, 40, 80} 4 | // ar2[] = {6, 7, 20, 80, 100} 5 | // ar3[] = {3, 4, 15, 20, 30, 70, 80, 120} 6 | // Output: 20, 80 7 | 8 | // Input: 9 | // ar1[] = {1, 5, 5} 10 | // ar2[] = {3, 4, 5, 5, 10} 11 | // ar3[] = {5, 5, 10, 20} 12 | // Output: 5, 5 13 | 14 | 15 | class FindCommon { 16 | static forThreeSortedArrays(arr1,arr2,arr3){ 17 | let len1 = arr1.length; 18 | let len2 = arr2.length; 19 | let len3 = arr3.length; 20 | let commons =[]; 21 | let i = 0, j = 0, k = 0; 22 | 23 | // Iterate through three arrays while all arrays have elements 24 | while (i < len1 && j < len2 && k < len3) 25 | { 26 | // If x = y and y = z, print any of them and move ahead 27 | // in all arrays 28 | if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) 29 | { 30 | commons.push(arr1[i]); 31 | i++; j++; k++; 32 | } 33 | 34 | // x < y 35 | else if (arr1[i] < arr2[j]) 36 | i++; 37 | 38 | // y < z 39 | else if (arr2[j] < arr3[k]) 40 | j++; 41 | 42 | // We reach here when x > y and z < y, i.e., z is smallest 43 | else 44 | k++; 45 | } 46 | return commons; 47 | } 48 | } 49 | 50 | console.log(FindCommon.forThreeSortedArrays([1, 5, 10, 20, 40, 80],[6, 7, 20, 80, 100],[3, 4, 15, 20, 30, 70, 80, 120])); 51 | console.log(FindCommon.forThreeSortedArrays([1, 5, 10,20,20, 40, 80],[6, 7, 20, 80, 100],[3, 4, 15, 20,20, 30, 70, 80, 120])); -------------------------------------------------------------------------------- /contest/minimum-ops-to-reinitialize-perm.js: -------------------------------------------------------------------------------- 1 | /** 2 | * !1806. Minimum Number of Operations to Reinitialize a Permutation 3 | **You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. 4 | ** 5 | **In one operation, you will create a new array arr, and for each i: 6 | ** 7 | *?If i % 2 == 0, then arr[i] = perm[i / 2]. 8 | *?If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2]. 9 | *?You will then assign arr​​​​ to perm. 10 | ** 11 | **Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value. 12 | */ 13 | 14 | /** 15 | * @param {number} n 16 | * @return {number} 17 | */ 18 | function reinitializePermutation(n) { 19 | let arr=[],perm=[],count=0; 20 | for(let i=0;i",arr); 27 | console.log("Perm ->",perm); 28 | for(let i=0;i",arr); 33 | console.log("Perm ->",perm); 34 | count++; 35 | console.log("Ops :",count); 36 | for(let i=0;i= l; --i) { 39 | list.push(matrix[r - 1][i]); 40 | } 41 | r--; 42 | } 43 | 44 | // print the first column from the remaining columns 45 | if (l < c) { 46 | for (i = r - 1; i >= k; --i) { 47 | list.push(matrix[i][l]); 48 | } 49 | l++; 50 | } 51 | } 52 | return list; 53 | } 54 | } 55 | 56 | //console.log("\n\nSpiral Traversal :\n",Matrix.spirallyTraverse( [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],4,4)); 57 | console.log("\n\nSpiral Traversal :\n",Matrix.spirallyTraverse( [[1,2,3,4],[5,6,7,8],[9,10,11,12]],3,4)); -------------------------------------------------------------------------------- /matrices/common-elements-of-all-rows.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix. 3 | *!Example: 4 | *!Input: 5 | *!mat[4][5] = {{1, 2, 1, 4, 8}, 6 | *! {3, 7, 8, 5, 1}, 7 | *! {8, 7, 7, 3, 1}, 8 | *! {8, 1, 2, 7, 9}, 9 | *! }; 10 | 11 | *?Output: 12 | *?1 8 or 8 1 13 | *?8 and 1 are present in all rows. 14 | */ 15 | 16 | const Sort = require("../Arrays/Extras/sorting-algorithms"); 17 | const Search = require("../Arrays/Extras/binary-search"); 18 | class Matrix{ 19 | static commonElements(mat){ 20 | for(let i=0;i",mat[0][j]); 28 | console.log("Commons till now ->",commons); 29 | let found=true; 30 | for(let i=1;i",mat[0][j]); 32 | console.log("In Array ->",mat[i]); 33 | let loc = Search.binarySearch(mat[i],0,mat[0].length-1,mat[0][j]); 34 | if(loc===-1) { 35 | found=false; 36 | break; 37 | } 38 | } 39 | if(found && commons[commons.length-1]!==mat[0][j]) commons.push(mat[0][j]); 40 | j++; 41 | } 42 | console.log(commons); 43 | } 44 | } 45 | 46 | Matrix.commonElements([[1, 2, 1, 4, 8],[3, 7, 8, 5, 1],[8, 7, 7, 3, 1],[8, 1, 2, 7, 9]]); 47 | Matrix.commonElements([[1, 2, 1, 4, 8],[3, 2, 8, 5, 1],[8, 2, 7, 3, 1],[8, 1, 2, 7, 9]]); 48 | -------------------------------------------------------------------------------- /string/extras/custom-sort-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * S and T are strings composed of lowercase letters. In S, no letter occurs more than once. 3 | console.log(Solution.customSortString("abc","badc"),"\n"); 4 | console.log(Solution.customSortString("eav","venaesvatra"),"\n"); 5 | console.log(Solution.customSortString("zd","vwkaps"),"\n"); 6 | S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string. 7 | 8 | Return any permutation of T (as a string) that satisfies this property. 9 | */ 10 | 11 | 12 | class Solution { 13 | 14 | //!O(n^3) solution very slow 15 | // static customSortString(s,t){ 16 | // let sorted = ""; 17 | // for(let i=0;i",s[i]," in ->",t); 20 | // while(k",k); 23 | // console.log(s[i]," <-> ",t[k]); 24 | // sorted += t[k]; 25 | // t = t.substring(0,k)+t.substring(k+1,t.length); 26 | // k=0; 27 | // console.log("Sorted ->",sorted); 28 | // console.log("t ->",t); 29 | // } 30 | // else k++; 31 | // } 32 | // } 33 | // sorted += t; 34 | // return sorted; 35 | // } 36 | 37 | //?Faster solution -> O(N^2) 38 | static customSortString(S,T){ 39 | return T.split('') 40 | .sort((a, b) => S.indexOf(a) - S.indexOf(b)) 41 | .join(''); 42 | } 43 | } 44 | 45 | 46 | console.log(Solution.customSortString("jftiugkz", "kfiukutzjg"),"\n"); -------------------------------------------------------------------------------- /linked-list/next-greater-node-in-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * We are given a linked list with head as the first node. Let's number the nodes in the list: node_1, node_2, node_3, ... etc. 3 | 4 | Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0. 5 | 6 | Return an array of integers answer, where answer[i] = next_larger(node_{i+1}). 7 | 8 | Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * function ListNode(val, next) { 14 | * this.val = (val===undefined ? 0 : val) 15 | * this.next = (next===undefined ? null : next) 16 | * } 17 | */ 18 | /** 19 | * @param {ListNode} head 20 | * @return {number[]} 21 | */ 22 | 23 | //?faster than 28% and efficient than 76% -> O(N*N) time solution 24 | var nextLargerNodes = function(head) { 25 | let curr = head,next = curr.next; 26 | let ans = []; 27 | while(curr.next!==null){ 28 | 29 | //continue checking until either next pointer reaches end or next val > curr val 30 | while(next && next.val<=curr.val){ 31 | next = next.next; 32 | } 33 | //if there are not values greater than the current value 34 | if(!next) ans.push(0); 35 | 36 | else ans.push(next.val); 37 | 38 | //reseting the values of curr and next for the next set of comparisons 39 | curr = curr.next; 40 | next = curr.next; 41 | } 42 | 43 | //there does not exist any node after the last node so pushing 0 44 | ans.push(0); 45 | return ans; 46 | }; -------------------------------------------------------------------------------- /Arrays/merge-overlapping-intervals.js: -------------------------------------------------------------------------------- 1 | // 2 | 3 | class MergeIntervals { 4 | static mergeSort(arr){ 5 | let len = arr.length; 6 | if(len===1) return arr; 7 | let mid = Math.floor(len/2); 8 | let left = arr.slice(0,mid); 9 | let right = arr.slice(mid,len); 10 | return MergeIntervals.merge(MergeIntervals.mergeSort(left),MergeIntervals.mergeSort(right) ) 11 | } 12 | static merge(left,right) { 13 | let l1 = left.length; 14 | let l2 = right.length; 15 | let i=0,j=0; 16 | let merged = []; 17 | while(i=intervals[i+1][0]){ 36 | let start = MergeIntervals.min(intervals[i][0],intervals[i+1][0]); 37 | let end = MergeIntervals.max(intervals[i][1],intervals[i+1][1]); 38 | let interval = [start,end]; 39 | intervals.splice(i,2,interval) 40 | } 41 | else { 42 | i++; 43 | } 44 | console.log("Intervals :",intervals); 45 | } 46 | return intervals; 47 | } 48 | static min(a,b){ 49 | return ab?a:b; 53 | } 54 | } 55 | 56 | console.log(MergeIntervals.mergeOverlapping([[1,3],[0,1],[0,2],[5,7],[2,6],[8,10],[15,18],[17,20]])); -------------------------------------------------------------------------------- /Arrays/Extras/reveal-cards-in-inreasing-order.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *In a deck of cards, every card has a unique integer. You can order the deck in any order you want. 3 | 4 | **Initially, all the cards start face down (unrevealed) in one deck. 5 | **Now, you do the following steps repeatedly, until all cards are revealed: 6 | *?Take the top card of the deck, reveal it, and take it out of the deck. 7 | *?If there are still cards in the deck, put the next top card of the deck at the bottom of the deck. 8 | *?If there are still unrevealed cards, go back to step 1. Otherwise, stop. 9 | **Return an ordering of the deck that would reveal the cards in increasing order. 10 | **The first entry in the answer is considered to be the top of the deck. 11 | */ 12 | const Sort = require("./sorting-algorithms"); 13 | class RevealCards { 14 | static inIncreasingOrder(deck){ 15 | deck = Sort.mergeSort(deck); 16 | let arranged = []; 17 | for(let i=deck.length-1;i>=1;i--){ 18 | arranged.unshift(deck[i]); 19 | arranged = RevealCards.sendLastToFront(arranged); 20 | } 21 | arranged.unshift(deck[0]); 22 | return arranged; 23 | } 24 | static sendLastToFront(arr){ 25 | arr = RevealCards.reverse(arr,0,arr.length-2); 26 | arr = RevealCards.reverse(arr,0,arr.length-1); 27 | return arr; 28 | } 29 | static reverse(arr,lb,ub) { 30 | while(lb",absDiff); 16 | // if(absDiff===0) return false; 17 | // //console.log("Abs diff ->",absDiff); 18 | // for(let i =0;i O(N) time complexity 26 | static forRotation(str1,str2){ 27 | if(str1.length!==str2.length) return false; 28 | let strCpy = str1+str1; 29 | let l2 = str2.length; 30 | 31 | //*using manual operation 32 | for(let i=0;i0 ? arr[0]-k: arr[0]+k; 34 | arr[arr.length-1] = big; 35 | arr[0] = small; 36 | let maxDiff = big-small; 37 | 38 | 39 | for(let i=1;i<=arr.length-2;i++){ 40 | console.log(maxDiff) 41 | let add = arr[i]+k; 42 | let sub = arr[i]-k>0 ? arr[i]-k : arr[i]+k; 43 | let currDiff=0; 44 | if(subbig){ 51 | arr[i] = big 52 | currDiff = add-small; 53 | big = add; 54 | 55 | } 56 | if(currDiff>0 &&currDiffcoins) break; 22 | else { 23 | coins = coins - costs[i]; 24 | max++; 25 | } 26 | } 27 | return max; 28 | }; 29 | 30 | class Sort { 31 | static mergeSort(arr){ 32 | let len = arr.length; 33 | if(len<=1) return arr; 34 | let mid = Math.floor(len/2); 35 | let left = arr.slice(0,mid); 36 | let right = arr.slice(mid,len); 37 | return Sort.mergeIncrease( 38 | Sort.mergeSort(left,"i"), 39 | Sort.mergeSort(right,"i") 40 | ); 41 | } 42 | static mergeIncrease(leftArr,rightArr){ 43 | const lLen = leftArr.length; 44 | const rLen = rightArr.length; 45 | let i=0,j=0; 46 | let merged = []; 47 | while(i= 1 and m >= 0. If m = 0, it means the directory is just the root directory. 10 | 11 | The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format: 12 | 13 | "directory_path/file_name.txt" 14 | */ 15 | 16 | /** 17 | * @param {string[]} paths 18 | * @return {string[][]} 19 | */ 20 | var findDuplicate = function(paths) { 21 | let contMap = new Map(), ans = [] 22 | for (let pStr of paths) { 23 | let i = 0, j, k 24 | while (pStr.charAt(i) !== ' ') i++ 25 | let path = pStr.slice(0,i) 26 | for (j = ++i; i < pStr.length; i++) 27 | if (pStr.charAt(i) === '(') k = i 28 | else if (pStr.charAt(i) === ')') { 29 | let pathfile = path + '/' + pStr.slice(j, k), 30 | cont = pStr.slice(k+1, i) 31 | if (!contMap.has(cont)) 32 | contMap.set(cont, [pathfile]) 33 | else contMap.get(cont).push(pathfile) 34 | j = i + 2 35 | } 36 | } 37 | for (let v of contMap.values()) 38 | if (v.length > 1) ans.push(v) 39 | return ans 40 | }; -------------------------------------------------------------------------------- /Arrays/Extras/majority-element.js: -------------------------------------------------------------------------------- 1 | //takes longer timer to resolve but still acceptable 2 | function majorityElement(nums) { 3 | nums = Sort.mergeSort(nums); 4 | let i = 0,j=0,count = 0,maj = Math.floor(nums.length/2); 5 | while(i<=nums.length-2&&jmaj) return nums[i]; 12 | i=j; 13 | } 14 | } 15 | //we can reduce the time with a simple hack -> If the elements are sorted in monotonically increasing (or decreasing) order, the majority element can be found at index (n/2) (and (n/2)+1 if n is even) incidentally, if n is even). 16 | var majorityElementHack = function(nums) { 17 | if(nums.length===1) return nums[0]; 18 | nums = Sort.mergeSort(nums); 19 | let n = nums.length-1; 20 | return nums[Math.floor(n/2)] 21 | }; 22 | 23 | 24 | class Sort { 25 | static mergeSort(arr){ 26 | let len = arr.length; 27 | if(len<=1) return arr; 28 | let mid = Math.floor(len/2); 29 | let left = arr.slice(0,mid); 30 | let right = arr.slice(mid,len); 31 | 32 | return Sort.merge( 33 | Sort.mergeSort(left), 34 | Sort.mergeSort(right) 35 | ); 36 | } 37 | static merge(leftArr,rightArr){ 38 | const lLen = leftArr.length; 39 | const rLen = rightArr.length; 40 | let i=0,j=0; 41 | let merged = []; 42 | while(i0){ 13 | // let curr = []; 14 | // let j=1; 15 | // while(j faster than 76% 44 | static groupAnagrams(strs){ 45 | let hash = {}; 46 | for(let i=0;i faster than 50% 9 | // static addBinary(a,b){ 10 | // a=a.length>=1 ? Solution.toInteger(a,2) : 0; 11 | // b=b.length>=1 ? Solution.toInteger(b,2) : 0; 12 | // let sum = a+b; 13 | // if(sum==0) return "0"; 14 | 15 | // let bin = Solution.binarySum(sum)+""; 16 | // return bin.slice(0,bin.length-1); 17 | // } 18 | // static binarySum(num){ 19 | // let bin = 0n; 20 | // while(num>0){ 21 | // let dig = BigInt(num%2n); 22 | // bin = dig + ""+bin; 23 | // num = BigInt(num/2n); 24 | // } 25 | // return bin; 26 | // } 27 | // static toInteger(s){ 28 | // let num = 0n,pow=0; 29 | // for(let i=s.length-1;i>=0;i--){ 30 | // num = num+ BigInt(s[i]*(2**pow)); 31 | // console.log(num); 32 | // pow++; 33 | // } 34 | // return num; 35 | // } 36 | 37 | //*Fastest O(Math.max(a.length,b.length)) ie O(N) time 38 | static addBinary(a,b){ 39 | let sumStr = ""; 40 | let i = a.length - 1; 41 | let j = b.length - 1; 42 | let carry = 0; 43 | while(i>=0 || j>=0){ 44 | let sum = carry; 45 | sum += Number(a[i]) || 0; 46 | sum += Number(b[j]) || 0; 47 | sumStr = (sum%2)+""+sumStr; 48 | carry = parseInt(sum/2); 49 | i--;j--; 50 | } 51 | if(carry!==0) sumStr = carry+""+sumStr; 52 | return sumStr; 53 | } 54 | } 55 | 56 | 57 | console.log(Solution.addBinary("10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101", 58 | "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"))//returns 110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000 -------------------------------------------------------------------------------- /string/extras/valid-palindrome-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. 3 | */ 4 | 5 | class Solution { 6 | 7 | //!recursive method -> Accepted but slow 8 | // static validPalindrome(s){ 9 | // return Solution.isPalindrome(s,0)===1 ? true : false; 10 | // } 11 | 12 | // static isPalindrome(s,removed){ 13 | // let len = s.length; 14 | // if(len<=1) { 15 | // return 1; 16 | // } 17 | // if(s[0]===s[len-1]) { 18 | // return Solution.isPalindrome(s.slice(1,len-1),removed); 19 | // } 20 | // if(removed===1 && s[0]!==s[len-1]) { 21 | // return 0; 22 | // } 23 | // if(removed===0 && s[0]!==s[len-1]) { 24 | // return Math.max(Solution.isPalindrome(s.slice(0,len-1),1),Solution.isPalindrome(s.slice(1,len),1)); 25 | // } 26 | // } 27 | 28 | //?faster than 50% -> O(N) 29 | static validPalindrome(s){ 30 | let i=0,j=s.length-1; 31 | if(j<=0) return true; 32 | while(i 0) { 18 | arr[i++] = 0; 19 | c0--; 20 | } 21 | 22 | // Counting the 1s and storing 23 | while (c1 > 0) { 24 | arr[i++] = 1; 25 | c1--; 26 | } 27 | 28 | // Counting the 2s and storing 29 | while (c2 > 0) { 30 | arr[i++] = 2; 31 | c2--; 32 | } 33 | return arr; 34 | } 35 | 36 | //Dutch National Flag Algorithm or 3 way partitioning 37 | class DNF { 38 | static sort(arr){ 39 | let len = arr.length; 40 | if(len<=1) return arr; 41 | let low = 0; 42 | let mid = 0; 43 | let high = len-1; 44 | while(mid<=high){ 45 | let curr= arr[mid]; 46 | switch(curr) { 47 | case 0 : 48 | arr[low] = arr[low] + arr[mid]; 49 | arr[mid] = arr[low]-arr[mid]; 50 | arr[low] = arr[low]-arr[mid]; 51 | low++; 52 | mid++; 53 | break; 54 | case 1 : 55 | mid++; 56 | break; 57 | case 2 : 58 | arr[high] = arr[high] + arr[mid]; 59 | arr[mid] = arr[high]-arr[mid]; 60 | arr[high] = arr[high]-arr[mid]; 61 | high --; 62 | break; 63 | default : 64 | arr[mid] = arr[mid]; 65 | } 66 | } 67 | return arr; 68 | } 69 | 70 | } 71 | 72 | console.log(sortArrayOf012([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ])); 73 | console.log(DNF.sort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ])); -------------------------------------------------------------------------------- /linked-list/merge-in-between-lists.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given two linked lists: list1 and list2 of sizes n and m respectively. 3 | 4 | Remove list1's nodes from the ath node to the bth node, and put list2 in their place. 5 | Build the result list and return its head. 6 | 7 | Example 1: 8 | Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] 9 | Output: [0,1,2,1000000,1000001,1000002,5] 10 | Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. 11 | */ 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * function ListNode(val, next) { 16 | * this.val = (val===undefined ? 0 : val) 17 | * this.next = (next===undefined ? null : next) 18 | * } 19 | */ 20 | /** 21 | * @param {ListNode} list1 22 | * @param {number} a 23 | * @param {number} b 24 | * @param {ListNode} list2 25 | * @return {ListNode} 26 | */ 27 | 28 | //?O(M*N) solution 29 | var mergeInBetween = function(list1, a, b, list2) { 30 | let left=list1,right=list2,curr = list1; 31 | let c1=0,c2=0; 32 | while(curr){ 33 | if(c1+1===a){ 34 | left = curr.next; 35 | curr.next = list2; 36 | while(curr.next!==null){ 37 | curr=curr.next; 38 | } 39 | curr.next = left; 40 | c1++; 41 | while(c1=0;i--){ 39 | if(dictionary[i].substr(0,pLen)===prefix && dictionary[i].substr(dictionary[i].length-sLen)===suffix) {index = i;break;} 40 | } 41 | this.map[prefix][suffix] = index; 42 | return index; 43 | }; 44 | 45 | /** 46 | * Your WordFilter object will be instantiated and called as such: 47 | * var obj = new WordFilter(words) 48 | * var param_1 = obj.f(prefix,suffix) 49 | */ 50 | 51 | var obj = new WordFilter(['test','te24s2t']) 52 | var param_1 = obj.f("te","t") 53 | console.log("found at =>",param_1) 54 | 55 | /** 56 | * ["WordFilter","f","f","f","f","f","f","f","f","f","f"] 57 | [[["cabaabaaaa","ccbcababac","bacaabccba","bcbbcbacaa","abcaccbcaa","accabaccaa","cabcbbbcca","ababccabcb","caccbbcbab","bccbacbcba"]],["bccbacbcba","a"],["ab","abcaccbcaa"],["a","aa"],["cabaaba","abaaaa"],["cacc","accbbcbab"],["ccbcab","bac"],["bac","cba"],["ac","accabaccaa"],["bcbb","aa"],["ccbca","cbcababac"]] 58 | */ -------------------------------------------------------------------------------- /maychallenge/construct-array-with-multiple-sums.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers target. From a starting array, A consisting of all 1's, you may perform the following procedure : 3 | 4 | let x be the sum of all elements currently in your array. 5 | choose index i, such that 0 <= i < target.size and set the value of A at index i to x. 6 | You may repeat this procedure as many times as needed. 7 | Return True if it is possible to construct the target array from A otherwise return False. 8 | 9 | 10 | **Example 1: 11 | 12 | *?Input: target = [9,3,5] 13 | *?Output: true 14 | *?Explanation: Start with [1, 1, 1] 15 | *?[1, 1, 1], sum = 3 choose index 1 16 | *?[1, 1, 3], sum = 5 choose index 2 -> sum = 5 17 | *?[1, 5, 3], sum = 9 choose index 0 -> sum = 9, diff=8 18 | *?[9, 5, 3] Done -> sum = 17, diff = 17-9=8, 9-diff =1 -> sum = 9,target[2] =1; 19 | */ 20 | 21 | 22 | /** 23 | * @param {number[]} target 24 | * @return {boolean} 25 | */ 26 | var isPossible = function(target) { 27 | let heap = [,], sum = 0 28 | 29 | const heapify = val => { 30 | let i = heap.length, par = i >> 1, temp 31 | heap.push(val) 32 | while (heap[par] < heap[i]) { 33 | temp = heap[par], heap[par] = heap[i], heap[i] = temp 34 | i = par, par = i >> 1 35 | } 36 | } 37 | const extract = () => { 38 | if (heap.length === 1) return null 39 | let top = heap[1], left, right, temp, 40 | i = 1, child = heap[3] > heap[2] ? 3 : 2 41 | if (heap.length > 2) heap[1] = heap.pop() 42 | else heap.pop() 43 | while (heap[i] < heap[child]) { 44 | temp = heap[child], heap[child] = heap[i], heap[i] = temp 45 | i = child, left = i << 1, right = left + 1 46 | child = heap[right] > heap[left] ? right : left 47 | } 48 | return top 49 | } 50 | 51 | for (let num of target) sum += num, heapify(num) 52 | while (heap[1] !== 1) { 53 | let num = extract() 54 | sum -= num 55 | if (num <= sum || sum < 1) return false 56 | num %= sum, sum += num, heapify(num) 57 | } 58 | return true 59 | }; 60 | 61 | console.log(isPossible([9,3,5])) 62 | console.log(isPossible([1,1,1,2])) 63 | console.log(isPossible([8,5])) 64 | -------------------------------------------------------------------------------- /maychallenge/super-palindromes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. 3 | 4 | Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]. 5 | 6 | 7 | Example 1: 8 | 9 | Input: left = "4", right = "1000" 10 | Output: 4 11 | Explanation: 4, 9, 121, and 484 are superpalindromes. 12 | Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome. 13 | */ 14 | 15 | 16 | /** 17 | * @param {string} left 18 | * @param {string} right 19 | * @return {number} 20 | */ 21 | var superpalindromesInRange = function(left, right) { 22 | let ans = 9 >= left && 9 <= right ? 1 : 0 23 | 24 | const isPal = str => { 25 | for (let i = 0, j = str.length - 1; i < j; i++, j--) 26 | if (str.charAt(i) !== str.charAt(j)) return false 27 | return true 28 | } 29 | 30 | for (let dig = 1; dig < 10; dig++) { 31 | let isOdd = dig % 2 && dig !== 1, 32 | innerLen = (dig >> 1) - 1, innerLim = Math.max(1, 2 ** innerLen), 33 | midPos = dig >> 1, midLim = isOdd ? 3 : 1 34 | for (let edge = 1; edge < 3; edge++) { 35 | let pal = new Uint8Array(dig) 36 | pal[0] = edge, pal[dig-1] = edge 37 | if (edge === 2) innerLim = 1, midLim = Math.min(midLim, 2) 38 | for (let inner = 0; inner < innerLim; inner++) { 39 | if (inner > 0) { 40 | let innerStr = inner.toString(2).padStart(innerLen, '0') 41 | for (let i = 0; i < innerLen; i++) 42 | pal[1+i] = innerStr[i], pal[dig-2-i] = innerStr[i] 43 | } 44 | for (let mid = 0; mid < midLim; mid++) { 45 | if (isOdd) pal[midPos] = mid 46 | let palin = ~~pal.join(""), 47 | square = BigInt(palin) * BigInt(palin) 48 | if (square > right) return ans 49 | if (square >= left && isPal(square.toString())) ans++ 50 | } 51 | } 52 | } 53 | } 54 | return ans 55 | }; 56 | 57 | 58 | console.log(superpalindromesInRange(4,10000000000000000)); -------------------------------------------------------------------------------- /contest/weekly/contest-239/minimum-adjacent-swaps-to-reach-kth-smallest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} num 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var getMinSwaps = function(num, k) { 7 | num = num.split("").map((val)=>parseInt(val)); 8 | let copy = [...num]; 9 | let tot = 0;let swap = 0; 10 | for(let i=0;i0;i--){ 34 | if(arr[i]>arr[i-1]){ 35 | pivot = i-1; 36 | let nextLargest = i; 37 | for(let j=i;jarr[pivot]&&arr[j]<=arr[nextLargest]) { 39 | nextLargest = j; 40 | } 41 | } 42 | let temp = arr[pivot]; 43 | arr[pivot] = arr[nextLargest]; 44 | arr[nextLargest] = temp; 45 | let start = pivot+1; 46 | let end = len -1; 47 | while(start<=end){ 48 | let t = arr[start]; 49 | arr[start] = arr[end]; 50 | arr[end] = t; 51 | swaps++; 52 | start++; 53 | end--; 54 | } 55 | return arr; 56 | } 57 | 58 | } 59 | if(pivot===-1){ 60 | let start = pivot+1; 61 | let end = len -1; 62 | 63 | while(start<=end){ 64 | let t = arr[start]; 65 | arr[start] = arr[end]; 66 | arr[end] = t; 67 | swaps++; 68 | start++; 69 | end--; 70 | } 71 | return arr; 72 | } 73 | } 74 | } 75 | 76 | console.log(getMinSwaps("5489355142",4)) -------------------------------------------------------------------------------- /Arrays/buy-and-sell-stocks-to-maximize-profit.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given an array prices where prices[i] is the price of a given stock on the ith day. 3 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 4 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 5 | */ 6 | 7 | class Profit { 8 | static stock(prices){ 9 | let minPrice = 100001; 10 | let maxProfit = 0; 11 | let len = prices.length; 12 | for(let i=0;imaxProfit) maxProfit = prices[i]-minPrice; 15 | } 16 | return maxProfit; 17 | } 18 | 19 | } 20 | 21 | /* 22 | NOt passing all test cases 23 | static mergingProcess(prices){ 24 | let len = prices.length; 25 | for(let i=0;i0;i--){ 13 | console.log("Arr[i] :",arr[i]); 14 | if(arr[i]>arr[i-1]){ 15 | pivot = i-1; 16 | let nextLargest = i; 17 | console.log("Arr[pivot] :",arr[pivot]," Arr[nxt_largest] :",arr[nextLargest]); 18 | for(let j=i;jarr[pivot]&&arr[j]<=arr[nextLargest]) { 20 | nextLargest = j; 21 | console.log("Next arr[nxt_largest] :",arr[nextLargest]); 22 | } 23 | } 24 | console.log("Arr before exchange of piv and nlrg :",arr); 25 | let temp = arr[pivot]; 26 | arr[pivot] = arr[nextLargest]; 27 | arr[nextLargest] = temp; 28 | console.log("Arr after exchange of piv and nlrg :",arr); 29 | let start = pivot+1; 30 | let end = len -1; 31 | while(start<=end){ 32 | let t = arr[start]; 33 | arr[start] = arr[end]; 34 | arr[end] = t; 35 | start++; 36 | end--; 37 | } 38 | console.log("Arr after reverse of nlar -> n :",arr); 39 | return arr; 40 | } 41 | 42 | } 43 | if(pivot===-1){ 44 | let start = pivot+1; 45 | let end = len -1; 46 | 47 | while(start<=end){ 48 | let t = arr[start]; 49 | arr[start] = arr[end]; 50 | arr[end] = t; 51 | start++; 52 | end--; 53 | } 54 | return arr; 55 | } 56 | } 57 | } 58 | 59 | console.log(Permutation.nextLarger([1,5,8,4,7,6,5,3,1])) 60 | 61 | -------------------------------------------------------------------------------- /string/extras/rearrange-words-in-string.js: -------------------------------------------------------------------------------- 1 | //!brute force solution 2 | // var arrangeWords = function(text) { 3 | // text = text.toLowerCase().split(" "); 4 | // for(let i =0;irightArr[j][0].length){ 40 | // merged.push(rightArr[j]); 41 | // j++; 42 | // } 43 | // else { 44 | // if(leftArr[i][1] { 65 | return a.length < b.length ? -1 : 1 66 | }) 67 | .join(' ') 68 | 69 | return newOrder.charAt(0).toUpperCase() + newOrder.slice(1) 70 | 71 | }; --------------------------------------------------------------------------------