├── .gitignore ├── .vscode ├── interview.txt └── settings.json ├── Arrays ├── Extras │ ├── Kids-with0greatest-number-of-candies.js │ ├── Number-of-good-pairs.js │ ├── Shuffle-the-array.js │ ├── binary-search.js │ ├── combination-sum.js │ ├── container-with-most-water.js │ ├── count-of-matches-in-a-tournament.js │ ├── fibonacci-sequence-at-n.js │ ├── find-all-numbers-disappeared-in-array.js │ ├── find-minimum-sum-of-products-for-two-arrrays.js │ ├── find-pivot-index.js │ ├── first-and-last-position-of-target-in-sorted-array.js │ ├── first-negative-integer-in-subarray-of-size-k.js │ ├── largest-continuous-increasing-subsequence.js │ ├── majority-element.js │ ├── max-consecutive-ones-in-array.js │ ├── minimum-number-operations-to-all-balls-to-each-box.js │ ├── minimum-size-subarray-with-sum.js │ ├── move-zeroes-to-the-end.js │ ├── number-of-teams.js │ ├── position-to-insert.js │ ├── ranges-array.js │ ├── remove-duplicates-from-sorted-array.js │ ├── reveal-cards-in-inreasing-order.js │ ├── sorting-algorithms.js │ ├── three-sum-closest.js │ └── three-sum.js ├── buy-and-sell-stocks-to-maximize-profit.js ├── check-if-array2-is-subset-of-array1.js ├── chocolate-distribution-problem.js ├── common-elements-in-three-sorted-arrays.js ├── count-inversions.js ├── count-pairs-with-given-sum.js ├── duplicate-in-an-array.js ├── elements-occuring-more-than-n-by-k-times.js ├── factorial-of-a-large-number.js ├── kth-smallest-array.js ├── largest-sum-contiguous-subarray.js ├── longest-consecutive-subsequence.js ├── maximum-product-subarray.js ├── merge-2-sorted-arrays-without-extra-space.js ├── merge-overlapping-intervals.js ├── min-max-of-array.js ├── minimize-maximum-difference-between-heights.js ├── minimum-number-of-jumps-to-reach-end.js ├── minimum-number-of-swaps-to-bring-together.js ├── move-negative-to-one-side.js ├── next-larger-permutation.js ├── palindrome-min-swaps.js ├── rearrange-array-in-alternating-positive-and-negative-items.js ├── reverse_an_array.js ├── rotate-array-clockwise-by-1.js ├── same-size-median-of-two-sorted-arrays.js ├── smallest-sum-subarray.js ├── sort-array-of-0-1-2.js ├── sum-of-subarray-is-0.js ├── tempCodeRunnerFile.js ├── three-way-partitioning.js ├── trapping-rainwater.js ├── triplet-sum-in-array.js └── union-intersection-of-2-sorted-arrays.js ├── README.md ├── contest ├── biweekly │ └── constest-51 │ │ ├── closest-room.js │ │ ├── max-element-after-decreasing-and-rearranging.js │ │ ├── replace-all-digits-with-characters.js │ │ └── seat-reservation-manager.js ├── check-if-string-is-pangram.js ├── evaluate-bracket-pairs-of-string.js ├── find-winner-of-circular-game.js ├── integers-in-a-string.js ├── longest-substring-containing-all-vowels-in-order.js ├── max-icecream-bars.js ├── minimum-ops-to-reinitialize-perm.js ├── sum-of-digits-in-base-k.js ├── weekly │ ├── contest-239 │ │ ├── minimum-adjacent-swaps-to-reach-kth-smallest.js │ │ ├── minimum-distance-to-target-element.js │ │ └── split-string-into-ddescending-consecutive-values.js │ └── contest-240 │ │ ├── max-population-year.js │ │ ├── maximum-distance-between-pair-of-values.js │ │ └── maximum-subarray-min-product.js └── xor-sum-of-bitwise-and-pairs.js ├── last-return.js ├── linked-list ├── add-two-numbers-2.js ├── add-two-numbers.js ├── convert-binary-number-in-a-linked-list-to-integer.js ├── insertion-sort-list.js ├── intersection-of-two-linked-lists.js ├── linked-list-cycle.js ├── merge-in-between-lists.js ├── merge-two-sorted-linked-list.js ├── middle-of-the-linked-list.js ├── next-greater-node-in-linked-list.js ├── odd-even-linked-list.js ├── partition-list.js ├── remove-duplicates-from-sorted-list-2.js ├── remove-duplicates-from-sorted-list.js ├── remove-linked-list-elements.js ├── reorder-list.js ├── reverse-linked-list-2.js ├── reverse-linked-list.js ├── sort-list.js ├── swap-nodes-in-pairs.js └── swapping-nodes-in-linked-list.js ├── matrices ├── common-elements-of-all-rows.js ├── extras │ └── transpose-of-matrix.js ├── find-specific-pair-in-matrix.js ├── max-area-rectangle-in-binary-matrix.js ├── median-of-rowwise-sorted-matrix.js ├── rotate-matrix-by-90deg-clockwise.js ├── row-wih-max-number-of-ones.js ├── search-element-in-matrix.js ├── sort-matrix-row-column-wise.js └── spiral-traversal-of-matrix.js ├── maychallenge ├── N-queens-2.js ├── ambiguous-coordinates.js ├── binary-tree-cameras.js ├── binary-tree-level-order-traversal.js ├── construct-array-with-multiple-sums.js ├── convert-sorted-list-to-balance-bst.js ├── coun-primes.js ├── course-schedule-3.js ├── delete-operations-on-string.js ├── evaluate-reverse-polish-notation.js ├── find-and-replace-pattern.js ├── find-duplicate-file-in-system.js ├── flatten-binary-tree-to-linkedlist.js ├── jumping-game-2.js ├── longest-string-chain.js ├── max-points-you-can-obtain-from-cards.js ├── maximum-erasure-value.js ├── maximum-gap.js ├── maximum-product-of-word-length.js ├── min-moves-to-equal-array-elements-2.js ├── n-queens.js ├── non-decreasing-array.js ├── partitioning-into-minimum-number-of-deci-binary-numbers.js ├── prefix-suffix-search.js ├── range-sum-query-2d.js ├── running-sum-of-1d-array.js ├── search-suggestion-system.js ├── super-palindromes.js ├── to-lower-case.js └── valid-number.js ├── most-liked-questions └── product-of-array-except-self.js ├── node_modules └── @datastructures-js │ ├── heap │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── index.js │ ├── package.json │ └── src │ │ ├── heap.js │ │ ├── maxHeap.js │ │ └── minHeap.js │ └── priority-queue │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── index.js │ ├── package.json │ └── src │ ├── maxPriorityQueue.js │ ├── minPriorityQueue.js │ └── priorityQueue.js ├── package-lock.json ├── sorting-searching ├── intersection-of-2-arrays-2.js ├── kth-strongest-values-in-an-array.js ├── largest-number.js ├── largest-perimeter-triangle.js ├── least-number-of-unique-integers-after-k-removals.js ├── max-units-on-truck.js ├── range-sum-of-sorted-arrays.js ├── remove-closed-intervals.js ├── shuffle-string.js ├── sort-array-by-increasing-frequency.js ├── sort-array-by-parity-2.js ├── sort-integers-by-power-value.js ├── sort-matrix-diagonally.js └── valid-anagram.js └── string ├── check-if-string-is-palindrome.js ├── check-if-strings-are-rotations-of-each-other.js ├── duplicates-in-string.js ├── extras ├── Check-if-word-equals-summation-of-two-words.js ├── Longest-Substring-Without-Repeating-Characters.js ├── add-binary.js ├── count-binary-substrings.js ├── count-the-number-of-consistent-strings.js ├── custom-sort-string.js ├── decrypt-string-from-alphabet-to-integer-mapping.js ├── delete-operations-on-strings.js ├── destination-city.js ├── determine-if-string-halves-are-alike.js ├── group-anagrams.js ├── longest-common-subsequence.js ├── make-the-string-great.js ├── max-number-of-vowels-in-substring-of-given-length.js ├── minimum-swaps-to-make-strings-anagram.js ├── multiply-strings.js ├── rearrange-words-in-string.js ├── reverse-vowels.js ├── search-suggestion-system.js ├── unique-email-addresses.js ├── valid-palindrome-2.js ├── valid-palindrome.js └── valid-parentheses.js ├── largest-palindrome-in-a-string.js ├── longest-repeating-subsequence.js ├── print-all-subsequences-of-a-string.js └── string-is-a-shuffle-of-2-strings-or-not.js /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "better-comments.highlightPlainText": true, 3 | "codesnap.backgroundColor": "none" 4 | } -------------------------------------------------------------------------------- /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/Extras/Number-of-good-pairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers nums. 3 | 4 | A pair (i,j) is called good if nums[i] == nums[j] and i < j. 5 | 6 | Return the number of good pairs. 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {number} 12 | */ 13 | var numIdenticalPairs = function(nums) { 14 | if(nums.length===1) return 0; 15 | 16 | nums.forEach((val,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 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)); -------------------------------------------------------------------------------- /Arrays/Extras/find-all-numbers-disappeared-in-array.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements of [1, n] inclusive that do not appear in this array. 5 | */ 6 | 7 | class FindDisappeared{ 8 | static numbersInRange(nums) { 9 | let count = 1;let missing=[]; 10 | let length = nums.length; 11 | nums= [...new Set(nums)]; 12 | while(count<=length){ 13 | if(nums.indexOf(count)===-1) missing.push(count); 14 | count++; 15 | } 16 | return missing; 17 | } 18 | 19 | //more efficient in space and time -> 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 | -------------------------------------------------------------------------------- /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/first-negative-integer-in-subarray-of-size-k.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Each test case contains an integer n denoting the size of the array. The next line contains n space separated integers forming the array. The last line contains the window size k. 3 | Output: 4 | Print the space separated negative integer starting from the first till the end for every window size k. If a window does not contain a negative integer , then print 0 for that window. 5 | */ 6 | 7 | /** 8 | * Sample 9 | * Input: 10 | 5 11 | -8 2 3 -6 10 12 | 2 13 | Output : 14 | -8 0 -6 -6 15 | */ 16 | 17 | class FirstNegativeInteger { 18 | static inSubArray(n,arr,k){ 19 | let prevNeg = 0; 20 | let firstNegative; 21 | for(let i=k-1;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/Extras/largest-continuous-increasing-subsequence.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. 3 | 4 | A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. 5 | 6 | Input: nums = [1,3,5,4,7] 7 | Output: 3 8 | Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3. 9 | 10 | Input: nums = [2,2,2,2,2] 11 | Output: 1 12 | Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly 13 | increasing. 14 | */ 15 | 16 | class LargestContinuousIncreasingSubsequence{ 17 | static bySlidingWindow(nums){ 18 | let len = nums.length; 19 | if(len<=1) return len; 20 | let l=0,r=0,max=0; 21 | for(let i =0;imax ? r-l+1 : max; 24 | if(nums[i]>=nums[i+1]) {l=i+1;r=i+1;} 25 | } 26 | return max; 27 | } 28 | } -------------------------------------------------------------------------------- /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(i=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 a [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(start 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]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/remove-duplicates-from-sorted-array.js: -------------------------------------------------------------------------------- 1 | function removeDuplicates(nums) { 2 | let length = nums.length; 3 | 4 | if(length == 0) 5 | return 0; 6 | 7 | let i; 8 | let targetIndex = 1; 9 | let OG = nums[0]; 10 | console.log("OG : ",OG); 11 | for(i = 1; i < length; i++){ 12 | 13 | if(nums[i] != OG){ 14 | 15 | OG = nums[i]; 16 | console.log("OG : ",OG); 17 | console.log("target index : ",targetIndex,"i :",i); 18 | nums[targetIndex] = nums[i]; 19 | console.log("target index val: ",nums[targetIndex],"i val:",nums[i]); 20 | targetIndex++; 21 | console.log("target index : ",targetIndex) 22 | } 23 | console.log("nums : ",nums) 24 | } 25 | 26 | return nums.splice(0,targetIndex); 27 | }; 28 | 29 | console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4,4,4,4,4,4,4,4,4,4,4,6,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9])); -------------------------------------------------------------------------------- /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 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)); -------------------------------------------------------------------------------- /Arrays/check-if-array2-is-subset-of-array1.js: -------------------------------------------------------------------------------- 1 | const Sort = require("../Extras/sorting-algorithms") 2 | class Subset { 3 | static ofArray(arr1,arr2){ 4 | arr1 = Sort.quickSort(arr1); 5 | let subset = true; 6 | for(let i=0;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)) -------------------------------------------------------------------------------- /Arrays/chocolate-distribution-problem.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that : 3 | **1. Each student gets exactly one packet. 4 | **2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum. 5 | 6 | *!The difference should be minimum, so even after sorting we need to find out the minimum difference subarray of the sorted array 7 | */ 8 | 9 | const Sort = require("../Extras/sorting-algorithms") 10 | 11 | class Chocolate{ 12 | static distribution(a,n,m){ 13 | if(m>n) return -1; 14 | a = Sort.quickSort(a); 15 | let diff = 0,minDiff = Number.MAX_VALUE; 16 | for(let i =0;i 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])); -------------------------------------------------------------------------------- /Arrays/count-inversions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Question Statement from Leetcode 3 | * We have some permutation A of [0, 1, ..., N - 1], where N is the length of A. 4 | 5 | The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > 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/count-pairs-with-given-sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K. 3 | 4 | Example 1: 5 | Input: 6 | N = 4, K = 6 7 | arr[] = {1, 5, 7, 1} 8 | Output: 2 9 | Explanation: 10 | arr[0] + arr[1] = 1 + 5 = 6 11 | and arr[1] + arr[3] = 5 + 1 = 6. 12 | 13 | Example 2: 14 | Input: 15 | N = 4, X = 2 16 | arr[] = {1, 1, 1, 1} 17 | Output: 6 18 | Explanation: 19 | Each 1 will produce sum 2 with any 1. 20 | */ 21 | 22 | class Count { 23 | static pairs(arr,n,k){ 24 | let pairCount=0; 25 | for(let i=0;i0){ 29 | for(let j=i+1;jMath.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] -------------------------------------------------------------------------------- /Arrays/factorial-of-a-large-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer, the task is to find factorial of the number. 3 | 4 | Input: 5 | The first line of input contains an integer T denoting the number of test cases. 6 | The first line of each test case is N,the number whose factorial is to be found 7 | 8 | Output: 9 | Print the factorial of the number in separate line. 10 | */ 11 | 12 | class Factorial { 13 | 14 | static ofLargeNumbers(T, nArr){ 15 | for(let i=0;inums[i] ? currSum+nums[i] : nums[i]; 7 | max = max 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=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/minimize-maximum-difference-between-heights.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array arr[] denoting heights of N towers and a positive integer K, you have to modify the height of each tower either by increasing or decreasing them by K only once. After modifying, height should be a non-negative integer. 3 | Find out what could be the possible minimum difference of the height of shortest and longest towers after you have modified each tower. 4 | 5 | 6 | Example 1: 7 | 8 | Input: 9 | K = 2, N = 4 10 | Arr[] = {1, 5, 8, 10} 11 | Output: 12 | 5 13 | Explanation: 14 | The array can be modified as 15 | {3, 3, 6, 8}. The difference between 16 | the largest and the smallest is 8-3 = 5. 17 | Example 2: 18 | 19 | Input: 20 | K = 3, N = 5 21 | Arr[] = {3, 9, 12, 16, 20} 22 | Output: 23 | 11 24 | Explanation: 25 | The array can be modified as 26 | {6, 12, 9, 13, 17}. The difference between 27 | the largest and the smallest is 17-6 = 11. 28 | */ 29 | 30 | class Heights{ 31 | static minimizeMaxDiff(arr,k){ 32 | let big = arr[arr.length-1]+k; 33 | let small = arr[0]-k>0 ? 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 &&currDiffk) 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)); -------------------------------------------------------------------------------- /Arrays/move-negative-to-one-side.js: -------------------------------------------------------------------------------- 1 | const moveNegative = function(arr){ 2 | let negCount = 0; 3 | const len = arr.length; 4 | for(let i=0;i=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 ] -------------------------------------------------------------------------------- /Arrays/palindrome-min-swaps.js: -------------------------------------------------------------------------------- 1 | //![3,4,5,5,4,3] 2 | //*[3,4,5,0,5,4,3] 3 | 4 | class MinSwaps{ 5 | static toCheckPalindrome(a,n){ 6 | for(let i = 0;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)); -------------------------------------------------------------------------------- /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(start [ '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] -------------------------------------------------------------------------------- /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/sort-array-of-0-1-2.js: -------------------------------------------------------------------------------- 1 | const sortArrayOf012 = function(arr){ 2 | let c0=0,c1=0,c2=0; 3 | for(let i=0;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 ])); -------------------------------------------------------------------------------- /Arrays/sum-of-subarray-is-0.js: -------------------------------------------------------------------------------- 1 | class FindSubArray{ 2 | static withSumZero(n,arr){ 3 | if(arr.indexOf(0)!==-1) return true; 4 | let sum = 0; 5 | let sumArr = []; 6 | 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 -------------------------------------------------------------------------------- /Arrays/tempCodeRunnerFile.js: -------------------------------------------------------------------------------- 1 | // else { 2 | // count +=2; 3 | // prev = nums1[i]; 4 | // curr = nums1[i]; 5 | // i++;j++; 6 | // } -------------------------------------------------------------------------------- /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] 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 | }; -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /contest/biweekly/constest-51/closest-room.js: -------------------------------------------------------------------------------- 1 | var closestRoom = function(rooms, queries) { 2 | let res = []; 3 | rooms.sort((a,b)=> 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(tar a-b); 22 | if(arr[0]!==1) arr[0] = 1; 23 | let prev = arr[0],curr; 24 | for(let i=1;i=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 { 25 | nArr[index] = parseInt(num); 26 | }); 27 | nArr = nArr.sort((a,b)=> a-b); 28 | let i =0; 29 | while(i ",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")); -------------------------------------------------------------------------------- /contest/max-icecream-bars.js: -------------------------------------------------------------------------------- 1 | /** 2 | * It is a sweltering summer day, and a boy wants to buy some ice cream bars. 3 | 4 | At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. 5 | 6 | Return the maximum number of ice cream bars the boy can buy with coins coins. 7 | 8 | Note: The boy can buy the ice cream bars in any order. 9 | */ 10 | 11 | 12 | /** 13 | * @param {number[]} costs 14 | * @param {number} coins 15 | * @return {number} 16 | */ 17 | var maxIceCream = function(costs, coins) { 18 | costs = Sort.mergeSort(costs); 19 | let max =0; 20 | for(let i=0;icoins) 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",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;i0){ 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 | }; -------------------------------------------------------------------------------- /contest/weekly/contest-239/minimum-distance-to-target-element.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x. 3 | 4 | Return abs(i - start). 5 | 6 | It is guaranteed that target exists in nums 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @param {number} target 12 | * @param {number} start 13 | * @return {number} 14 | */ 15 | var getMinDistance = function(nums, target, start) { 16 | let ti=null,diff = Number.MAX_VALUE; 17 | 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/weekly/contest-240/maximum-distance-between-pair-of-values.js: -------------------------------------------------------------------------------- 1 | /** 2 | * *You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. 3 | 4 | **A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. 5 | ** 6 | **Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. 7 | ** 8 | **An array arr is non-increasing if arr[i-1] >= 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(iprevMin){ 20 | 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /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;i0) 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)); -------------------------------------------------------------------------------- /linked-list/add-two-numbers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 3 | 4 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 5 | */ 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | */ 10 | 11 | /** 12 | * @param {ListNode} l1 13 | * @param {ListNode} l2 14 | * @return {ListNode} 15 | */ 16 | 17 | //?faster than 75% -> 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 | }; -------------------------------------------------------------------------------- /linked-list/convert-binary-number-in-a-linked-list-to-integer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 3 | 4 | Return the decimal value of the number in the linked list. 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 {number} 17 | */ 18 | 19 | //?accepted -> 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;i 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 | }; -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /linked-list/linked-list-cycle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given head, the head of a linked list, determine if the linked list has a cycle in it. 3 | 4 | There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. 5 | 6 | Return true if there is a cycle in the linked list. Otherwise, return false. 7 | */ 8 | 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * function ListNode(val) { 13 | * this.val = val; 14 | * this.next = null; 15 | * } 16 | */ 17 | 18 | /** 19 | * @param {ListNode} head 20 | * @return {boolean} 21 | */ 22 | var hasCycle = function(head) { 23 | if(head===null) return false; 24 | let seen = []; 25 | let curr = head.next,prev=head; 26 | while(prev!==curr){ 27 | if(curr===null || curr.next===null){ 28 | return false; 29 | } 30 | curr = curr.next.next; 31 | prev = prev.next; 32 | } 33 | return true; 34 | }; -------------------------------------------------------------------------------- /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 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 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 | }; -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /linked-list/partition-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 3 | 4 | You should preserve the original relative order of the nodes in each of the two partitions. 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 | * @param {number} x 17 | * @return {ListNode} 18 | */ 19 | 20 | //*Time Complexity -> 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 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 | }; -------------------------------------------------------------------------------- /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/swap-nodes-in-pairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 3 | */ 4 | 5 | //* faster than 85% -> 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 | }; -------------------------------------------------------------------------------- /linked-list/swapping-nodes-in-linked-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given the head of a linked list, and an integer k. 3 | 4 | Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). 5 | 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * function ListNode(val, next) { 11 | * this.val = (val===undefined ? 0 : val) 12 | * this.next = (next===undefined ? null : next) 13 | * } 14 | */ 15 | /** 16 | * @param {ListNode} head 17 | * @param {number} k 18 | * @return {ListNode} 19 | */ 20 | var swapNodes = function(head, k) { 21 | let arr =[]; 22 | let curr = head; 23 | while(curr.next!==null){ 24 | arr.push(curr.val); 25 | curr = curr.next; 26 | } 27 | arr.push(curr.val); 28 | let temp = arr[k-1]; 29 | arr[k-1]=arr[arr.length-k]; 30 | arr[arr.length-k] = temp; 31 | curr = head; 32 | let ind = 0; 33 | while(curr){ 34 | if(ind===k-1){ 35 | curr.val = arr[ind] 36 | } 37 | if(ind===arr.length-k){ 38 | curr.val = arr[ind] 39 | } 40 | curr = curr.next; 41 | ind++; 42 | } 43 | return head; 44 | }; -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 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)); -------------------------------------------------------------------------------- /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;itarget || 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)); -------------------------------------------------------------------------------- /matrices/sort-matrix-row-column-wise.js: -------------------------------------------------------------------------------- 1 | const Sort = require("../Arrays/Extras/sorting-algorithms"); 2 | 3 | class SortMatrix{ 4 | static sortedMatrix(N,Mat){ 5 | let sorted = []; 6 | let k=0,l=0; 7 | let i = 1,len = N*N; 8 | 9 | //O(N^2) 10 | while(i<=len){ 11 | sorted.push(Mat[k][l]); 12 | if(i%N == 0){ 13 | k = i/N; 14 | l=0; 15 | } 16 | else { 17 | l++; 18 | } 19 | i++; 20 | } 21 | 22 | //O(NlogN) 23 | sorted = Sort.quickSort(sorted); 24 | Mat = []; 25 | i=N;k=0; 26 | 27 | //O(log N) 28 | while(i<=len){ 29 | if(i%N == 0){ 30 | Mat[k] = [...sorted.slice(i-N,i)]; 31 | k = i/N; 32 | i = i+N; 33 | } 34 | // i++; 35 | } 36 | console.log("Matrix :\n",Mat); 37 | console.log("\n\nSorted :",sorted); 38 | } 39 | } 40 | 41 | SortMatrix.sortedMatrix(4,[[10,20,30,40],[15,25,35,45],[27,29,37,48],[32,33,39,50]]); -------------------------------------------------------------------------------- /matrices/spiral-traversal-of-matrix.js: -------------------------------------------------------------------------------- 1 | const process = require("process"); 2 | let mat = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]; 3 | //[13,14,15,16]]; 4 | 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)); -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /maychallenge/ambiguous-coordinates.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string[]} 4 | */ 5 | var ambiguousCoordinates = function(S) { 6 | let ans = [] 7 | const isValid = (str, dec) => { 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/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 | }; -------------------------------------------------------------------------------- /maychallenge/convert-sorted-list-to-balance-bst.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 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 | * Definition for a binary tree node. 16 | * function TreeNode(val, left, right) { 17 | * this.val = (val===undefined ? 0 : val) 18 | * this.left = (left===undefined ? null : left) 19 | * this.right = (right===undefined ? null : right) 20 | * } 21 | */ 22 | /** 23 | * @param {ListNode} head 24 | * @return {TreeNode} 25 | */ 26 | var sortedListToBST = function(head) { 27 | let curr = head, count = 0 28 | while (curr) curr = curr.next, count++ 29 | const treeify = (i, j) => { 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 | }; -------------------------------------------------------------------------------- /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/course-schedule-3.js: -------------------------------------------------------------------------------- 1 | /** 2 | * There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi. 3 | 4 | You will start on the 1st day and you cannot take two or more courses simultaneously. 5 | 6 | Return the maximum number of courses that you can take. 7 | */ 8 | 9 | 10 | /** 11 | * @param {number[][]} courses 12 | * @return {number} 13 | */ 14 | 15 | 16 | //!install using -> 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/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/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 | }; -------------------------------------------------------------------------------- /maychallenge/find-and-replace-pattern.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. 3 | 4 | A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. 5 | 6 | Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. 7 | 8 | 9 | */ 10 | 11 | /** 12 | * @param {string[]} words 13 | * @param {string} pattern 14 | * @return {string[]} 15 | */ 16 | var findAndReplacePattern = function(words, pattern) { 17 | let ans = [], codex = new Map() 18 | const translate = char => { 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 | }; -------------------------------------------------------------------------------- /maychallenge/find-duplicate-file-in-system.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order. 3 | 4 | A group of duplicate files consists of at least two files that have the same content. 5 | 6 | A single directory info string in the input list has the following format: 7 | 8 | "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)" 9 | It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 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 | }; -------------------------------------------------------------------------------- /maychallenge/flatten-binary-tree-to-linkedlist.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the root of a binary tree, flatten the tree into a "linked list": 3 | 4 | The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. 5 | The "linked list" should be in the same order as a pre-order traversal of the binary tree. 6 | */ 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * function TreeNode(val, left, right) { 11 | * this.val = (val===undefined ? 0 : val) 12 | * this.left = (left===undefined ? null : left) 13 | * this.right = (right===undefined ? null : right) 14 | * } 15 | */ 16 | /** 17 | * @param {TreeNode} root 18 | * @return {void} Do not return anything, modify root in-place instead. 19 | */ 20 | var flatten = function(root) { 21 | let head = null, curr = root 22 | while (head != root) { 23 | if (curr.right === head) curr.right = null 24 | if (curr.left === head) curr.left = null 25 | if (curr.right) curr = curr.right 26 | else if (curr.left) curr = curr.left 27 | else curr.right = head, head = curr, curr = root 28 | } 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /maychallenge/longest-string-chain.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list of words, each word consists of English lowercase letters. 3 | 4 | Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac". 5 | 6 | A word chain is a sequence of words [word_1, word_2, ..., word_k] with 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 | }; -------------------------------------------------------------------------------- /maychallenge/maximum-erasure-value.js: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. 3 | 4 | Return the maximum score you can get by erasing exactly one subarray. 5 | 6 | An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {number} 12 | */ 13 | var maximumUniqueSubarray = function(nums) { 14 | let nmap = new Int8Array(10001), total = 0, best = 0 15 | for (let left = 0, right = 0; right < nums.length; right++) { 16 | nmap[nums[right]]++, total += nums[right] 17 | while (nmap[nums[right]] > 1) 18 | nmap[nums[left]]--, total -= nums[left++] 19 | best = Math.max(best, total) 20 | } 21 | return best 22 | }; -------------------------------------------------------------------------------- /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;i 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 | }; -------------------------------------------------------------------------------- /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 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/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])) -------------------------------------------------------------------------------- /maychallenge/partitioning-into-minimum-number-of-deci-binary-numbers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. 3 | 4 | Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n. 5 | */ 6 | 7 | 8 | /** 9 | * @param {string} n 10 | * @return {number} 11 | */ 12 | var minPartitions = function(n) { 13 | return Math.max(...n.split('')); 14 | }; -------------------------------------------------------------------------------- /maychallenge/prefix-suffix-search.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Design a special dictionary which has some words and allows you to search the words in it by a prefix and a suffix. 3 | 4 | Implement the WordFilter class: 5 | 6 | WordFilter(string[] words) Initializes the object with the words in the dictionary. 7 | f(string prefix, string suffix) Returns the index of the word in the dictionary which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1. 8 | */ 9 | 10 | /** 11 | * @param {string[]} words 12 | */ 13 | var WordFilter = function(words) { 14 | this.dictionary = [...words]; 15 | this.map = {}; 16 | }; 17 | 18 | /** 19 | * @param {string} prefix 20 | * @param {string} suffix 21 | * @return {number} 22 | */ 23 | WordFilter.prototype.f = function(prefix, suffix) { 24 | this.map[prefix] = this.map[prefix] || {}; 25 | this.map[prefix][suffix] = this.map[prefix][suffix] || null; 26 | 27 | 28 | if(this.map[prefix][suffix]!==null){ 29 | return this.map[prefix][suffix]; 30 | } 31 | 32 | const dictionary = this.dictionary; 33 | let pLen = prefix.length; 34 | let sLen = suffix.length; 35 | let index = -1; 36 | 37 | 38 | for(let i=dictionary.length-1;i>=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/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 | */ -------------------------------------------------------------------------------- /maychallenge/running-sum-of-1d-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 3 | 4 | Return the running sum of nums. 5 | */ 6 | 7 | /** 8 | * @param {number[]} nums 9 | * @return {number[]} 10 | */ 11 | var runningSum = function(nums) { 12 | let sum = [nums[0]]; 13 | for(let i=1;i 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 | }; -------------------------------------------------------------------------------- /maychallenge/to-lower-case.js: -------------------------------------------------------------------------------- 1 | //Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. 2 | 3 | /** 4 | * @param {string} s 5 | * @return {string} 6 | */ 7 | var toLowerCase = function(s) { 8 | return s.toLowerCase(); 9 | }; 10 | 11 | var toLowerCase = function(s) { 12 | s = s.split(""); 13 | let curr = 0; 14 | for(let i=0;i=65 && curr<=90){ 17 | s[i] = String.fromCharCode(curr+32); 18 | } 19 | } 20 | return s.join(""); 21 | }; -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /most-liked-questions/product-of-array-except-self.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 5 | 6 | You must write an algorithm that runs in O(n) time and without using the division operation. 7 | 8 | */ 9 | 10 | /** 11 | * @param {number[]} nums 12 | * @return {number[]} 13 | */ 14 | 15 | //? faster than 12% 16 | var productExceptSelf = function(nums) { 17 | let lProd = [nums[0]],rProd = [nums[nums.length-1]]; 18 | let r = rProd[0]; 19 | for(let i=1;i 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/heap/index.js: -------------------------------------------------------------------------------- 1 | const MinHeap = require('./src/minHeap'); 2 | const MaxHeap = require('./src/maxHeap'); 3 | 4 | exports.MinHeap = MinHeap; 5 | exports.MaxHeap = MaxHeap; 6 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/heap/src/maxHeap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @copyright 2020 Eyas Ranjous 4 | */ 5 | 6 | const Heap = require('./heap'); 7 | 8 | /** 9 | * @class MaxHeap 10 | * @extends Heap 11 | */ 12 | class MaxHeap extends Heap { 13 | /** 14 | * Checks two nodes are in relatively valid position 15 | * @private 16 | * @param {object} parent 17 | * @param {object} child 18 | * @returns {boolean} 19 | */ 20 | _compareKeys(parentKey, childKey) { 21 | return parentKey > childKey; 22 | } 23 | 24 | /** 25 | * Returns max child's index of two children before an index 26 | * @private 27 | * @param {number} index 28 | * @param {number} leftChildIndex 29 | * @param {number} rightChildIndex 30 | * @returns {number} 31 | */ 32 | _compareChildrenBefore(index, leftChildIndex, rightChildIndex) { 33 | const leftChildKey = this._getKey(this._nodes[leftChildIndex]); 34 | const rightChildKey = this._getKey(this._nodes[rightChildIndex]); 35 | 36 | if (rightChildKey > leftChildKey && rightChildIndex < index) { 37 | return rightChildIndex; 38 | } 39 | return leftChildIndex; 40 | } 41 | 42 | /** 43 | * Returns a shallow copy of the heap 44 | * @public 45 | * @returns {MaxHeap} 46 | */ 47 | clone() { 48 | return super._clone(MaxHeap); 49 | } 50 | 51 | /** 52 | * Builds a max heap from an array of items 53 | * @public 54 | * @static 55 | * @param {array} list 56 | * @returns {MaxHeap} 57 | */ 58 | static heapify(list) { 59 | return super._heapify(list, MaxHeap); 60 | } 61 | 62 | /** 63 | * Checks if a list of items is a valid max heap 64 | * @public 65 | * @static 66 | * @param {array} list 67 | * @returns {boolean} 68 | */ 69 | static isHeapified(list) { 70 | return super._isHeapified(list, MaxHeap); 71 | } 72 | } 73 | 74 | module.exports = MaxHeap; 75 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/heap/src/minHeap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * @copyright 2019 Eyas Ranjous 4 | */ 5 | 6 | const Heap = require('./heap'); 7 | 8 | /** 9 | * @class MinHeap 10 | * @extends Heap 11 | */ 12 | class MinHeap extends Heap { 13 | /** 14 | * Checks two nodes are in relatively valid position 15 | * @private 16 | * @param {object} parent 17 | * @param {object} child 18 | * @returns {boolean} 19 | */ 20 | _compareKeys(parentKey, childKey) { 21 | return parentKey < childKey; 22 | } 23 | 24 | /** 25 | * Returns min child's index of two children before an index 26 | * @protected 27 | * @param {number} index 28 | * @param {number} leftChildIndex 29 | * @param {number} rightChildIndex 30 | * @returns {number} 31 | */ 32 | _compareChildrenBefore(index, leftChildIndex, rightChildIndex) { 33 | const leftChildKey = this._getKey(this._nodes[leftChildIndex]); 34 | const rightChildKey = this._getKey(this._nodes[rightChildIndex]); 35 | 36 | if (rightChildKey < leftChildKey && rightChildIndex < index) { 37 | return rightChildIndex; 38 | } 39 | return leftChildIndex; 40 | } 41 | 42 | /** 43 | * Returns a shallow copy of the heap 44 | * @public 45 | * @returns {MinHeap} 46 | */ 47 | clone() { 48 | return super._clone(MinHeap); 49 | } 50 | 51 | /** 52 | * Builds a min heap from an array of items 53 | * @public 54 | * @static 55 | * @param {array} list 56 | * @returns {MinHeap} 57 | */ 58 | static heapify(list) { 59 | return super._heapify(list, MinHeap); 60 | } 61 | 62 | /** 63 | * Checks if a list of list is a valid min heap 64 | * @public 65 | * @static 66 | * @param {array} list 67 | * @returns {boolean} 68 | */ 69 | static isHeapified(list) { 70 | return super._isHeapified(list, MinHeap); 71 | } 72 | } 73 | 74 | module.exports = MinHeap; 75 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/priority-queue/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | ## [5.0.3] - 2021-04-27 9 | 10 | ### Fixed 11 | - README 12 | 13 | ## [5.0.2] - 2021-03-12 14 | 15 | ### Fixed 16 | - README 17 | 18 | ## [5.0.1] - 2021-02-23 19 | 20 | ### Fixed 21 | - README 22 | 23 | ## [5.0.0] - 2021-01-24 24 | ### Changed 25 | - upgrade heap to latest major version. 26 | - `.enqueue` can now be chanined. 27 | 28 | ### Added 29 | - a default priority callback that returns the element itself if no callback is provided. 30 | 31 | ### Fixed 32 | - cleaner error messages. 33 | - README 34 | - jsdoc 35 | 36 | ## [4.1.2] - 2020-09-22 37 | ### Fixed 38 | - Allow any number value for priority. 39 | 40 | ## [4.1.1] - 2020-05-03 41 | ### Fixed 42 | - README 43 | - package.json 44 | 45 | ## [4.1.0] - 2020-04-22 46 | ### Added 47 | - allow passing a priority callback in constructor. 48 | 49 | ## [4.0.0] - 2020-04-13 50 | ### Changed 51 | - split PriorityQueue into `MinPriorityQueue` & `MaxPriorityQueue` to enable working with different type of priorities. 52 | 53 | ## [3.0.1] - 2020-04-11 54 | ### Fixed 55 | - jsdoc 56 | 57 | ## [3.0.0] - 2020-04-09 58 | ### Changed 59 | - `.front()`, `.back()`, `.dequeue()`, `.toArray()` now returns the priority with the element. 60 | 61 | ### Fixed 62 | - README 63 | - jsdoc 64 | 65 | ## [2.0.0] - 2020-03-09 66 | ### Changed 67 | - use a Min Heap to store queue elements. 68 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/priority-queue/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Eyas Ranjous 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /node_modules/@datastructures-js/priority-queue/index.js: -------------------------------------------------------------------------------- 1 | const MinPriorityQueue = require('./src/minPriorityQueue'); 2 | const MaxPriorityQueue = require('./src/maxPriorityQueue'); 3 | 4 | module.exports = { MinPriorityQueue, MaxPriorityQueue }; 5 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/priority-queue/src/maxPriorityQueue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @copyright 2020 Eyas Ranjous 3 | * @license MIT 4 | */ 5 | 6 | const { MaxHeap } = require('@datastructures-js/heap'); 7 | const PriorityQueue = require('./priorityQueue'); 8 | 9 | /** 10 | * @class MaxPriorityQueue 11 | * @extends PriorityQueue 12 | */ 13 | class MaxPriorityQueue extends PriorityQueue { 14 | constructor(options) { 15 | super(options); 16 | this._heap = new MaxHeap(); 17 | } 18 | } 19 | 20 | module.exports = MaxPriorityQueue; 21 | -------------------------------------------------------------------------------- /node_modules/@datastructures-js/priority-queue/src/minPriorityQueue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @copyright 2020 Eyas Ranjous 3 | * @license MIT 4 | */ 5 | 6 | const { MinHeap } = require('@datastructures-js/heap'); 7 | const PriorityQueue = require('./priorityQueue'); 8 | 9 | /** 10 | * @class MinPriorityQueue 11 | * @extends PriorityQueue 12 | */ 13 | class MinPriorityQueue extends PriorityQueue { 14 | constructor(options) { 15 | super(options); 16 | this._heap = new MinHeap(); 17 | } 18 | } 19 | 20 | module.exports = MinPriorityQueue; 21 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "requires": true, 3 | "lockfileVersion": 1, 4 | "dependencies": { 5 | "@datastructures-js/heap": { 6 | "version": "3.0.1", 7 | "resolved": "https://registry.npmjs.org/@datastructures-js/heap/-/heap-3.0.1.tgz", 8 | "integrity": "sha512-1nphUN9dVoVL2KsdipFYJMxgAZhsOE7fNEUW09IhT0z/cNFj5h6Nf3lcA1smCEC0BI420FTuPMcfOAi1Q7RELw==" 9 | }, 10 | "@datastructures-js/priority-queue": { 11 | "version": "5.0.3", 12 | "resolved": "https://registry.npmjs.org/@datastructures-js/priority-queue/-/priority-queue-5.0.3.tgz", 13 | "integrity": "sha512-owqR303gaR2Gk6KI1SbobLCjIK2vwwgpWlexa6LUkSSDlwrUKB+vf1nNGoM9Gy4SgKx3I9vyc0cmdvLryPmj9Q==", 14 | "requires": { 15 | "@datastructures-js/heap": "^3.0.0" 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /sorting-searching/intersection-of-2-arrays-2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * console.log(intersect([1,2,2,1],[2,2])) 4 | console.log(intersect([4,9,5],[9,4,9,8,4])) 5 | */ 6 | 7 | 8 | /** 9 | * @param {number[]} nums1 10 | * @param {number[]} nums2 11 | * @return {number[]} 12 | */ 13 | 14 | //?faster than 80%, more efficient than 60% 15 | var intersect = function(nums1, nums2) { 16 | if(nums2.length0){ 27 | intersec.push(nums2[i]); 28 | reps[nums2[i]] -= 1; 29 | } 30 | } 31 | 32 | return intersec; 33 | }; 34 | 35 | 36 | console.log(intersect([9],[9])) 37 | console.log(intersect([1,2,2,1],[2,2])) 38 | console.log(intersect([4,9,5],[9,4,9,8,4])) 39 | -------------------------------------------------------------------------------- /sorting-searching/kth-strongest-values-in-an-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers arr and an integer k. 3 | 4 | A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |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)) -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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-b) 25 | let sum = 0; 26 | for(let i=left-1;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 { 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), 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 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)) -------------------------------------------------------------------------------- /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(a0) 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/check-if-string-is-palindrome.js: -------------------------------------------------------------------------------- 1 | class PalindromeChecker{ 2 | static forString(str){ 3 | if(str.length<=1) return true; 4 | str = str.toLowerCase(); 5 | let i = 0,j=str.length-1; 6 | while(i",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;i count = ",dup[prop]); 20 | } 21 | } 22 | return dup; 23 | } 24 | } 25 | 26 | Duplicates.inString("geeksforgeeks"); 27 | Duplicates.inString("g"); -------------------------------------------------------------------------------- /string/extras/Check-if-word-equals-summation-of-two-words.js: -------------------------------------------------------------------------------- 1 | /** 2 | * The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 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",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/add-binary.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two binary strings a and b, return their sum as a binary string. 3 | */ 4 | 5 | class Solution { 6 | 7 | 8 | //?works -> 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/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",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"); -------------------------------------------------------------------------------- /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")); -------------------------------------------------------------------------------- /string/extras/delete-operations-on-strings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. 3 | 4 | *In one step, you can delete exactly one character in either string. 5 | */ 6 | 7 | class Solution { 8 | 9 | //!this does not work because though not specified in question, we need to consider the order of characters too 10 | static minDistance(word1, word2) { 11 | let hash1 = new Array(26).fill(0); 12 | let hash2 = new Array(26).fill(0); 13 | for(let i=0;i72 ms, faster than 99.10%,space -> 39.5 MB, less than 92.33% 23 | static destCity(paths){ 24 | for(let i=0;i O(n^2) 26 | //! for(let i=0;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=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")) -------------------------------------------------------------------------------- /string/extras/max-number-of-vowels-in-substring-of-given-length.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //!time limit exceeded 3 | // static maxVowels(s, k) { 4 | // let reg = /[aeiou]/g; 5 | // let max = 0; 6 | // for(let i =0;i<=s.length-k;i++){ 7 | // let curr = s.substr(i,k).match(reg); 8 | // console.log(s.substr(i,k),curr) 9 | // if(curr) max = Math.max(max,curr.length); 10 | // } 11 | // return max; 12 | // } 13 | 14 | static maxVowels(s,k){ 15 | var vowels = 'aeiou'; 16 | var max = 0; // result 17 | var count = 0; // count of vowels of current window 18 | for (var i = 0; i < s.length; i++) { 19 | if (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/extras/minimum-swaps-to-make-strings-anagram.js: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static minSteps(s,t){ 3 | let map = {} 4 | let count = 0; 5 | for (let char of s) { 6 | map[char] = ++map[char] || 1 7 | } 8 | for (let word of t) { 9 | if (map[word]) { 10 | map[word]--; 11 | continue; 12 | } 13 | count++; 14 | } 15 | return count; 16 | } 17 | } 18 | 19 | 20 | console.log(Solution.minSteps("gctcxyuluxjuxnsvmomavutrrfb", "qijrjrhqqjxjtprybrzpyfyqtzf")) -------------------------------------------------------------------------------- /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")); -------------------------------------------------------------------------------- /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 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")) -------------------------------------------------------------------------------- /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(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 -------------------------------------------------------------------------------- /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;i 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 --------------------------------------------------------------------------------