├── 0-1KnapsackProblem.java ├── 0-1KnapsackProblem.js ├── 3Sum.java ├── 3Sum.js ├── AddBinary.js ├── AddToArrayFormOfInteger.js ├── AddTwoNumbers.java ├── AddTwoNumbers.js ├── AlternatePositiveAndNegativeNumbers.js ├── ApplyOperationsToAnArray.java ├── ArrangeConsonantsAndVowels.java ├── ArrayPrototypeLast.js ├── ArraySubsetOfAnotherArray.js ├── BackspaceStringCompare.java ├── BalancedBinaryTree.java ├── BasicCalculator.js ├── BestTimeToBuyAndSellStock.js ├── BestTimeToBuyAndSellStockII.js ├── BestTimeToBuyAndSellStocksII.java ├── BestTimetoBuyandSellStock.java ├── BinarySearch.java ├── BinarySearch.js ├── BinaryTreeInorderTraversal.java ├── BinaryTreeInorderTraversal.js ├── BinaryTreeLevelOrderTraversal.java ├── BinaryTreeLevelOrderTraversal.js ├── BinaryTreeMaximumPathSum.js ├── BinaryTreePostorderTraversal.java ├── BinaryTreePreorderTraversal.java ├── BinaryTreeRightSideView.java ├── BinaryTreeRightSideView.js ├── BinaryTreeZigzagLevelOrderTraversal.js ├── BreakAPalindrome.java ├── BulbSwitcher.java ├── CanPlaceFlowers.js ├── CapacityToShipPackagesWithinDDays.js ├── CheckForBST.js ├── CheckIfArrayIsSortedAndRotated.js ├── CheckIfLinkedListIsPalindrome.js ├── CheckIfObjectInstanceOfClass.js ├── CheckIfStringIsRotatedByTwoPlaces.js ├── CheckIfStringsAreRotationsOfEachOtherOrNot.js ├── CheckIfTheSentenceIsPangram.java ├── CheckIfTwoStringArraysAreEquivalent.java ├── ChocolateDistributionProblem.js ├── ClimbingStairs.java ├── ClimbingStairs.js ├── CloneGraph.js ├── CoinChange(Combination)GFG.java ├── CombinationSum.js ├── CombinationSumII.js ├── CombinationSumIV.java ├── ConstructBinarySearchTreeFromPreorderTraversal.java ├── ConstructBinaryTreeFromPreorderAndInorderTraversal.js ├── ContainerWithMostWater.java ├── ContainerWithMostWater.js ├── ContainsDuplicate.java ├── ContainsDuplicate.js ├── ContinuousSubarraySum.java ├── ConvertSortedArrayToBinarySearchTree.java ├── CopyListWithRandomPointer.js ├── CountAndSay.java ├── CountInversions.js ├── CountNumberOfDistinctIntegersAfterReverseOperations.java ├── CountOddNumbersInAnIntervalRange.js ├── CountPairsWithGivenSum.js ├── CountPrimes.java ├── CountTheNumberOfConsistentStrings.js ├── CountTheTriplets.js ├── Counter.js ├── CyclicallyRotateArrayByOne.js ├── DeleteAndEarn.java ├── DeleteCharactersToMakeFancyString.js ├── DeleteColumnsToMakeSorted.js ├── DeleteMiddleElementOfAStack.java ├── DeleteNNodesAfterMNodesOfALinkedList.java ├── DeleteNNodesAfterMNodesOfALinkedList.js ├── DeleteNodeInABST.java ├── DeleteNodeInALinkedList.java ├── DeleteNodeInALinkedList.js ├── DeleteTheMiddleNodeOfALinkedList.java ├── DetectCapital.js ├── DetermineIfTwoEventsHaveConflict.java ├── DiameterOfBinaryTree.js ├── DivideTwoIntegers.js ├── DivisorGame.java ├── ExcelSheetColumnTitle.js ├── FactorialsOfLargeNumbers.js ├── FibonacciNumber.java ├── FibonacciNumber.js ├── FindAllAnagramsInAString.java ├── FindAllAnagramsInAString.js ├── FindAllDuplicatesInAnArray.js ├── FindCommonElementsInThreeSortedArrays.js ├── FindFirstAndLastPositionOfElementInSortedArray.java ├── FindFirstAndLastPositionOfElementInSortedArray.js ├── FindKClosestElements.java ├── FindKthSmallestElements.java ├── FindLargestWordInDictionary.js ├── FindMiddleElementInALinkedList.js ├── FindMinimumInRotatedSortedArray.js ├── FindMissingPositive.js ├── FindPeakElement.js ├── FindPivotIndex.java ├── FindTheDuplicateNumber..java ├── FindTheDuplicateNumber.js ├── FindTheIndexOfTheFirstOccurenceInAString.js ├── FindTheKthLargestIntegerInTheArray.java ├── FindTheMinimumAndMaximumNumberOfNodesBetweenCriticalPoints.js ├── FindTheTownJudge.js ├── FindTripletsWithZeroSum.js ├── Finding3DigitEvenNumbers.js ├── FirstAndLastOccurencesOfX.js ├── FirstBadVersion.java ├── FirstBadVersion.js ├── FirstMissingPositive.java ├── FirstUniqueCharacterInAString.java ├── FirstUniqueCharacterInAString.js ├── FlatteningALinkedList.java ├── FlatteningALinkedList.js ├── FloodFill.java ├── FloodFill.js ├── GasStation.js ├── GenerateBinaryNumbersFrom1ToN.js ├── GenerateParenthesis.java ├── GenerateParenthesis.js ├── GetMaximumInGeneratedArray.java ├── GivenALinkedListOf0s1s2sSortIt.js ├── GreatestCommonDivisorOfStrings.js ├── GroupAnagrams.java ├── GroupAnagrams.js ├── GuessNumberHigherOrLower.js ├── HappyNumber.java ├── HappyNumber.js ├── HouseRobber.java ├── HouseRobber.js ├── HouseRobberII.java ├── ImplementAtoiGFG.js ├── ImplementQueueUsingLinkedList.js ├── ImplementStrStr.js ├── ImplementstrStr.java ├── IncreasingTripletSubsequence.java ├── InsertInterval.js ├── InsertIntoABinarySearchTree.js ├── IntegerToEnglishWords.java ├── IntegerToRoman.java ├── IntersectionOfTwoArrays.java ├── IntersectionOfTwoArraysII.java ├── IntersectionOfTwoArraysII.js ├── IntersectionOfTwoLinkedLists.java ├── IntersectionOfTwoLinkedLists.js ├── IntersectionPointInYShapedLinkedLists.js ├── InvertBinaryTree.java ├── InvertBinaryTree.js ├── IsSubsequence.java ├── IsSubsequence.js ├── IsomorphicStrings.java ├── IsomorphicStrings.js ├── JumpGame.java ├── JumpGame.js ├── JumpGameII.java ├── JumpGameII.js ├── KidsWithTheGreatestNumberOfCandies.js ├── KthLargestElement.js ├── KthMissingPositiveNumber.js ├── KthSmallestElement.js ├── KthSmallestElementInABST.java ├── KthSmallestElementInABST.js ├── LargestNumber.js ├── LargestNumberFormedFromAnArray.js ├── LargestPerimeterTriangle.java ├── LargestPositiveIntegerThatExistsWithItsNegative.java ├── LargestSubarrayWith0Sum.js ├── LastStoneWeight.js ├── LeftViewOfBinaryTree.java ├── LengthOfLastWord.js ├── LengthOfLongestSubarrayWithAtMostKFrequency.js ├── LengthOfTheLongestAlphabeticalContinuousSubstring.java ├── LetterCombinationsOfAPhoneNumber.js ├── LinkedListCycle.java ├── LinkedListCycle.js ├── LinkedListCycleII.java ├── LinkedListCycleII.js ├── LongestCommonPrefix.java ├── LongestCommonPrefix.js ├── LongestCommonPrefixInAnArray.js ├── LongestCommonSubsequence.java ├── LongestConsecutiveSequence.java ├── LongestConsecutiveSequence.js ├── LongestHappyPrefix.js ├── LongestIncreasingSubsequence.java ├── LongestIncreasingSubsequence.js ├── LongestKUniqueCharactersSubstring.js ├── LongestPalindrome.java ├── LongestPalindrome.js ├── LongestPalindromicSubstring.java ├── LongestPalindromicSubstring.js ├── LongestSubArrayHavingSumK.java ├── LongestSubstringWithoutRepeatingCharacters.java ├── LongestSubstringWithoutRepeatingCharacters.js ├── LowestCommonAncestorOfABinarySearchTree.js ├── LowestCommonAncestorOfABinaryTree.js ├── LuckyNumbersInAMatrix.js ├── MajorityElement.java ├── MajorityElement.js ├── MajorityElementII.js ├── MakeTheStringGreat.js ├── MakeTwoArraysEqualByReversingSubarrays.js ├── MaxAreaOfIsland.java ├── MaxAreaOfIsland.js ├── MaxConsecutiveOnes.java ├── MaxDepthOfABinaryTree.java ├── MaxDepthOfBinaryTree.js ├── MaxPointsOnALine.js ├── MaxSumInTheConfiguration.js ├── MaximalSquare.js ├── MaximumHeightOfATriangle.js ├── MaximumIceCreamBars.js ├── MaximumLengthOfRepeatedSubarray.java ├── MaximumNestingDepthOfTheParentheses.js ├── MaximumProductSubarray.js ├── MaximumSubarray.java ├── MaximumSubarray.js ├── MaximumSumCircularSubarray.js ├── MaximumSumOfDistinctSubarraysWithLengthK.java ├── MedianOfTwoSortedArrays.java ├── MergeIntervals.java ├── MergeIntervals.js ├── MergeKSortedLists.java ├── MergeKSortedLists.js ├── MergeSort.js ├── MergeSortForLinkedList.js ├── MergeSortedArray.java ├── MergeSortedArray.js ├── MergeStringsAlternatively.js ├── MergeTwoSorted Lists.java ├── MiddleOfTheLinkedList.java ├── MinCostClimbingStairs.java ├── MinimumAbsoluteDifferenceInBST.js ├── MinimumDepthOfBinaryTree.java ├── MinimumDistanceBetweenBSTNodes.js ├── MinimumElementInASortedAndRotatedArray.js ├── MinimumNumberOfSwapsToMakeTheStringBalanced.js ├── MinimumOperations.js ├── MinimumPlatforms.js ├── MinimumRemoveToMakeValidParenthesis.js ├── MinimumSizeSubarraySum.js ├── MinimumWindowSubstring.java ├── MirrorTree.java ├── MissingNumberInArray.js ├── MostFrequentEvenElement.java ├── MoveAllNegativeElementsToEnd.js ├── MoveZeroes.java ├── MoveZeroes.js ├── NQueens.java ├── NaryTreePreOrderTraversal.java ├── NextGreaterElementI.java ├── NextGreaterElementI.js ├── NextGreaterElementII.js ├── NextGreaterNodeInLinkedList.java ├── NextPermutation.java ├── NextPermutation.js ├── NonRepeatingNummbers.js ├── NthTribonacciNumber.java ├── NthTribonacciNumber.js ├── NumberOfIslands.java ├── NumberOfIslands.js ├── NumberOfSubarraysWithGCDEqualToK.java ├── NumberOfZeroFilledSubarrays.js ├── OddEvenLinkedList.java ├── OddEvenLinkedList.js ├── OptimalPartitionOfString.java ├── PairwiseSwapElementsOfALinkedList.js ├── PalindromeLinkedList.java ├── PalindromeLinkedList.js ├── PalindromeNumber.java ├── PalindromePartitioning.js ├── PalindromePermutation.js ├── PalindromicArray.js ├── PalindromicSubstrings.js ├── PangramChecking.js ├── PartitionList.java ├── PascalsTriangle.java ├── PascalsTriangle.js ├── PascalsTriangleII.java ├── PassThePillow.js ├── PathSum.java ├── PeakIndexInAMountainArray.js ├── PermutationInString.js ├── Permutations.js ├── PermutationsOfAGivenString.js ├── PlusOne.java ├── PlusOne.js ├── PopulatingNextRightPointersInEachNode.js ├── PowXN.java ├── PowXN.js ├── PowerOfFour.java ├── PowerOfThree.java ├── PowerOfTwo.java ├── PrintBSTElementsInGivenRange.js ├── ProductOfArrayExceptSelf.java ├── ProductOfArrayExceptSelf.js ├── PythagoreanTriplet.js ├── PythagoreanTripletInAnArray.java ├── README.md ├── RansomNote.java ├── RansomNote.js ├── RearrangeArrayAlternatively.js ├── RearrangeSortedArrayInMaxMinAlternativeForm.js ├── RecursivelyRemoveAllAdjacentDuplicates.js ├── RegularExpressionMatching.java ├── RemoveAllAdjacentDuplicatesInString.js ├── RemoveAllDuplicatesFromAGivenString.js ├── RemoveDuplicatesFromSortedArrayII.js ├── RemoveDuplicatesFromSortedList.java ├── RemoveDuplicatesFromSortedList.js ├── RemoveDuplicatesfromSortedArray.js ├── RemoveDuplicatesfromSortedListII.js ├── RemoveElement.java ├── RemoveElement.js ├── RemoveLoopInLinkedList.js ├── RemoveNthNodeFromEndOfList.java ├── RemoveNthNodeFromEndOfList.js ├── RemoveOutermostParentheses.java ├── ReorderList.js ├── ReshapeTheMatrix.js ├── RevealCardsInIncreasingOrder.js ├── ReverseArrayInGroups.js ├── ReverseInteger.java ├── ReverseLinkedList.java ├── ReverseLinkedList.js ├── ReverseLinkedListII.java ├── ReverseLinkedListII.js ├── ReverseNodesInKGroup.java ├── ReverseNodesInKGroup.js ├── ReverseOddLevelsOfBinaryTree.java ├── ReverseString.java ├── ReverseString.js ├── ReverseWordsInAGivenString.js ├── ReverseWordsInAString.java ├── RomanToInteger.java ├── RotateArray.java ├── RotateArray.js ├── RotateImage.java ├── RotateImage.js ├── RotateList.java ├── RotateList.js ├── RotateListGFG.js ├── RotateString.js ├── RowWithMax1s.js ├── RunningSumof1dArray.java ├── SameTree.java ├── SameTree.js ├── SearchA2DMatrix.java ├── SearchA2DMatrixII.java ├── SearchInABinarySearchTree.js ├── SearchInRotatedSortedArray.java ├── SearchInRotatedSortedArray.js ├── SearchInsertPosition.java ├── SearchInsertPosition.js ├── SetMatrixZeroes.java ├── SetMatrixZeroes.js ├── ShuffleTheArray.js ├── SingleElementInASortedArray.js ├── SingleNumber.java ├── Sleep.js ├── SlidingWindowMaximum.java ├── SmallestEvenMultiple.java ├── SmallestNumberInInfiniteSet.js ├── SortAnArray.js ├── SortAnArrayOf0s1sAnd2s.js ├── SortColors.js ├── SortList.js ├── SpecialArrayWithXElementsGreaterThanOrEqualX.js ├── SpecialStack.java ├── SpiralMatrix.java ├── SpiralMatrix.js ├── SpiralMatrixII.js ├── SqrtX.js ├── SquaresOfASortedArray.java ├── StringToIntegeratoi.java ├── StringToIntegeratoi.js ├── SubarraySumEqualsK.java ├── SubarraySumEqualsK.js ├── SubarrayWith0Sum.js ├── SubarrayWithGivenSum.js ├── SubarraysWithEqual1sAnd0s.js ├── Subsets.java ├── Subsets.js ├── SubsetsII.js ├── SubtreeOfAnotherTree.js ├── SumOfEvenNumbersAfterQueries.java ├── SumOfNumberAndItsReverse.java ├── SumOfTreeValues.js ├── SumRootToLeafNumbers.js ├── SummaryRanges.java ├── SwapNodesInPairs.java ├── SwapNodesInPairs.js ├── SymmetricTree.java ├── SymmetricTree.js ├── TakingInputFromConsoleJS.js ├── TheNumberOfWeakCharactersInTheGame.java ├── ThreeConsecutiveOdds.js ├── ThreeWayPartitioning.js ├── ToeplitzMatrix.java ├── TopKFrequentElements.js ├── TrappingRainWater.java ├── TrappingRainWater.js ├── TripletSumInArray.js ├── TwoSum.java ├── TwoSumII_InputArrayIsSorted.js ├── TwoSumIV_InputIsABST.java ├── UnionOfTwoArrays.js ├── UniqueMorseCodeWords.java ├── UniquePaths.java ├── UniquePaths.js ├── ValidAnagram.java ├── ValidAnagram.js ├── ValidPalindrome.java ├── ValidPalindrome.js ├── ValidPalindromeII.java ├── ValidParentheses.java ├── ValidParentheses.js ├── ValidPerfectSquare.js ├── ValidSudoku.java ├── ValidSudoku.js ├── ValidateAnIPAddressGFG.js ├── ValidateBinarySearchTree.java ├── ValidateBinarySearchTree.js ├── ValueEqualToIndexValue.js ├── WaveArray.js ├── WaysToSwap2Integers.js ├── WordPattern.js ├── WordSearch.java ├── WordSearch.js ├── WordSubsets.java └── ZigzagConversion.js /0-1KnapsackProblem.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to return max value that can be put in knapsack of capacity W. 4 | static int knapSack(int totalWeights, int weights[], int values[], int n) 5 | { 6 | // your code here 7 | 8 | // Creating A 2D Array For Storing The Results 9 | int[][] dp = new int[values.length + 1][totalWeights + 1]; 10 | 11 | for(int i=1; i= wt[i - 1]){ 22 | dp[i][j] = Math.max(dp[i-1][j - wt[i - 1]] + val[i - 1], dp[i - 1][j]); 23 | } 24 | else { 25 | dp[i][j] = dp[i - 1][j]; 26 | } 27 | } 28 | } 29 | return dp[dp.length - 1][dp[0].length - 1]; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /AddToArrayFormOfInteger.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} num 3 | * @param {number} k 4 | * @return {number[]} 5 | */ 6 | var addToArrayForm = function(num, k) { 7 | return String(BigInt(num.join('')) + BigInt(k)).split(''); 8 | }; 9 | -------------------------------------------------------------------------------- /AlternatePositiveAndNegativeNumbers.js: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | rearrange(arr,n){ 3 | //code here 4 | if(arr.length === 2) { 5 | if(arr[0] < 0) { 6 | return [arr[1], arr[0]]; 7 | } 8 | else return arr; 9 | } 10 | let result = []; 11 | let positiveIndex = 0; 12 | let negativeIndex = 1; 13 | arr.forEach((num) => { 14 | 15 | 16 | if(num >= 0) { 17 | result[positiveIndex] = num; 18 | positiveIndex += 2; 19 | } 20 | else { 21 | result[negativeIndex] = num; 22 | negativeIndex += 2; 23 | } 24 | 25 | 26 | }); 27 | 28 | result = result.filter((num) => num !== undefined); 29 | 30 | return result; 31 | 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ApplyOperationsToAnArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] applyOperations(int[] nums) { 3 | for(int i=0; i { 14 | map.has(num) ? map.set(num, map.get(num) + 1) : map.set(num, 1); 15 | }); 16 | for(let num of a2) { 17 | if(map.has(num)) { 18 | if(map.get(num) === 1) map.delete(num); 19 | else map.set(num, map.get(num) - 1); 20 | } 21 | else return 'No'; 22 | } 23 | return 'Yes'; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStock.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} prices 3 | * @return {number} 4 | */ 5 | var maxProfit = function(prices) { 6 | let lowestPrice = prices[0]; 7 | let maxProfit = 0; 8 | prices.forEach((currentPrice, i) => { 9 | if(lowestPrice > currentPrice) { 10 | lowestPrice = currentPrice; 11 | } 12 | else { 13 | maxProfit = Math.max(maxProfit, currentPrice - lowestPrice); 14 | } 15 | }); 16 | return maxProfit; 17 | }; 18 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStockII.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} prices 3 | * @return {number} 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var maxProfit = function(prices) { 7 | let profit = 0; // Initialize total profit to zero 8 | 9 | // Loop through prices starting from the second day 10 | for (let i = 1; i < prices.length; i++) { 11 | 12 | // If today's price is higher than yesterday's, we can make a profit 13 | if (prices[i] > prices[i - 1]) { 14 | 15 | // Add the profit from buying yesterday and selling today 16 | profit += prices[i] - prices[i - 1]; 17 | } 18 | } 19 | 20 | // Return the accumulated profit 21 | return profit; 22 | }; 23 | -------------------------------------------------------------------------------- /BestTimetoBuyandSellStock.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 2 ms, faster than 93.61% of Java online submissions for Best Time to Buy and Sell Stock. 3 | Memory Usage: 84 MB, less than 34.66% of Java online submissions for Best Time to Buy and Sell Stock. 4 | */ 5 | // TC: O(n) SC: O(1) 6 | class Solution { 7 | public int maxProfit(int[] prices) { 8 | 9 | // Declaring And Initialising Variables To Store Result And Minimum Value Of Prices 10 | int maxProfit = 0; 11 | int minimumValue = Integer.MAX_VALUE; 12 | 13 | // Loop To Store Minimum Price In currentValue & Calculating Profit With Every Element Greater Than currentValue 14 | for(int price : prices){ 15 | 16 | if(price < minimumValue){ 17 | minimumValue = price; 18 | }else{ 19 | // Calculating The Max Profit 20 | maxProfit = Math.max(maxProfit, (price - minimumValue)); 21 | } 22 | 23 | } 24 | 25 | //Returning The Final Result 26 | return maxProfit; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /BinarySearch.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int index = Arrays.binarySearch(nums, target); 4 | if(index <0){ ////This condition becomes necessary because the library function at times returns values >-1 5 | index = -1; 6 | } 7 | return index; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /BinarySearch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | 7 | var search = function(nums, target) { 8 | let start = 0, end = nums.length; 9 | while(start < end){ 10 | const mid = start + Math.floor((end - start) / 2); 11 | if(nums[mid] === target) { 12 | return mid; 13 | } 14 | else if( nums[mid] < target) { 15 | start = mid + 1; 16 | } 17 | else { 18 | end = mid; 19 | } 20 | } 21 | return -1; 22 | }; 23 | -------------------------------------------------------------------------------- /BinaryTreeInorderTraversal.java: -------------------------------------------------------------------------------- 1 | 2 | // Time Complexity O(n) Space Complexity O(n) 3 | class Solution { 4 | public List inorderTraversal(TreeNode root) { 5 | 6 | // Storing Result In A List 7 | List treeList = new LinkedList<>(); 8 | 9 | // Calling In Order Function 10 | inorder(treeList, root); 11 | 12 | // Returning Final Result 13 | return treeList; 14 | 15 | } 16 | 17 | // Inorder Function 18 | public void inorder(List list, TreeNode root){ 19 | 20 | // In case The Root Is Null We Stop The Recursive Call 21 | // This Is The Base Condition 22 | if(root == null){ 23 | return; 24 | } 25 | 26 | // We Traverse Through All The Left Nodes First 27 | inorder(list, root.left); 28 | 29 | // Then We Add The Values 30 | list.add(root.val); 31 | 32 | // And Finally We Traverse The Right Nodes Of The Tree. 33 | inorder(list, root.right); 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /BinaryTreeInorderTraversal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {TreeNode} root 3 | * @return {number[]} 4 | */ 5 | // TC: O(N) SC: O(N) Recursion 6 | const traversal = (root) => { 7 | if(!root) return []; 8 | 9 | const node = root; 10 | const result = []; 11 | 12 | const inorder = (root) => { 13 | if(!root) return; 14 | if(root.left) inorder(root.left); 15 | result.push(root.val); 16 | if(root.right) inorder(root.right); 17 | } 18 | inorder(node); 19 | return result; 20 | } 21 | 22 | var inorderTraversal = function(root) { 23 | return traversal(root); 24 | }; 25 | 26 | 27 | 28 | //TC: O(N) SC: O(N) Iteration 29 | var inorderTraversal = function(root) { 30 | const result = []; 31 | const stack = []; 32 | let current = root; 33 | while(current || stack.length > 0) { 34 | while(current) { 35 | stack.push(current); 36 | current = current.left; 37 | } 38 | current = stack.pop(); 39 | result.push(current.val); 40 | current = current.right; 41 | } 42 | return result; 43 | }; 44 | -------------------------------------------------------------------------------- /BinaryTreeMaximumPathSum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {number} 12 | */ 13 | var maxPathSum = function(root) { 14 | let result = -Infinity; 15 | const dfs = (node) => { 16 | if(!node) return 0; 17 | const left = dfs(node.left); 18 | const right = dfs(node.right); 19 | result = Math.max(left + right + node.val, result); 20 | return Math.max(0, node.val + left, node.val + right); 21 | } 22 | dfs(root); 23 | return result; 24 | }; 25 | -------------------------------------------------------------------------------- /BinaryTreeZigzagLevelOrderTraversal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {number[][]} 12 | */ 13 | var zigzagLevelOrder = function(root) { 14 | if(!root) return []; 15 | const result = []; 16 | const queue = [root]; 17 | let direction = true; 18 | while(queue.length !== 0) { 19 | const list = []; 20 | const size = queue.length; 21 | 22 | for(let i=0; i 1) { 12 | return false; 13 | } 14 | else { 15 | return flowerbed[0] === 0 ? true : false; 16 | } 17 | } 18 | for(let i=0; i { 8 | let daysNeeded = 1; 9 | let currentLoad = 0; 10 | weights.forEach((weight) => { 11 | currentLoad += weight; 12 | if(currentLoad > capacity) { 13 | currentLoad = weight; 14 | daysNeeded++; 15 | } 16 | }); 17 | return daysNeeded <= days; 18 | } 19 | 20 | var shipWithinDays = function(weights, days) { 21 | let maxWeight = 0; 22 | const totalWeights = weights.reduce((acc, curr) => { 23 | maxWeight = Math.max(maxWeight, curr); 24 | return acc + curr; 25 | }, 0); 26 | let start = maxWeight; 27 | let end = totalWeights; 28 | while(start <= end) { 29 | const mid = start + Math.floor((end - start) / 2); 30 | if(findOptimalWeight(weights, mid, days)) end = mid - 1; 31 | else start = mid + 1; 32 | } 33 | return start; 34 | }; 35 | -------------------------------------------------------------------------------- /CheckForBST.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Node} root 3 | * @returns {boolean} 4 | */ 5 | 6 | 7 | 8 | // Brute Force Inorder Traversal 9 | class Solution 10 | { 11 | //Function to check whether a Binary Tree is BST or not. 12 | isBST(root) 13 | { 14 | //your code here 15 | let currentValue, previousValue, flag = true; 16 | const inorder = (root) => { 17 | 18 | if(!root) return; 19 | 20 | if(root.left) inorder(root.left); 21 | 22 | if(currentValue !== undefined) { 23 | previousValue = currentValue; 24 | currentValue = root.data; 25 | if(currentValue < previousValue) flag = false; 26 | } 27 | else { 28 | currentValue = root.data; 29 | } 30 | 31 | if(root.right) inorder(root.right); 32 | 33 | } 34 | 35 | inorder(root); 36 | return flag; 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /CheckIfArrayIsSortedAndRotated.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var check = function(nums) { 6 | let occurance = 0; 7 | for(let i=0; i nums[i + 1]) occurance++; 9 | } 10 | nums[0] < nums[nums.length - 1] && occurance++; 11 | return occurance < 2 ? true : false; 12 | }; 13 | -------------------------------------------------------------------------------- /CheckIfLinkedListIsPalindrome.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //Function to check whether the list is palindrome. 3 | reverse(head) { 4 | let previousNode = null; 5 | while(head) { 6 | const nextNode = head.next; 7 | head.next = previousNode; 8 | previousNode = head; 9 | head = nextNode; 10 | } 11 | return previousNode; 12 | } 13 | 14 | isPalindrome(head) 15 | { 16 | //your code here 17 | let traverseNode = head; 18 | let fastNode = head; 19 | while(fastNode && fastNode.next) { 20 | traverseNode = traverseNode.next; 21 | fastNode = fastNode.next.next; 22 | } 23 | let reverseNode = this.reverse(traverseNode); 24 | traverseNode = head; 25 | while(reverseNode) { 26 | if(reverseNode.data !== traverseNode.data) return false; 27 | reverseNode = reverseNode.next; 28 | traverseNode = traverseNode.next; 29 | } 30 | return true; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /CheckIfObjectInstanceOfClass.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {any} object 3 | * @param {any} classFunction 4 | * @return {boolean} 5 | */ 6 | var checkIfInstanceOf = function(obj, classFunction) { 7 | if(obj === null || classFunction === null 8 | || obj === undefined || classFunction === undefined 9 | || typeof classFunction !== 'function') { 10 | return false; 11 | } 12 | return Object(obj) instanceof classFunction; 13 | }; 14 | 15 | /** 16 | * checkIfInstanceOf(new Date(), Date); // true 17 | */ 18 | -------------------------------------------------------------------------------- /CheckIfStringsAreRotationsOfEachOtherOrNot.js: -------------------------------------------------------------------------------- 1 | //User function Template for javascript 2 | /** 3 | * @param {string} s1 4 | * @param {string} s2 5 | * @returns {boolean} 6 | */ 7 | 8 | class Solution 9 | { 10 | //Function to check if two strings are rotations of each other or not. 11 | areRotations(s1, s2) 12 | { 13 | // code here 14 | const str = s1 + s1; 15 | return str.includes(s2) && s2.length * 2 === str.length; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /CheckIfTheSentenceIsPangram.java: -------------------------------------------------------------------------------- 1 | // Approach 1: TC: O(N) SC: O(N) 2 | class Solution { 3 | public boolean checkIfPangram(String sentence) { 4 | 5 | int[] charCount = new int[26]; 6 | 7 | for(char c : sentence.toCharArray()){ 8 | charCount[c - 'a']++; 9 | } 10 | 11 | for(int frequency : charCount){ 12 | if(frequency == 0){ 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | 19 | } 20 | } 21 | 22 | // Approach 2: One Loop TC: O(N) SC: O(N) 23 | class Solution { 24 | public boolean checkIfPangram(String sentence) { 25 | HashSet set = new HashSet<>(); 26 | for( char c : sentence.toCharArray()){ 27 | set.add(c); 28 | } 29 | 30 | if(set.size() == 26){ 31 | return true; 32 | }else{ 33 | return false; 34 | } 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /CheckIfTwoStringArraysAreEquivalent.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean arrayStringsAreEqual(String[] word1, String[] word2) { 3 | String str1 = ""; 4 | String str2 = ""; 5 | for(String s : word1){ 6 | str1 += s; 7 | } 8 | for(String s : word2){ 9 | str2 += s; 10 | } 11 | return str1.equals(str2); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ChocolateDistributionProblem.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @param {number} m 5 | * @returns {number} 6 | */ 7 | // TC: o(NlogN) SC: O(1) 8 | class Solution{ 9 | findMinDiff(arr,n,m){ 10 | //code here 11 | arr.sort((a,b) => a - b); 12 | 13 | if(arr.length === m) return arr[arr.length - 1] - arr[0]; 14 | let iStart = 0; 15 | let max = Infinity; 16 | 17 | for(let i=0; i { 9 | if(sum === target) { 10 | result.push([...store]); 11 | return; 12 | } 13 | if(sum > target) return; 14 | for(let i=start; i a - b); 9 | const backtrack = (currentIdx, store, sum) => { 10 | if(sum === target) { 11 | result.push([...store]); 12 | return; 13 | } 14 | if(sum > target) return; 15 | for(let i=currentIdx; i set = new HashSet<>(); 4 | for(int i=0; i map = new HashMap<>(); 5 | 6 | map.put(0,0); 7 | 8 | int sum = 0; 9 | 10 | for(int i=0; i set = new HashSet<>(); 5 | 6 | for(int num : nums){ 7 | set.add(num); 8 | } 9 | 10 | for(int num : nums){ 11 | StringBuilder str = new StringBuilder(); 12 | str.append(num + ""); 13 | str.reverse(); 14 | set.add(Integer.parseInt(str.toString())); 15 | } 16 | 17 | return set.size(); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CountOddNumbersInAnIntervalRange.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} low 3 | * @param {number} high 4 | * @return {number} 5 | */ 6 | // Approach 1 7 | var countOdds = function(low, high) { 8 | low = low % 2 === 0 ? low + 1 : low; 9 | high = high % 2 === 0 ? high -1 : high; 10 | return low > high ? 0 : Math.floor((high - low) / 2) + 1; 11 | }; 12 | 13 | // Approach 2 14 | var countOdds = function(low, high) { 15 | return Math.floor((high - low)/2) + (low%2 || high%2 ? 1 : 0); 16 | }; 17 | -------------------------------------------------------------------------------- /CountPairsWithGivenSum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @param {number} k 5 | * @return {number} 6 | */ 7 | 8 | class Solution { 9 | getPairsCount(arr,n,k){ 10 | //code here 11 | const map = new Map(); 12 | let count = 0; 13 | arr.forEach((num) => { 14 | if(map.has(k - num)) count+= map.get(k - num); 15 | map.has(num) ? map.set(num, map.get(num) + 1) : map.set(num, 1); 16 | }); 17 | return count; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CountTheTriplets.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @return {number} 5 | */ 6 | 7 | class Solution { 8 | 9 | countTriplet(nums,n){ 10 | //code here 11 | const set = new Set(nums); 12 | let count = 0; 13 | nums.forEach((num, index)=> { 14 | if(index < nums.length - 1) 15 | for(let i=index + 1; i 0) { 10 | if(s[i] === s[i-1]) count++; 11 | else count = 1; 12 | } 13 | if(count < 3) { 14 | result += s[i]; 15 | } 16 | } 17 | return result; 18 | }; 19 | -------------------------------------------------------------------------------- /DeleteColumnsToMakeSorted.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} strs 3 | * @return {number} 4 | */ 5 | var minDeletionSize = function(strs) { 6 | if(strs.length === 1) return 0; 7 | let count = 0; 8 | const set = new Set(); 9 | for(let i=1; i= 65 && word[0].charCodeAt(0) <= 90){ 8 | if(word[1].charCodeAt(0) >= 65 && word[1].charCodeAt(0) <= 90){ 9 | for(let i=2; i= 65 && word[i].charCodeAt(0) <= 90) continue; 11 | else return false; 12 | } 13 | }else if(word[1].charCodeAt(0) >= 97 && word[1].charCodeAt(0) <= 122){ 14 | for(let i=2; i= 65 && word[i].charCodeAt(0) <= 90) return false; 16 | else continue; 17 | } 18 | } 19 | }else if(word[0].charCodeAt(0) >= 97 && word[0].charCodeAt(0) <= 122){ 20 | for(let i=1; i= 65 && word[i].charCodeAt(0) <= 90) return false; 22 | else continue; 23 | } 24 | } 25 | return true; 26 | }; 27 | -------------------------------------------------------------------------------- /DiameterOfBinaryTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {number} 12 | */ 13 | 14 | var diameterOfBinaryTree = function(root) { 15 | let result = 0; 16 | const dfs = (node) => { 17 | if(!node) return 0; 18 | const left = dfs(node.left); 19 | const right = dfs(node.right); 20 | result = Math.max(left + right, result); 21 | return Math.max(left, right) + 1; 22 | } 23 | dfs(root); 24 | return result; 25 | }; 26 | -------------------------------------------------------------------------------- /DivideTwoIntegers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} dividend 3 | * @param {number} divisor 4 | * @return {number} 5 | */ 6 | var divide = function(dividend, divisor) { 7 | 8 | let value = dividend / divisor; 9 | if(value < 0){ 10 | if(value <= -2147483648){ 11 | value = -2147483648; 12 | }else{ 13 | value = Math.ceil(value); 14 | } 15 | }else{ 16 | if(value >= 2147483647){ 17 | value = 2147483647; 18 | } 19 | else{ 20 | value = Math.floor(value); 21 | } 22 | } 23 | 24 | return value; 25 | }; 26 | -------------------------------------------------------------------------------- /DivisorGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 0 ms, faster than 100.00% of Java online submissions for Divisor Game. 3 | Memory Usage: 38.7 MB, less than 99.07% of Java online submissions for Divisor Game. 4 | */ 5 | // TC: O(1) SC: O(1) 6 | class Solution { 7 | public boolean divisorGame(int n) { 8 | return n % 2 == 0; 9 | } 10 | } 11 | 12 | 13 | /* 14 | Runtime: 0 ms, faster than 100.00% of Java online submissions for Divisor Game. 15 | Memory Usage: 38.8 MB, less than 94.89% of Java online submissions for Divisor Game. 16 | */ 17 | // TC: O(1) SC: O(1) 18 | class Solution { 19 | public boolean divisorGame(int N) { 20 | return (N & 1) == 0; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ExcelSheetColumnTitle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} columnNumber 3 | * @return {string} 4 | */ 5 | var convertToTitle = function(columnNumber) { 6 | let result = ''; 7 | while(columnNumber > 0) { 8 | columnNumber--; 9 | const charCode = columnNumber % 26; 10 | result = String.fromCharCode(charCode + 65) + result; 11 | columnNumber = (columnNumber - charCode) / 26; 12 | } 13 | return result; 14 | }; 15 | -------------------------------------------------------------------------------- /FactorialsOfLargeNumbers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} N 3 | * @return {number[]} 4 | */ 5 | 6 | class Solution { 7 | factorial(N){ 8 | //code here 9 | let fact = 1n; 10 | while(N > 0) { 11 | fact *= BigInt(N); 12 | N--; 13 | } 14 | const result = `${fact}`.split(''); 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number. 3 | Memory Usage: 41.1 MB, less than 32.82% of Java online submissions for Fibonacci Number. 4 | */ 5 | class Solution { 6 | public int fib(int n) { 7 | 8 | if(n == 0){ 9 | return 0; 10 | } 11 | if(n == 1){ 12 | return 1; 13 | } 14 | 15 | int[] dp = new int[n+1]; 16 | dp[0] = 0; 17 | dp[1] = 1; 18 | 19 | for(int i=2; i<=n; i++){ 20 | dp[i] = dp[i-1] + dp[i-2]; 21 | } 22 | 23 | return dp[n]; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /FibonacciNumber.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number} 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var fib = function(n) { 7 | if(n === 0) return n; 8 | if(n === 1 || n === 2) return 1; 9 | let first = 1, second = 1, result = 1; 10 | for(let i=3; i<=n; i++) { 11 | result = first + second; 12 | first = second; 13 | second = result; 14 | } 15 | return result; 16 | }; 17 | 18 | // TC: O(N) SC: O(N) 19 | var fib = function(n) { 20 | if(n === 0) return 0; 21 | if(n === 1 || n === 2) return 1; 22 | const dp = [0, 1, 1]; 23 | for(let i=3; i<=n; i++) { 24 | dp[i] = dp[i - 1] + dp[i - 2]; 25 | } 26 | return dp.pop(); 27 | 28 | }; 29 | 30 | 31 | // TC: O(2^N) SC: O(N) 32 | var fib = function(n) { 33 | if(n === 0) return 0; 34 | if(n === 1 || n === 2) return 1; 35 | return fib(n - 1) + fib(n - 2); 36 | }; 37 | -------------------------------------------------------------------------------- /FindAllDuplicatesInAnArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | var findDuplicates = function(nums) { 6 | const result = []; 7 | for(let i=0; i 0 && result[result.length - 1] === arr1[i]) { 20 | i++; 21 | j++; 22 | k++; 23 | continue; 24 | } 25 | result.push(arr1[i]); 26 | i++; 27 | j++; 28 | k++; 29 | } 30 | else if(arr1[i] < arr2[j]) i++; 31 | else if(arr2[j] < arr3[k]) j++; 32 | else k++; 33 | } 34 | 35 | return result; 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /FindKClosestElements.java: -------------------------------------------------------------------------------- 1 | // Optimized Solution TC: O(N) SC: O(1) 2 | class Solution { 3 | public List findClosestElements(int[] arr, int k, int x) { 4 | 5 | // For Storing Data 6 | List result = new ArrayList<>(); 7 | 8 | // 2 Pointers, start At Beginning, end At The End 9 | int start = 0; 10 | int end = arr.length - 1; 11 | 12 | // Traversing Till The Pointers Reach A Window Of Length k 13 | while(end - start >= k){ 14 | 15 | // start++ if element at start index is closer, else end++; 16 | if(Math.abs(arr[start] - x) > Math.abs(arr[end] - x)){ 17 | start++; 18 | } 19 | else{ 20 | end--; 21 | } 22 | 23 | } 24 | 25 | // Filling The Result Array With Data In Between The Pointers Including The Data At The Pointers 26 | for(int i=start; i<=end; i++){ 27 | result.add(arr[i]); 28 | } 29 | 30 | // Returning The Result 31 | return result; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /FindKthSmallestElements.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] kLargest(int[] arr, int n, int k) { 3 | // code here 4 | Arrays.sort(arr); 5 | int[] res = new int[k]; 6 | n=n-1; 7 | for(int i=0; i { 27 | 28 | if(this.compareWord(word, s)) result = result.length < word.length ? word : result; 29 | 30 | }); 31 | 32 | return result; 33 | 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /FindMiddleElementInALinkedList.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /* Should return data of middle node. If linked list is empty, then -1*/ 3 | getMiddle(head) 4 | { 5 | //your code here 6 | let traverseNode = head; 7 | let fastNode = head; 8 | while(fastNode && fastNode.next) { 9 | fastNode = fastNode.next.next; 10 | traverseNode = traverseNode.next; 11 | } 12 | return traverseNode.data; 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /FindMinimumInRotatedSortedArray.js: -------------------------------------------------------------------------------- 1 | //TC: O(logn) SC: O(1) 2 | var findMin = function(nums) { 3 | let start = 0, end = nums.length - 1; // Initialize search range 4 | 5 | while(start < end) { 6 | const mid = Math.floor(start + (end - start) / 2); // Calculate middle index 7 | 8 | // If the middle element is greater than the rightmost, the pivot is to the right 9 | if(nums[mid] > nums[end]) start = mid + 1; 10 | 11 | // Otherwise, the pivot is to the left (or the subarray is sorted) 12 | else end = mid; 13 | } 14 | 15 | return nums[start]; // Return the minimum element (when start == end) 16 | }; 17 | -------------------------------------------------------------------------------- /FindPivotIndex.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int pivotIndex(int[] nums) { 3 | int rightSum = 0; 4 | for (int i=0; i haystack.length) return -1; 10 | 11 | for(let i=0; i<=haystack.length - needle.length; i++) { 12 | if(haystack.slice(i, i + needle.length) === needle) { 13 | return i; 14 | } 15 | } 16 | return -1; 17 | }; 18 | -------------------------------------------------------------------------------- /FindTheKthLargestIntegerInTheArray.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | class Solution { 3 | public String kthLargestNumber(String[] nums, int k) { 4 | 5 | BigInteger[] res = new BigInteger[nums.length]; 6 | for(int i=0; i { 9 | 10 | result[people]--; 11 | result[mayor]++; 12 | 13 | }); 14 | 15 | for(let i=1; i a - b); 13 | for(let i=0; i 0 && nums[i] !== nums[i - 1])) { 15 | const target = -nums[i]; 16 | let start = i + 1, end = n - 1; 17 | while(start < end) { 18 | if(nums[start] + nums[end] === target) return true; 19 | else if(nums[start] + nums[end] < target) { 20 | while(start < end && nums[start] === nums[start + 1]) start++; 21 | start++; 22 | } 23 | else { 24 | while(start < end && nums[end] === nums[end - 1]) end--; 25 | end--; 26 | } 27 | } 28 | } 29 | } 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Finding3DigitEvenNumbers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} digits 3 | * @return {number[]} 4 | */ 5 | // TC: O(1) SC: O(N) 6 | var findEvenNumbers = function(digits) { 7 | const freq = new Array(10).fill(0); 8 | const result = []; 9 | digits.forEach((currentNum) => { 10 | freq[currentNum]++; 11 | }); 12 | for(let i=100; i<1000; i+=2) { 13 | const firstDigit = Math.floor(i / 100); 14 | const secondDigit = Math.floor((i / 10) % 10); 15 | const thirdDigit = Math.floor(i % 10); 16 | const currentNum = new Array(10).fill(0); 17 | currentNum[firstDigit]++; 18 | currentNum[secondDigit]++; 19 | currentNum[thirdDigit]++; 20 | let canForm = true; 21 | for(let j=0; j<10; j++) { 22 | if(currentNum[j] > freq[j]) { 23 | canForm = false; 24 | break; 25 | } 26 | } 27 | if(canForm) result.push(i); 28 | } 29 | return result; 30 | }; 31 | -------------------------------------------------------------------------------- /FirstBadVersion.java: -------------------------------------------------------------------------------- 1 | /* The isBadVersion API is defined in the parent class VersionControl. 2 | boolean isBadVersion(int version); */ 3 | 4 | public class Solution extends VersionControl { 5 | public int firstBadVersion(int n) { 6 | int start=1; 7 | int end=n; 8 | int ans=0; 9 | 10 | while(start<=end){ 11 | int mid=(start)+(end-start)/2; 12 | 13 | if(isBadVersion(mid)){ 14 | ans=mid; 15 | end=mid-1; 16 | } 17 | else{ 18 | start=mid+1; 19 | } 20 | } 21 | 22 | return ans; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /FirstBadVersion.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for isBadVersion() 3 | * 4 | * @param {integer} version number 5 | * @return {boolean} whether the version is bad 6 | * isBadVersion = function(version) { 7 | * ... 8 | * }; 9 | */ 10 | 11 | /** 12 | * @param {function} isBadVersion() 13 | * @return {function} 14 | */ 15 | var solution = function(isBadVersion) { 16 | /** 17 | * @param {integer} n Total versions 18 | * @return {integer} The first bad version 19 | */ 20 | return function(n) { 21 | let start = 1, end = n; 22 | while(start <= end) { 23 | const mid = start + Math.floor((end - start) / 2); 24 | const target = isBadVersion(mid); 25 | if(target === false) start = mid + 1; 26 | else end = mid - 1; 27 | } 28 | return start; 29 | }; 30 | }; 31 | -------------------------------------------------------------------------------- /FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | // Optimised Solution TC: O(n) SC: O(1) 2 | class Solution { 3 | public int firstUniqChar(String s) { 4 | int[] charCount = new int[26]; // Constant Space 5 | for(char c : s.toCharArray()){ 6 | charCount[c-'a']++; // Incrementing the value of index of the 26 lowercase characters 7 | } 8 | for(int i=0; i map = new HashMap<>(); 23 | for(char c : s.toCharArray()){ 24 | map.put(c, map.getOrDefault(c,0)+1); 25 | } 26 | for(int i=0; i=image.length || j<0 || j>=image[0].length || image[i][j] != oldColor){ 12 | return; 13 | } 14 | 15 | image[i][j] = newColor; 16 | 17 | floodFill(image, i+1, j, oldColor, newColor); 18 | floodFill(image, i-1, j, oldColor, newColor); 19 | floodFill(image, i, j+1, oldColor, newColor); 20 | floodFill(image, i, j-1, oldColor, newColor); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /FloodFill.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} image 3 | * @param {number} sr 4 | * @param {number} sc 5 | * @param {number} color 6 | * @return {number[][]} 7 | */ 8 | var floodFill = function(image, sr, sc, color) { 9 | if(image[sr][sc] === color) return image; 10 | const flood = (image, sr, sc, originalColor, color) => { 11 | if(sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] !== originalColor) { 12 | return; 13 | } 14 | image[sr][sc] = color; 15 | flood(image, sr + 1, sc, originalColor, color); 16 | flood(image, sr - 1, sc, originalColor, color); 17 | flood(image, sr, sc + 1, originalColor, color); 18 | flood(image, sr, sc - 1, originalColor, color); 19 | } 20 | const originalColor = image[sr][sc]; 21 | flood(image, sr, sc, originalColor, color); 22 | return image; 23 | }; 24 | -------------------------------------------------------------------------------- /GasStation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} gas 3 | * @param {number[]} cost 4 | * @return {number} 5 | */ 6 | var canCompleteCircuit = function(gas, cost) { 7 | let total = 0, avail = 0, index = 0; 8 | for(let i=0; i= 0) ? index : -1; 18 | }; 19 | -------------------------------------------------------------------------------- /GenerateBinaryNumbersFrom1ToN.js: -------------------------------------------------------------------------------- 1 | // Sample Input: n = 3 2 | // Sample Output: ["1","10","11"] 3 | 4 | // Using Queue 5 | "use strict"; 6 | function findBin(number) { 7 | const result = []; 8 | const queue = new Queue(); 9 | queue.enqueue('1'); 10 | for(let i=0; i generateParenthesis(int n) { 4 | List result = new ArrayList<>(); 5 | generateParenthesis(result, "", 0, 0, n); 6 | return result; 7 | } 8 | 9 | void generateParenthesis(List result, String s, int open, int close, int max){ 10 | if(s.length() == max * 2){ 11 | result.add(s); 12 | return; 13 | } 14 | 15 | if(open < max) generateParenthesis(result, s + "(", open + 1, close, max); 16 | if(close < open) generateParenthesis(result, s + ")", open, close + 1, max); 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /GenerateParenthesis.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {string[]} 4 | */ 5 | var generateParenthesis = function(n) { 6 | const result = []; 7 | const createParenthesis = (str, strLength, open, close) => { 8 | if(strLength === n * 2) { 9 | result.push(str); 10 | return; 11 | } 12 | if(open < n) { 13 | createParenthesis(str + '(', strLength + 1, open + 1, close); 14 | } 15 | if(close < open) { 16 | createParenthesis(str + ')', strLength + 1, open, close + 1); 17 | 18 | } 19 | } 20 | createParenthesis('', 0, 0, 0); 21 | return result; 22 | }; 23 | -------------------------------------------------------------------------------- /GreatestCommonDivisorOfStrings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} str1 3 | * @param {string} str2 4 | * @return {string} 5 | */ 6 | 7 | const gcd = (x, y) => { 8 | if(y === 0) return x; 9 | else return gcd(y, x % y); 10 | } 11 | 12 | var gcdOfStrings = function(str1, str2) { 13 | if((str1 + str2) !== (str2 + str1)) { 14 | return ''; 15 | } 16 | const gcdLength = gcd(str1.length, str2.length); 17 | return str1.slice(0, gcdLength); 18 | 19 | }; 20 | -------------------------------------------------------------------------------- /GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> groupAnagrams(String[] strs) { 3 | HashMap map = new HashMap<>(); 4 | for(int i=0; i()); 10 | } 11 | map.get(key).add(strs[i]); 12 | } 13 | return new ArrayList(map.values()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /GuessNumberHigherOrLower.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param {number} num your guess 4 | * @return -1 if num is higher than the picked number 5 | * 1 if num is lower than the picked number 6 | * otherwise return 0 7 | * var guess = function(num) {} 8 | */ 9 | 10 | /** 11 | * @param {number} n 12 | * @return {number} 13 | */ 14 | var guessNumber = function(n) { 15 | let start = 1, end = n; 16 | while(start <= end) { 17 | const mid = start + Math.floor((end - start) / 2); 18 | const result = guess(mid); 19 | 20 | if(result === 0) return mid; 21 | else if (result === 1) start = mid + 1; 22 | else end = mid - 1; 23 | 24 | 25 | } 26 | return -1; 27 | }; 28 | -------------------------------------------------------------------------------- /HappyNumber.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {boolean} 4 | */ 5 | var isHappy = function(n) { 6 | const breakAndSquare = (num) => { 7 | let sum = 0; 8 | while(num >= 1) { 9 | sum += (num % 10) ** 2; 10 | num = Math.floor(num / 10); 11 | } 12 | return sum; 13 | } 14 | const set = new Set(); 15 | while(!set.has(n)) { 16 | if(n === 1) return true; 17 | else{ 18 | set.add(n); 19 | n = breakAndSquare(n); 20 | } 21 | } 22 | return false; 23 | }; 24 | 25 | // Alternate Solution 26 | var isHappy = function(n) { 27 | const breakAndSquare = (num) => [...`${num}`].reduce((acc, curr) => acc + Number(curr % 10) ** 2, 0); 28 | const set = new Set(); 29 | while(!set.has(n)) { 30 | if(n === 1) return true; 31 | set.add(n); 32 | n = breakAndSquare(n); 33 | } 34 | return false; 35 | }; 36 | -------------------------------------------------------------------------------- /HouseRobber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 0 ms, faster than 100.00% of Java online submissions for House Robber. 3 | Memory Usage: 39.5 MB, less than 95.96% of Java online submissions for House Robber. 4 | */ 5 | // Optimized Solution : TC: O(n) SC: O(n) 6 | class Solution { 7 | public int rob(int[] nums) { 8 | 9 | // Standard Dynamic Programming Procedure With An Array Of Size nums.length + 1 10 | int[] dp = new int[nums.length + 1]; 11 | 12 | // Assigning The first 2 elements Of The DP Array 13 | dp[0] = 0; 14 | dp[1] = nums[0]; 15 | 16 | // Calculating The dp Element Value As Per: 17 | // Math.max Of Previous Element Of dp Array And Sum Of Current nums Element + The Last Non Adjacent Element Sum 18 | for(int i=2; i= '0' && s[i] <='9') { 17 | result +=s[i]; 18 | } 19 | else { 20 | return -1; 21 | } 22 | } 23 | if(isNegative) result = +(result) * -1; 24 | else result = +result; 25 | 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ImplementStrStr.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} x 4 | * @returns {number} 5 | */ 6 | 7 | class Solution 8 | { 9 | //Function to locate the occurrence of the string x in the string s. 10 | strstr(s, x) 11 | { 12 | // code here 13 | 14 | if(x.length > s.length) return -1; 15 | 16 | 17 | for(let i=0; i s.length) return -1; 20 | let j = 0; 21 | let index = i; 22 | while(j < x.length) { 23 | if(s[index] !== x[j]) { 24 | break; 25 | 26 | } 27 | else { 28 | j++; 29 | index++; 30 | } 31 | } 32 | if(j === x.length) return i; 33 | 34 | } 35 | } 36 | return -1; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /ImplementstrStr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | if(haystack.isEmpty() || needle.isEmpty()){ 4 | return 0; 5 | } 6 | if(needle.length() > haystack.length()){ 7 | return -1; 8 | } 9 | if(needle.length() == haystack.length() && haystack.equals(needle) == true){ 10 | return 0; 11 | } 12 | if(haystack.contains(needle)){ 13 | return haystack.indexOf(needle); 14 | } 15 | return -1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /InsertInterval.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} intervals 3 | * @param {number[]} newInterval 4 | * @return {number[][]} 5 | */ 6 | var insert = function(intervals, newInterval) { 7 | 8 | let [start, end] = newInterval; 9 | const left = []; 10 | const right = []; 11 | 12 | for(const [first, last] of intervals) { 13 | if(start > last) left.push([first, last]); 14 | else if(end < first) right.push([first, last]); 15 | else { 16 | start = Math.min(start, first); 17 | end = Math.max(end, last); 18 | } 19 | } 20 | 21 | return [...left, [start, end], ...right]; 22 | 23 | }; 24 | -------------------------------------------------------------------------------- /InsertIntoABinarySearchTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @param {number} val 12 | * @return {TreeNode} 13 | */ 14 | 15 | const insertNode = (root, val) => { 16 | if(!root) return new TreeNode(val); 17 | if(root.val > val) root.left = insertNode(root.left, val); 18 | else root.right = insertNode(root.right, val); 19 | return root; 20 | } 21 | 22 | var insertIntoBST = function(root, val) { 23 | root = insertNode(root, val); 24 | return root; 25 | }; 26 | -------------------------------------------------------------------------------- /IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | // TC: O(1) SC: O(n) 2 | class Solution { 3 | public static String intToRoman(int num) { 4 | 5 | // Creating Dictionary For Possible Outcomes 6 | String M[] = {"", "M", "MM", "MMM"}; 7 | String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 8 | String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 9 | String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 10 | 11 | // Returning Result Based On The Max Constraints 12 | return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /IntersectionOfTwoArraysII.js: -------------------------------------------------------------------------------- 1 | 2 | // TC: O(N) SC: O(N) 3 | var intersect = function(nums1, nums2) { 4 | const map = new Map(); 5 | nums1.forEach(num => { 6 | map.set(num, map.has(num) ? map.get(num) + 1 : 1); 7 | }); 8 | const result = []; 9 | nums2.forEach(num => { 10 | if(map.has(num)) { 11 | result.push(num); 12 | map.get(num) > 1 ? map.set(num, map.get(num) - 1) : map.delete(num); 13 | } 14 | }); 15 | return result; 16 | }; 17 | -------------------------------------------------------------------------------- /IntersectionOfTwoLinkedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 | ListNode aPointer = headA; 15 | ListNode bPointer = headB; 16 | 17 | while(aPointer != bPointer){ 18 | if(aPointer == null){ 19 | aPointer = headB; 20 | }else{ 21 | aPointer = aPointer.next; 22 | } 23 | if(bPointer == null){ 24 | bPointer = headA; 25 | }else{ 26 | bPointer = bPointer.next; 27 | } 28 | } 29 | return aPointer; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /IntersectionOfTwoLinkedLists.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | 9 | /** 10 | * @param {ListNode} headA 11 | * @param {ListNode} headB 12 | * @return {ListNode} 13 | */ 14 | var getIntersectionNode = function(headA, headB) { 15 | let headAPointer = headA; 16 | let headBPointer = headB; 17 | while(headAPointer !== headBPointer) { 18 | if(headAPointer) headAPointer = headAPointer.next; 19 | else headAPointer = headB; 20 | if(headBPointer) headBPointer = headBPointer.next; 21 | else headBPointer = headA; 22 | } 23 | return headAPointer; 24 | }; 25 | -------------------------------------------------------------------------------- /IntersectionPointInYShapedLinkedLists.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //Function to find intersection point in Y shaped Linked Lists. 3 | intersectPoint(head1, head2) 4 | { 5 | //your code here 6 | let headA = head1; 7 | let headB = head2; 8 | 9 | while(headA !== headB) { 10 | if(headA) headA = headA.next; 11 | else headA = head2; 12 | if(headB) headB = headB.next; 13 | else headB = head1; 14 | } 15 | return headA ? headA.data : -1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /InvertBinaryTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {TreeNode} 12 | */ 13 | var invertTree = function(root) { 14 | if(!root) return null; 15 | const left = invertTree(root.left); 16 | const right = invertTree(root.right); 17 | root.left = right; 18 | root.right = left; 19 | 20 | return root; 21 | }; 22 | -------------------------------------------------------------------------------- /IsSubsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSubsequence(String s, String t) { 3 | if(s.length()>t.length()){ 4 | return false; 5 | } 6 | int i=0; 7 | int count = 0; 8 | int j = 0; 9 | 10 | while(i characterMap = new HashMap<>(); 8 | HashMap uniqueMap = new HashMap<>(); 9 | 10 | for(int i=0; i (extraCandies + element) >= max ? true : false); 9 | }; 10 | -------------------------------------------------------------------------------- /KthMissingPositiveNumber.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var findKthPositive = function(arr, k) { 7 | const max = Math.max(...arr); 8 | const set = new Set(arr); 9 | let count = 0; 10 | let i; 11 | for(i=1; i<=max; i++) { 12 | if(!set.has(i)) count++; 13 | if(count === k) return i; 14 | } 15 | if(count < k) { 16 | while(count < k - 1) { 17 | i++; 18 | count++; 19 | } 20 | } 21 | return i; 22 | }; 23 | -------------------------------------------------------------------------------- /KthSmallestElement.js: -------------------------------------------------------------------------------- 1 | // Sort Approach 2 | class Solution { 3 | kthSmallest(arr,l,r,k){ 4 | //code here 5 | arr.sort((a,b) => a-b); 6 | return arr[k - 1]; 7 | } 8 | } 9 | 10 | 11 | // Binary Search Tree Approach 12 | class Node { 13 | constructor (data) { 14 | this.data = data; 15 | this.left = null; 16 | this.right = null; 17 | } 18 | 19 | } 20 | 21 | const insert = (root, val) => { 22 | if(!root) return new Node(val); 23 | if(root.data > val) root.left = insert(root.left, val); 24 | else root.right = insert(root.right, val); 25 | return root; 26 | } 27 | 28 | const inorder = (root, result) => { 29 | if(!root) return; 30 | inorder(root.left, result); 31 | result.push(root.data); 32 | inorder(root.right, result); 33 | } 34 | 35 | class Solution { 36 | kthSmallest(arr,l,r,k){ 37 | //code here 38 | let root; 39 | for(let i=l; i<=r; i++) { 40 | root = insert(root, arr[i]); 41 | } 42 | const result = []; 43 | inorder(root, result); 44 | return result[k - 1]; 45 | 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /LargestNumber.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {string} 4 | */ 5 | //TC: O(NlogN) SC: O(1) 6 | var largestNumber = function(nums) { 7 | // Sort the array using a custom comparator function. 8 | // The comparator compares two numbers, a and b, as strings. 9 | // `${b}${a}` and `${a}${b}` create two different string combinations. 10 | // If `${b}${a}` is greater, b should come before a; otherwise, a should come before b. 11 | nums.sort((a, b) => `${b}${a}` - `${a}${b}`); 12 | 13 | // If the first number in the sorted array is 0, return '0'. 14 | // This is to handle cases where all numbers are zeros (e.g., [0, 0]). 15 | // In such cases, joining the numbers would still give '0'. 16 | return nums[0] ? nums.join('') : '0'; 17 | }; 18 | -------------------------------------------------------------------------------- /LargestNumberFormedFromAnArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Number[]} arr 3 | * @returns {String} 4 | */ 5 | 6 | class Solution{ 7 | printLargest(arr){ 8 | //code here 9 | arr.sort((a,b) => { 10 | const str1 = String(a + b); 11 | const str2 = String(b + a); 12 | if(str1.localeCompare(str2) > 0) return 1; 13 | else if(str2.localeCompare(str1) > 0) return -1; 14 | else return 0; 15 | }); 16 | return arr.reverse().join(''); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LargestPerimeterTriangle.java: -------------------------------------------------------------------------------- 1 | // TC: O(nlogn) SC: O(1) 2 | class Solution { 3 | public int largestPerimeter(int[] nums) { 4 | 5 | // Sort 6 | Arrays.sort(nums); 7 | 8 | // Iterating With A Gap Of 3 In the End 9 | for(int i=nums.length-3; i>=0; i--){ 10 | 11 | // Checking If It Satisfies The Basic Condition Of A Triangle From The End Of The Array 12 | if(nums[i] + nums[i+1] > nums[i+2]){ 13 | return nums[i] + nums[i+1] + nums[i+2]; 14 | } 15 | 16 | } 17 | 18 | // Default Return 19 | return 0; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LargestPositiveIntegerThatExistsWithItsNegative.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMaxK(int[] nums) { 3 | HashSet set = new HashSet<>(); 4 | int max = Integer.MIN_VALUE; 5 | for(int num : nums){ 6 | set.add(num); 7 | } 8 | 9 | for(int num : nums){ 10 | if(num > 0 && set.contains(-1 * num)){ 11 | if(max < num){ 12 | max = num; 13 | } 14 | } 15 | } 16 | 17 | if(max == Integer.MIN_VALUE){ 18 | return -1; 19 | } 20 | 21 | return max; 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LargestSubarrayWith0Sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Number[]} arr 3 | * @param {Number} n 4 | * @returns {Number} 5 | */ 6 | // TC: O(N) SC: O(N) 7 | class Solution { 8 | maxLen(arr,n){ 9 | //code here 10 | let maxLength = 0, sum = 0; 11 | const map = new Map([[sum, -1]]); 12 | arr.forEach((num, i) => { 13 | sum += num; 14 | !map.has(sum) ? map.set(sum, i) : maxLength = Math.max(maxLength, i - map.get(sum)); 15 | }); 16 | return maxLength; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LastStoneWeight.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} stones 3 | * @return {number} 4 | */ 5 | var lastStoneWeight = function(stones) { 6 | const maxHeap = new MaxPriorityQueue(); 7 | stones.forEach((el) => { 8 | maxHeap.enqueue(el); 9 | }); 10 | while(maxHeap.size() > 1) { 11 | const y = maxHeap.dequeue().element; 12 | const x = maxHeap.dequeue().element; 13 | if(y !== x) { 14 | maxHeap.enqueue(y - x); 15 | } 16 | } 17 | return maxHeap.size() === 0 ? 0 : maxHeap.front().element; 18 | }; 19 | -------------------------------------------------------------------------------- /LeftViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* A Binary Tree node 2 | class Node 3 | { 4 | int data; 5 | Node left, right; 6 | 7 | Node(int item) 8 | { 9 | data = item; 10 | left = right = null; 11 | } 12 | }*/ 13 | class Tree 14 | { 15 | //Function to return list containing elements of left view of binary tree. 16 | ArrayList leftView(Node root) 17 | { 18 | // Your code here 19 | ArrayList result = new ArrayList<>(); 20 | 21 | leftSideView(result, root, 0); 22 | 23 | return result; 24 | 25 | } 26 | 27 | public void leftSideView(ArrayList result, Node root, int depth){ 28 | 29 | // Base Case 30 | if(root == null){ 31 | return; 32 | } 33 | 34 | if(result.size() == depth){ 35 | result.add(root.data); 36 | } 37 | 38 | leftSideView(result, root.left, depth+1); 39 | leftSideView(result, root.right, depth+1); 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /LengthOfLastWord.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var lengthOfLastWord = function(s) { 7 | if(s.length === 0) return 0; 8 | let foundWord = false; 9 | let count = 0; 10 | for(let i=s.length - 1; i>=0; i--) { 11 | if(s[i] !== ' ') { 12 | count++; 13 | foundWord = true; 14 | } 15 | else if(foundWord) { 16 | return count; 17 | } 18 | } 19 | return count; 20 | }; 21 | 22 | //TC: O(N) SC: O(N) 23 | var lengthOfLastWord = function(s) { 24 | if(s.length === 0) return 0; 25 | return s.trim().split(' ').pop().length; 26 | }; 27 | -------------------------------------------------------------------------------- /LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | 15 | if(head == null){ 16 | return false; 17 | } 18 | 19 | ListNode stable = head; 20 | ListNode unstable = head.next; 21 | while(stable != unstable){ 22 | if(stable.next == null || unstable.next == null || unstable.next.next == null){ 23 | return false; 24 | } 25 | 26 | stable = stable.next; 27 | unstable = unstable.next.next; 28 | 29 | } 30 | 31 | return true; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LinkedListCycle.js: -------------------------------------------------------------------------------- 1 | // TC: O(N) SC: O(1) 2 | var hasCycle = function(head) { 3 | if(!head || !head.next) return false; // Handle empty or single-node lists 4 | 5 | let traverseNode = head; // Initialize slow pointer 6 | let fastNode = head; // Initialize fast pointer 7 | 8 | while(fastNode && fastNode.next) { // Loop until fast pointer reaches end 9 | traverseNode = traverseNode.next; // Move slow pointer one step 10 | fastNode = fastNode.next.next; // Move fast pointer two steps 11 | 12 | if(traverseNode === fastNode) return true; // Cycle detected 13 | } 14 | 15 | return false; // No cycle found 16 | }; 17 | -------------------------------------------------------------------------------- /LinkedListCycleII.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | 9 | /** 10 | * @param {ListNode} head 11 | * @return {ListNode} 12 | */ 13 | var detectCycle = function(head) { 14 | let traverseNode = head; 15 | let fastNode = head; 16 | 17 | while(fastNode && fastNode.next) { 18 | fastNode = fastNode.next.next; 19 | traverseNode = traverseNode.next; 20 | if(fastNode === traverseNode) { 21 | let entry = head; 22 | while(entry !== fastNode) { 23 | entry = entry.next; 24 | fastNode = fastNode.next; 25 | } 26 | return entry; 27 | } 28 | } 29 | return null; 30 | }; 31 | -------------------------------------------------------------------------------- /LongestCommonPrefix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} strs 3 | * @return {string} 4 | */ 5 | var longestCommonPrefix = function(strs) { 6 | let word = strs[0]; 7 | const n = strs.length; 8 | for(let i=1; i= 0; i--){ 7 | 8 | for(int j=dp[0].length - 2; j >= 0; j--){ 9 | 10 | if(text1.charAt(i) == text2.charAt(j)){ 11 | dp[i][j] = dp[i + 1][j + 1] + 1; 12 | } 13 | else{ 14 | dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]); 15 | } 16 | 17 | } 18 | 19 | } 20 | 21 | return dp[0][0]; 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LongestConsecutiveSequence.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | //TC: O(N) SC: O(N) 6 | var longestConsecutive = function(nums) { 7 | const set = new Set(nums); 8 | let maxSize = 0; 9 | nums.forEach((num) => { 10 | if(set.has(num) && !set.has(num + 1)) { 11 | let size = 0; 12 | while(set.has(num)) { 13 | size++; 14 | num--; 15 | } 16 | maxSize = Math.max(maxSize, size); 17 | } 18 | }); 19 | return maxSize; 20 | }; 21 | -------------------------------------------------------------------------------- /LongestHappyPrefix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var longestPrefix = function(s) { 6 | const prefixes = []; 7 | for(let i=1; i 0; i--){ 12 | suffixes.push(s.slice(i, s.length)); 13 | } 14 | console.log(prefixes); 15 | console.log(suffixes); 16 | 17 | let result = ''; 18 | prefixes.forEach((word, i) => { 19 | if(word === suffixes[i]){ 20 | result = (result.length > word) ? result : word; 21 | } 22 | }); 23 | return result; 24 | }; 25 | -------------------------------------------------------------------------------- /LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestPalindrome(String s) { 3 | int[] charCount = new int[128]; 4 | 5 | for(char c: s.toCharArray()){ 6 | charCount[c]++; 7 | } 8 | 9 | int result = 0; 10 | 11 | for(int char_count : charCount){ 12 | result = result + (char_count / 2) * 2; 13 | if(result%2 == 0 && char_count%2==1){ 14 | result++; 15 | } 16 | } 17 | 18 | return result; 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LongestSubArrayHavingSumK.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | 4 | // Function for finding maximum and value pair 5 | public static int lenOfLongSubarr (int A[], int N, int K) { 6 | //Complete the function 7 | Map map = new HashMap<>(); 8 | int maxLength = 0; 9 | int sum = 0; 10 | 11 | for(int i=0; i root.val && q.val > root.val) { 10 | root = root.right; // Move search towards the right subtree 11 | } 12 | // Case 3: LCA Found! 13 | // One node lies on the left, the other on the right OR one of the nodes is the current node 14 | else { 15 | return root; 16 | } 17 | } 18 | return null; // This line should theoretically not be reached if it's a valid BST 19 | }; 20 | -------------------------------------------------------------------------------- /LowestCommonAncestorOfABinaryTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {TreeNode} root 3 | * @param {TreeNode} p 4 | * @param {TreeNode} q 5 | * @return {TreeNode} 6 | */ 7 | // TC: O(N) SC: O(N) 8 | var lowestCommonAncestor = function(root, p, q) { 9 | if(!root || root === p || root === q) return root; 10 | const left = lowestCommonAncestor(root.left, p, q); 11 | const right = lowestCommonAncestor(root.right, p, q); 12 | if(!left) return right; 13 | else if(!right) return left; 14 | else return root; 15 | // Alternate Way of writing the if else condition 16 | // if(left && right) return root; 17 | // else return left || right; 18 | }; 19 | -------------------------------------------------------------------------------- /LuckyNumbersInAMatrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number[]} 4 | */ 5 | // TC: O(N * M) SC: O(N) 6 | var luckyNumbers = function(matrix) { 7 | const minRows = []; 8 | const maxCols = []; 9 | for(let i=0; i { 8 | if(count === 0) majEl = num; 9 | count += (majEl === num) ? 1 : -1; 10 | }); 11 | return majEl; 12 | }; 13 | -------------------------------------------------------------------------------- /MajorityElementII.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | //TC: O(N) SC: O(1) 6 | var majorityElement = function(nums) { 7 | let freq1 = 0, el1 = null, freq2 = 0, el2 = null; 8 | nums.forEach((num) => { 9 | if(el1 && el1 === num) freq1++; 10 | else if(el2 && el2 === num) freq2++; 11 | else if(freq1 === 0) { 12 | el1 = num; 13 | freq1++; 14 | } 15 | else if(freq2 === 0) { 16 | el2 = num; 17 | freq2++; 18 | } 19 | else { 20 | freq1--; 21 | freq2--; 22 | } 23 | }); 24 | freq1 = 0; 25 | freq2 = 0; 26 | nums.forEach((num) => { 27 | if(el1 === num) freq1++; 28 | else if(el2 === num) freq2++; 29 | }) 30 | const result = []; 31 | if(freq1 > Math.floor(nums.length/3)) result.push(el1); 32 | if(freq2 > Math.floor(nums.length/3)) result.push(el2); 33 | return result; 34 | }; 35 | -------------------------------------------------------------------------------- /MakeTheStringGreat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var makeGood = function(s) { 6 | let result = ''; 7 | for (let i = 0; i < s.length; i++) { 8 | if (result.length > 0 && 9 | (result.charCodeAt(result.length - 1) + 32 === s.charCodeAt(i) || 10 | result.charCodeAt(result.length - 1) - 32 === s.charCodeAt(i))) { 11 | result = result.slice(0, -1); // Remove last character 12 | } else { 13 | result += s[i]; 14 | } 15 | } 16 | return result; 17 | }; 18 | -------------------------------------------------------------------------------- /MakeTwoArraysEqualByReversingSubarrays.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} target 3 | * @param {number[]} arr 4 | * @return {boolean} 5 | */ 6 | // TC: O(N) SC: O(N) 7 | var canBeEqual = function(target, arr) { 8 | const map = new Map(); 9 | target.forEach(el => { 10 | map.set(el, (map.get(el) || 0) + 1); 11 | }); 12 | 13 | for(let i=0; i=grid.length || j<0 || j>=grid[0].length || grid[i][j] == 0){ 21 | return; 22 | }else{ 23 | count = count + 1; 24 | grid[i][j]=0; 25 | 26 | weFoundOne(grid, i+1, j); 27 | weFoundOne(grid, i-1, j); 28 | weFoundOne(grid, i, j+1); 29 | weFoundOne(grid, i, j-1); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MaxAreaOfIsland.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} grid 3 | * @return {number} 4 | */ 5 | var maxAreaOfIsland = function(grid) { 6 | 7 | const calculateArea = (grid, i, j) => { 8 | let totalArea = 0; 9 | const islandArea = (grid, i, j) => { 10 | if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] === 0) { 11 | return; 12 | } 13 | totalArea += 1; 14 | grid[i][j] = 0; 15 | islandArea(grid, i + 1, j); 16 | islandArea(grid, i, j + 1); 17 | islandArea(grid, i - 1, j); 18 | islandArea(grid, i, j - 1); 19 | } 20 | islandArea(grid, i, j); 21 | return totalArea; 22 | } 23 | 24 | let maxArea = 0; 25 | for(let i=0; i { 15 | sumOfProducts += (num * i); 16 | sum += num; 17 | }); 18 | 19 | result = sumOfProducts; 20 | 21 | for(let i=1; i 0 && j > 0){ 11 | matrix[i][j] = Math.min(matrix[i][j - 1], matrix[i - 1][j], matrix[i - 1][j - 1]) + 1; 12 | } 13 | max = Math.max(matrix[i][j], max); 14 | } 15 | } 16 | return max ** 2; 17 | }; 18 | -------------------------------------------------------------------------------- /MaximumHeightOfATriangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} red 3 | * @param {number} blue 4 | * @return {number} 5 | */ 6 | // TC: O(SQRT(min(red, blue))) 7 | var maxHeightOfTriangle = function(red, blue) { 8 | const findHeight = (red, blue) => { 9 | let maxHeight = 0; 10 | let level = 1; 11 | let flag = true; 12 | while(flag) { 13 | if(level % 2 === 1) { 14 | red >= level ? red-=level : flag = false; 15 | } 16 | else { 17 | blue >= level ? blue -= level : flag = false; 18 | } 19 | if(!flag) break; 20 | level++; 21 | maxHeight++; 22 | } 23 | return maxHeight; 24 | } 25 | return Math.max(findHeight(red,blue), findHeight(blue, red)); 26 | }; 27 | -------------------------------------------------------------------------------- /MaximumIceCreamBars.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} costs 3 | * @param {number} coins 4 | * @return {number} 5 | */ 6 | 7 | var maxIceCream = (costs, coins) => { 8 | const max = Math.max(...costs); 9 | const dp = new Array(max + 1).fill(0); 10 | let iceCreams = 0; 11 | costs.forEach(val => { 12 | dp[val]++; 13 | }) 14 | let index = 1; 15 | while(index < dp.length && coins > 0){ 16 | if(index <= coins && dp[index] > 0){ 17 | while(dp[index] > 0 && coins >= index){ 18 | coins -= index; 19 | iceCreams++; 20 | dp[index]--; 21 | } 22 | } 23 | index++; 24 | } 25 | return iceCreams; 26 | } 27 | 28 | // var maxIceCream = function(costs, coins) { 29 | // costs.sort((a,b) => a-b); 30 | // let iceCreams = 0; 31 | // let index = 0; 32 | // while(index < costs.length && coins > 0){ 33 | // if(coins >= costs[index]){ 34 | // iceCreams++; 35 | // coins -= costs[index]; 36 | // } 37 | // index++; 38 | // } 39 | // return iceCreams; 40 | // }; 41 | -------------------------------------------------------------------------------- /MaximumNestingDepthOfTheParentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var maxDepth = function(s) { 6 | let tracker = 0; 7 | let depth = 0; 8 | for(let ch of s) { 9 | if(ch === '(') tracker++; 10 | if(ch === ')') tracker--; 11 | depth = Math.max(depth, tracker); 12 | } 13 | return depth; 14 | 15 | }; 16 | -------------------------------------------------------------------------------- /MaximumProductSubarray.js: -------------------------------------------------------------------------------- 1 | var maxProduct = function(nums) { 2 | 3 | let currentMaxProduct = nums[0]; 4 | let currentMinProduct = nums[0]; 5 | let previousMaxProduct = nums[0]; 6 | let previousMinProduct = nums[0]; 7 | let result = nums[0]; 8 | 9 | for(let i=1; i= 0){ 16 | currentSum += nums[i]; 17 | }else{ 18 | currentSum = nums[i]; 19 | } 20 | 21 | if(currentSum > maxSum){ 22 | maxSum = currentSum; 23 | } 24 | 25 | } 26 | return maxSum; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /MaximumSubarray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var maxSubArray = function(nums) { 6 | let currentSum = 0, maxSum = nums[0]; 7 | nums.forEach((currentElement, i) => { 8 | currentSum <= 0 ? currentSum = currentElement : currentSum += currentElement; 9 | maxSum = Math.max(maxSum, currentSum); 10 | }); 11 | return maxSum; 12 | }; 13 | -------------------------------------------------------------------------------- /MaximumSumOfDistinctSubarraysWithLengthK.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maximumSubarraySum(int[] nums, int k) { 3 | 4 | long result = 0L; 5 | long sum = 0L; 6 | 7 | int n = nums.length; 8 | 9 | HashMap map = new HashMap<>(); 10 | 11 | for(int i=0; i= k){ 15 | 16 | map.put(nums[i - k], map.get(nums[i - k]) - 1); 17 | sum -= nums[i-k]; 18 | if(map.get(nums[i - k]) == 0){ 19 | map.remove(nums[i - k]); 20 | } 21 | 22 | } 23 | 24 | if(map.size() == k){ 25 | result = Math.max(result, sum); 26 | } 27 | 28 | } 29 | 30 | return result; 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /MergeIntervals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} intervals 3 | * @return {number[][]} 4 | */ 5 | 6 | 7 | 8 | var merge = function(intervals) { 9 | // Base Condition 10 | if(!intervals.length) return intervals; 11 | // Sort Based On The First Start Interval Of The Array 12 | intervals.sort((a,b) => a[0] - b[0]); 13 | 14 | let prev = intervals[0]; 15 | let result = [prev]; 16 | 17 | const mergeIntervals = (currentElement) => { 18 | if(currentElement[0] <= prev[1]){ 19 | prev[1] = Math.max(prev[1], currentElement[1]); 20 | } 21 | else { 22 | result.push(currentElement); 23 | prev = currentElement; 24 | } 25 | } 26 | 27 | 28 | // Creating the new intervals 29 | intervals.forEach(mergeIntervals); 30 | return result; 31 | }; 32 | -------------------------------------------------------------------------------- /MergeSortedArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number} m 4 | * @param {number[]} nums2 5 | * @param {number} n 6 | * @return {void} Do not return anything, modify nums1 in-place instead. 7 | */ 8 | // TC: O(N) SC: O(1) Clean Code 9 | var merge = function(nums1, m, nums2, n) { 10 | 11 | if(m === 0) { 12 | for(let i=0; i= 0 || nums1Index >= 0 || nums2Index >= 0) { 20 | 21 | const nums1Val = nums1Index >= 0 ? nums1[nums1Index] : -Infinity; 22 | const nums2Val = nums2Index >= 0 ? nums2[nums2Index] : -Infinity; 23 | 24 | if(nums1Val < nums2Val) { 25 | nums1[numsIndex--] = nums2Val; 26 | nums2Index--; 27 | } 28 | else { 29 | nums1[numsIndex--] = nums1Val; 30 | nums1Index--; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MergeStringsAlternatively.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} word1 3 | * @param {string} word2 4 | * @return {string} 5 | */ 6 | var mergeAlternately = function(word1, word2) { 7 | let word1Size = word1.length; 8 | let word2Size = word2.length; 9 | let i=0, j=0, result = ''; 10 | while(i < word1Size || j < word2Size) { 11 | if(i < word1Size) { 12 | result += word1[i]; 13 | i++; 14 | } 15 | if(j < word2Size) { 16 | result += word2[j]; 17 | j++; 18 | } 19 | } 20 | return result; 21 | }; 22 | -------------------------------------------------------------------------------- /MiddleOfTheLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode middleNode(ListNode head) { 13 | 14 | ListNode midLink = head; 15 | ListNode runnerLink = head; 16 | 17 | while(midLink!=null && runnerLink != null 18 | && midLink.next!=null && runnerLink.next != null){ 19 | midLink = midLink.next; 20 | runnerLink = runnerLink.next.next; 21 | } 22 | 23 | return midLink; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /MinimumAbsoluteDifferenceInBST.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {number} 12 | */ 13 | 14 | const traversal = (root) => { 15 | let currentValue, previousValue; 16 | let minValue = Infinity; 17 | const inorder = (root) => { 18 | if(!root) return; 19 | if(root.left) inorder(root.left); 20 | if(currentValue !== undefined) { 21 | 22 | previousValue = currentValue; 23 | currentValue = root.val; 24 | minValue = Math.min(minValue, currentValue - previousValue); 25 | } 26 | else { 27 | 28 | currentValue = root.val; 29 | } 30 | if(root.right) inorder(root.right); 31 | } 32 | inorder(root); 33 | return minValue; 34 | } 35 | 36 | var getMinimumDifference = function(root) { 37 | return traversal(root); 38 | }; 39 | -------------------------------------------------------------------------------- /MinimumDistanceBetweenBSTNodes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {TreeNode} root 3 | * @return {number} 4 | */ 5 | 6 | const traversal = (root) => { 7 | let currentValue, previousValue; 8 | let minValue = Infinity; 9 | const inorder = (root) => { 10 | if(!root) return; 11 | if(root.left) inorder(root.left); 12 | if(currentValue !== undefined) { 13 | 14 | previousValue = currentValue; 15 | currentValue = root.val; 16 | minValue = Math.min(minValue, currentValue - previousValue); 17 | } 18 | else { 19 | 20 | currentValue = root.val; 21 | } 22 | if(root.right) inorder(root.right); 23 | } 24 | inorder(root); 25 | return minValue; 26 | } 27 | 28 | 29 | var minDiffInBST = function(root) { 30 | return traversal(root); 31 | }; 32 | -------------------------------------------------------------------------------- /MinimumElementInASortedAndRotatedArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @returns {number} 5 | */ 6 | // TC: O(logn) SC: O(1) 7 | class Solution{ 8 | 9 | findPivot(arr, n) { 10 | let start = 0, end = n - 1; 11 | while(start < end) { 12 | const mid = start + Math.floor((end - start) / 2); 13 | if(arr[mid] > arr[end]) start = mid + 1; 14 | else end = mid; 15 | } 16 | return start; 17 | } 18 | 19 | findMin(arr,n){ 20 | //code here 21 | const index = this.findPivot(arr, n); 22 | return arr[index]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /MinimumNumberOfSwapsToMakeTheStringBalanced.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var minSwaps = function(s) { 6 | let balance = 0, maxImbalance = 0; 7 | for(let ch of s) { 8 | ch === '[' ? balance++ : balance--; 9 | maxImbalance = Math.max(maxImbalance, -balance); 10 | } 11 | return Math.ceil(maxImbalance / 2); 12 | }; 13 | -------------------------------------------------------------------------------- /MinimumOperations.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number} 4 | */ 5 | 6 | class Solution { 7 | 8 | minOperation(n){ 9 | 10 | //code here 11 | let count = 0; 12 | 13 | while(n > 0) { 14 | if(n % 2 === 0) n /= 2; 15 | else n -= 1; 16 | count++; 17 | } 18 | 19 | return count; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /MinimumPlatforms.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number[]} dep 4 | * @param {number} n 5 | * @returns {number} 6 | */ 7 | // TC: O(NlogN) SC: O(1) 8 | class Solution { 9 | //Function to find the minimum number of platforms required at the 10 | //railway station such that no train waits. 11 | findPlatform(arr, dep, n) 12 | { 13 | //your code here 14 | arr.sort((a,b) => a-b); 15 | dep.sort((a,b) => a-b); 16 | let platforms = 1, result = 1; 17 | let arrivalIndex=1, departureIndex=0; 18 | 19 | while(arrivalIndex < n && departureIndex < n) { 20 | if(arr[arrivalIndex] <= dep[departureIndex]) { 21 | platforms++; 22 | arrivalIndex++; 23 | } 24 | else { 25 | platforms--; 26 | departureIndex++; 27 | } 28 | result = Math.max(platforms, result); 29 | } 30 | 31 | return result; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /MinimumRemoveToMakeValidParenthesis.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var minRemoveToMakeValid = function(s) { 6 | const stack = []; 7 | const str = [...s]; 8 | 9 | for(let i=0; i 0) stack.pop(); 15 | } 16 | 17 | if(stack.length > 0) 18 | while(stack.length > 0){ 19 | const index = stack.pop(); 20 | str[index]=''; 21 | 22 | } 23 | return str.join(''); 24 | }; 25 | -------------------------------------------------------------------------------- /MirrorTree.java: -------------------------------------------------------------------------------- 1 | /* A Binary Tree node 2 | class Node 3 | { 4 | int data; 5 | Node left, right; 6 | Node(int item) 7 | { 8 | data = item; 9 | left = right = null; 10 | } 11 | } */ 12 | 13 | class Solution { 14 | // Function to convert a binary tree into its mirror tree. 15 | void mirror(Node root) { 16 | // Your code here 17 | 18 | if(root == null){ 19 | return; 20 | } 21 | 22 | mirror(root.left); 23 | mirror(root.right); 24 | 25 | Node temp = root.right; 26 | root.right = root.left; 27 | root.left = temp; 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /MissingNumberInArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} array 3 | * @param {number} n 4 | * @returns {number} 5 | */ 6 | 7 | // Optimized Solution: TC: O(N) SC: O(1) 8 | class Solution{ 9 | MissingNumber(array,n){ 10 | //code here 11 | // Mathematical Formula To Find Sum Of 1-N Numbers 12 | const sum = Math.floor(n * (n + 1) / 2); 13 | // Finding Sum Of All Elements Of The Array 14 | const arraySum = array.reduce((acc, curr) => acc + curr, 0); 15 | return sum - arraySum; 16 | } 17 | } 18 | 19 | // Brute Force TC: O(N) SC: O(1) 20 | class Solution{ 21 | MissingNumber(array,n){ 22 | //code here 23 | const set = new Set(array); 24 | if(!set.has(1)) return 1; 25 | if(!set.has(n)) return n; 26 | let num = n; 27 | while(set.has(num)) num--; 28 | return num; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /MostFrequentEvenElement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mostFrequentEven(int[] nums) { 3 | HashMap map = new HashMap<>(); 4 | for(int num : nums){ 5 | map.put(num, map.getOrDefault(num, 0) + 1); 6 | } 7 | 8 | int minNumber = Integer.MAX_VALUE; 9 | int maxFrequency = 0; 10 | 11 | for(int num : nums){ 12 | if(map.get(num) > maxFrequency && num % 2 == 0){ 13 | 14 | minNumber = num; 15 | maxFrequency = map.get(num); 16 | 17 | }else if(map.get(num) == maxFrequency && num % 2 == 0){ 18 | minNumber = Math.min(minNumber, num); 19 | } 20 | } 21 | 22 | if(minNumber != Integer.MAX_VALUE){ 23 | return minNumber; 24 | }else { 25 | return -1; 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /MoveAllNegativeElementsToEnd.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @returns {void} 5 | */ 6 | 7 | class Solution{ 8 | segregateElements(arr,n){ 9 | //code here 10 | const resultPos = []; 11 | const resultNeg = []; 12 | arr.forEach((num) => { 13 | num >= 0 ? resultPos.push(num) : resultNeg.push(num); 14 | }); 15 | const result = [...resultPos, ...resultNeg]; 16 | for(let i=0; i { 8 | if(currentElement !== 0) { 9 | if(index !== i) { 10 | nums[index] = currentElement; 11 | nums[i] = 0; 12 | } 13 | index++; 14 | } 15 | }); 16 | }; 17 | -------------------------------------------------------------------------------- /NextGreaterElementI.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number[]} nums2 4 | * @return {number[]} 5 | */ 6 | 7 | 8 | 9 | 10 | 11 | var nextGreaterElement = function(nums1, nums2) { 12 | const stack = []; 13 | const map = new Map(); 14 | 15 | const peek = () => stack[stack.length - 1]; 16 | 17 | nums2.forEach((num) => { 18 | while(stack.length !== 0 && peek() < num) map.set(stack.pop(), num); 19 | stack.push(num); 20 | }); 21 | 22 | const result = nums1.map((num) => map.has(num) ? map.get(num) : -1); 23 | return result; 24 | 25 | }; 26 | -------------------------------------------------------------------------------- /NextGreaterElementII.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | var nextGreaterElements = function(nums) { 6 | 7 | if(nums.length === 1) return [-1]; 8 | 9 | const result = []; 10 | const stack = []; 11 | 12 | const peek = () => stack[stack.length - 1]; 13 | const isEmpty = () => stack.length === 0; 14 | 15 | for(let i = 2 * nums.length - 1; i >= 0; i--) { 16 | while(!isEmpty() && nums[peek()] <= nums[i % nums.length]) stack.pop(); 17 | result[i % nums.length] = !isEmpty() ? nums[peek()] : -1; 18 | stack.push(i % nums.length); 19 | } 20 | 21 | return result; 22 | 23 | }; 24 | -------------------------------------------------------------------------------- /NonRepeatingNummbers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | 6 | class Solution { 7 | singleNumber(nums){ 8 | //code here 9 | const xXORy = nums.reduce((acc, curr) => acc ^ curr, 0); 10 | const rightMostBit = xXORy & (-1 * xXORy); 11 | let x = 0, y = 0; 12 | nums.forEach((num) => { 13 | (num & rightMostBit) === 0 ? x ^= num : y ^= num; 14 | }); 15 | if(x < y) return [x, y]; 16 | else return [y, x]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /NthTribonacciNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 0 ms, faster than 100.00% of Java online submissions for N-th Tribonacci Number. 3 | Memory Usage: 40.6 MB, less than 70.83% of Java online submissions for N-th Tribonacci Number. 4 | */ 5 | // Tabulation: TC: O(N) SC: O(N) 6 | class Solution { 7 | public int tribonacci(int n) { 8 | 9 | //Handling Edge Cases 10 | if(n == 0){ 11 | return 0; 12 | } 13 | if(n == 1 || n == 2){ 14 | return 1; 15 | } 16 | 17 | // Standard DP Template 18 | int[] dp = new int[n+1]; 19 | 20 | // Manually Inputting First 3 Elements Into The Array 21 | dp[0] = 0; 22 | dp[1] = 1; 23 | dp[2] = 1; 24 | 25 | // Calculating The Current Value Of Dp Using Sum Of Last 3 Elements 26 | for(int i=3 ; i { 8 | if(i >= grid.length || i < 0 || j >= grid[0].length || j < 0 || grid[i][j] === '0') { 9 | return; 10 | } 11 | grid[i][j] = '0'; 12 | countArea(grid, i + 1, j); 13 | countArea(grid, i - 1, j); 14 | countArea(grid, i, j + 1); 15 | countArea(grid, i, j - 1); 16 | } 17 | 18 | let count = 0; 19 | 20 | for(let i=0; i { 8 | if(num === 0) { 9 | maxLength++; 10 | count += maxLength; 11 | } 12 | else { 13 | maxLength = 0; 14 | } 15 | }); 16 | return count; 17 | }; 18 | -------------------------------------------------------------------------------- /OddEvenLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode oddEvenList(ListNode head) { 13 | if(head == null){ 14 | return head; 15 | } 16 | ListNode odd = head, even = head.next, evenHead = even; 17 | while(even != null && even.next != null){ 18 | odd.next = even.next; 19 | odd = odd.next; 20 | even.next = odd.next; 21 | even = even.next; 22 | } 23 | odd.next = evenHead; 24 | return head; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /OptimalPartitionOfString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int partitionString(String s) { 3 | 4 | HashSet set = new HashSet<>(); 5 | int count = 0; 6 | 7 | for(char c : s.toCharArray()){ 8 | if(set.contains(c)){ 9 | count++; 10 | set.clear(); 11 | set.add(c); 12 | }else{ 13 | set.add(c); 14 | } 15 | } 16 | 17 | count++; 18 | 19 | return count; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /PairwiseSwapElementsOfALinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Node} node 3 | * @return {Node} node 4 | */ 5 | 6 | 7 | /* 8 | Pairwise swap a linked list 9 | The input list will have at least one element 10 | node is defined as 11 | 12 | class Node{ 13 | constructor(data){ 14 | this.data = data; 15 | this.next = null; 16 | } 17 | } 18 | 19 | let head; 20 | This is method only submission. 21 | You only need to complete the below method. 22 | */ 23 | 24 | class Solution { 25 | pairWiseSwap(head) 26 | { 27 | //your code here 28 | let result = new Node(0); 29 | let resultPointer = result; 30 | resultPointer.next = head; 31 | while(resultPointer.next && resultPointer.next.next) { 32 | let firstNode = resultPointer.next; 33 | let secondNode = resultPointer.next.next; 34 | firstNode.next = secondNode.next; 35 | secondNode.next = firstNode; 36 | resultPointer.next = secondNode; 37 | resultPointer = resultPointer.next.next; 38 | } 39 | return result.next; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /PalindromeLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {boolean} 11 | */ 12 | // TC: O(N) SC: O(1) 13 | var isPalindrome = function(head) { 14 | const reverse = (head) => { 15 | let prev = null; 16 | while(head) { 17 | const next = head.next; 18 | head.next = prev; 19 | prev = head; 20 | head = next; 21 | } 22 | return prev; 23 | } 24 | 25 | let midNode = head; 26 | let traverseNode = head; 27 | 28 | while(traverseNode && traverseNode.next) { 29 | traverseNode = traverseNode.next.next; 30 | midNode = midNode.next; 31 | } 32 | traverseNode = head; 33 | midNode = reverse(midNode); 34 | while(midNode && traverseNode) { 35 | if(midNode.val !== traverseNode.val) return false; 36 | midNode = midNode.next; 37 | traverseNode = traverseNode.next; 38 | } 39 | return true; 40 | }; 41 | -------------------------------------------------------------------------------- /PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 9 ms, faster than 98.77% of Java online submissions for Palindrome Number. 3 | Memory Usage: 41.5 MB, less than 96.60% of Java online submissions for Palindrome Number. 4 | */ 5 | class Solution { 6 | public boolean isPalindrome(int x) { 7 | if(x < 0){ 8 | return false; 9 | } 10 | int nums = x; 11 | int reverse = 0; 12 | while(x != 0){ 13 | reverse = reverse * 10 + x%10; 14 | x = x/10; 15 | } 16 | if(nums == reverse){ 17 | return true; 18 | } 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /PalindromePermutation.js: -------------------------------------------------------------------------------- 1 | function permutePalindrome(st){ 2 | const map = new Map(); 3 | for(let str of st) { 4 | map.set(str, map.has(str) ? map.get(str) + 1 : 1); 5 | } 6 | let count = 0; 7 | for(let [key, value] of map) { 8 | if(Math.floor(value % 2) !== 0) { 9 | count++; 10 | } 11 | if(count > 1) return false; 12 | } 13 | return true; 14 | } 15 | 16 | export { 17 | permutePalindrome 18 | } 19 | -------------------------------------------------------------------------------- /PalindromicArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @return {number} 5 | */ 6 | 7 | class Solution { 8 | 9 | PalinArray(arr,n){ 10 | //code here 11 | const palindrome = (num) => { 12 | let start = 0, end = num.length - 1; 13 | while(start < end) { 14 | if(num[start] !== num[end]) return false; 15 | start++; 16 | end--; 17 | } 18 | return true; 19 | } 20 | for(let num of arr) { 21 | num = `${num}`; 22 | if(!palindrome(num)) return 0; 23 | } 24 | return 1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /PalindromicSubstrings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | // TC: O(N^2) SC: O(1) 6 | var countSubstrings = function(s) { 7 | const checkPalindrome = (s, left, right) => { 8 | let count = 0; 9 | while(left >= 0 && right < s.length && s[left] === s[right]) { 10 | left--; 11 | right++; 12 | count++; 13 | } 14 | return count; 15 | } 16 | let maxCount = 0; 17 | for(let i=0; i { 9 | c = c.toLowerCase(); 10 | if(c.charCodeAt(0) >= 'a'.charCodeAt(0) && c.charCodeAt(0) <= 'z'.charCodeAt(0)) { 11 | set.add(c); 12 | } 13 | }); 14 | return set.size === 26; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /PartitionList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode partition(ListNode head, int x) { 13 | ListNode highHead = new ListNode(0); 14 | ListNode high = highHead; 15 | ListNode lowHead = new ListNode(0); 16 | ListNode low = lowHead; 17 | 18 | while(head !=null){ 19 | if(head.val < x){ 20 | low.next = head; 21 | low = low.next; 22 | }else{ 23 | high.next = head; 24 | high = high.next; 25 | } 26 | 27 | head = head.next; 28 | 29 | } 30 | 31 | high.next = null; 32 | low.next = highHead.next; 33 | 34 | return lowHead.next; 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /PascalsTriangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} numRows 3 | * @return {number[][]} 4 | */ 5 | var generate = function(numRows) { 6 | if(numRows === 1) return [[1]]; 7 | const result = [[1]]; 8 | 9 | for(let i=1; i arr[mid + 1]) { 11 | end = mid; 12 | }else { 13 | start = mid + 1; 14 | } 15 | } 16 | return start; 17 | 18 | }; 19 | -------------------------------------------------------------------------------- /Permutations.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | // TC: O(n*n!) SC: O(n*n!) 6 | var permute = function(nums) { 7 | const result = []; 8 | const backtrack = (store, freq) => { 9 | if(store.length === nums.length) { 10 | result.push([...store]); 11 | return; 12 | } 13 | for(let i=0; i=0 ; i--){ 4 | digits[i] = (digits[i] + 1)%10; 5 | 6 | if(digits[i] != 0){ 7 | return digits; 8 | } 9 | } 10 | int[] nums = new int[digits.length+1]; 11 | nums[0] = 1; 12 | return nums; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /PlusOne.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} digits 3 | * @return {number[]} 4 | */ 5 | var plusOne = function(digits) { 6 | let carry = 1; 7 | for(let i=digits.length - 1; i>=0; i--) { 8 | const sum = digits[i] + carry; 9 | if(Math.floor(sum / 10) !== 0) { 10 | digits[i] = 0; 11 | carry = 1; 12 | } 13 | else { 14 | digits[i] = sum; 15 | return digits; 16 | } 17 | } 18 | return [1,...digits]; 19 | }; 20 | -------------------------------------------------------------------------------- /PopulatingNextRightPointersInEachNode.js: -------------------------------------------------------------------------------- 1 | /** 2 | * // Definition for a Node. 3 | * function Node(val, left, right, next) { 4 | * this.val = val === undefined ? null : val; 5 | * this.left = left === undefined ? null : left; 6 | * this.right = right === undefined ? null : right; 7 | * this.next = next === undefined ? null : next; 8 | * }; 9 | */ 10 | 11 | /** 12 | * @param {Node} root 13 | * @return {Node} 14 | */ 15 | var connect = function(root) { 16 | if(!root) return root; 17 | const queue = [root]; 18 | while(queue.length !== 0) { 19 | let rightNode = null; 20 | const nodeCount = queue.length; 21 | for(let i=nodeCount - 1; i >= 0; i--) { 22 | let node = queue.shift(); 23 | node.next = rightNode; 24 | rightNode = node; 25 | if(node.right) queue.push(node.right); 26 | if(node.left) queue.push(node.left); 27 | } 28 | } 29 | return root; 30 | }; 31 | -------------------------------------------------------------------------------- /PowXN.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @param {number} n 4 | * @return {number} 5 | */ 6 | // TC: O(logN) SC: O(1) 7 | var myPow = function(x, n) { 8 | if(n === 0) return 1; 9 | let isNegative = false; 10 | let result = 1; 11 | if(n < 0) { 12 | isNegative = true; 13 | n *= -1; 14 | } 15 | while(n > 0) { 16 | if(n % 2 === 0) { 17 | x *= x; 18 | n /= 2; 19 | } 20 | else { 21 | result *= x; 22 | n -= 1; 23 | } 24 | } 25 | return (!isNegative) ? result : 1/result; 26 | }; 27 | -------------------------------------------------------------------------------- /PowerOfFour.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 1 ms, faster than 100.00% of Java online submissions for Power of Four. 3 | Memory Usage: 41.6 MB, less than 25.85% of Java online submissions for Power of Four. 4 | */ 5 | class Solution { 6 | public boolean isPowerOfFour(int n) { 7 | // Base Cases For Recursion To Stop 8 | if(n == 1){ 9 | return true; 10 | } 11 | if(n == 0 || n%2 != 0){ 12 | return false; 13 | } 14 | 15 | // Dividing The Number By 4 (Because n == 4^x) 16 | double remainingNumber = n/4.0; 17 | 18 | // Checking for decimal places, if it exists, the number is not a perfect square 19 | if(remainingNumber%1 != 0){ 20 | return false; 21 | } 22 | 23 | // Calling Recursive Function Till Either n == 1 or n == 0 or n%2 != 0 24 | return isPowerOfFour((int)remainingNumber); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /PowerOfThree.java: -------------------------------------------------------------------------------- 1 | // Optimised Solution 2 | /* 3 | Runtime: 15 ms, faster than 95.97% of Java online submissions for Power of Three. 4 | Memory Usage: 42.5 MB, less than 83.84% of Java online submissions for Power of Three. 5 | */ 6 | class Solution { 7 | public boolean isPowerOfThree(int n) { 8 | 9 | if(n < 1){ 10 | return false; 11 | } 12 | 13 | while(n % 3 == 0){ 14 | 15 | n = n / 3; 16 | 17 | } 18 | 19 | return n == 1; 20 | 21 | } 22 | } 23 | 24 | // Brute Force Solution (Recursion) 25 | class Solution { 26 | public boolean isPowerOfThree(int n) { 27 | 28 | if(n == 1){ 29 | return true; 30 | } 31 | if(n == 0){ 32 | return false; 33 | } 34 | 35 | if(n % 3.00 != 0){ 36 | return false; 37 | } 38 | 39 | n = n/3; 40 | 41 | return isPowerOfThree(n); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /PrintBSTElementsInGivenRange.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Node} root 3 | * @param {number} low 4 | * @param {number} high 5 | * @returns {number[]} 6 | */ 7 | 8 | 9 | class Solution 10 | { 11 | //Function to return a list of BST elements in a given range. 12 | printNearNodes(root, low, high) 13 | { 14 | //your code here 15 | const findRange = (root) => { 16 | const result = []; 17 | const inorder = (root) => { 18 | if(!root) return; 19 | inorder(root.left); 20 | if(root.data >=low && root.data <= high) 21 | result.push(root.data); 22 | else if(root.data > high) return; 23 | inorder(root.right); 24 | } 25 | inorder(root); 26 | return result; 27 | } 28 | return (findRange(root)) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ProductOfArrayExceptSelf.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var productExceptSelf = function(nums) { 7 | const result = [1]; 8 | let right = 1; 9 | for(let i=0;i=0; i--) { 14 | result[i] = right * result[i]; 15 | right *= nums[i]; 16 | } 17 | return result; 18 | }; 19 | 20 | 21 | /** 22 | * @param {number[]} nums 23 | * @return {number[]} 24 | */ 25 | // TC: O(N) SC: O(N) 26 | var productExceptSelf = function(nums) { 27 | const left = [1]; 28 | const right = []; 29 | const result = []; 30 | right[nums.length - 1] = 1; 31 | for(let i=1; i=0; i--) { 35 | right[i] = nums[i + 1] * right[i + 1]; 36 | } 37 | for(let i=0; i a - b); 13 | const squares = arr.map((num) => num * num); 14 | 15 | for(let i=n-1; i>=0; i--) { 16 | let j = 0; 17 | let k = i - 1; 18 | while(j < k) { 19 | if(squares[j] + squares[k] === squares[i]) return true; 20 | else if(squares[j] + squares[k] <= squares[i]) j++; 21 | else k--; 22 | } 23 | } 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /RansomNote.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 2 ms, faster than 99.48% of Java online submissions for Ransom Note. 3 | Memory Usage: 42.4 MB, less than 96.37% of Java online submissions for Ransom Note. 4 | */ 5 | class Solution { 6 | public boolean canConstruct(String ransomNote, String magazine) { 7 | int[] charCount = new int[26]; 8 | for(char s : magazine.toCharArray()){ 9 | charCount[s - 'a']++; 10 | } 11 | for(char s : ransomNote.toCharArray()){ 12 | if(charCount[s - 'a'] <= 0){ 13 | return false; 14 | }else{ 15 | charCount[s - 'a']--; 16 | } 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RansomNote.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} ransomNote 3 | * @param {string} magazine 4 | * @return {boolean} 5 | */ 6 | var canConstruct = function(ransomNote, magazine) { 7 | const charArray = new Array(26).fill(0); 8 | for(let ch of magazine) { 9 | charArray[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++; 10 | } 11 | for(let ch of ransomNote) { 12 | charArray[ch.charCodeAt(0) - 'a'.charCodeAt(0)]--; 13 | if(charArray[ch.charCodeAt(0) - 'a'.charCodeAt(0)] < 0) return false; 14 | } 15 | return true; 16 | }; 17 | -------------------------------------------------------------------------------- /RearrangeArrayAlternatively.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | */ 5 | 6 | class Solution { 7 | //Function to rearrange the array elements alternately. 8 | rearrange(nums, n){ 9 | // code here 10 | const max = nums[n - 1] + 1; 11 | let minIndex = 0; 12 | let maxIndex = n - 1; 13 | for(let i=0; i nums.length === 0; 8 | const peek = nums => nums[nums.length - 1]; 9 | 10 | const stack = []; 11 | let result = ''; 12 | 13 | for(const str of string) !isEmpty(stack) && str === peek(stack) ? stack.pop() : stack.push(str); 14 | 15 | return stack.join(''); 16 | 17 | }; 18 | -------------------------------------------------------------------------------- /RemoveAllDuplicatesFromAGivenString.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} n 3 | * @return {string} 4 | */ 5 | 6 | class Solution { 7 | removeDuplicates(str){ 8 | //code here 9 | const set = new Set(); 10 | let result = ''; 11 | for(let i=0; i { 9 | if(el !== val) { 10 | const temp = nums[index]; 11 | nums[index] = el; 12 | nums[i] = temp; 13 | index++; 14 | } 15 | }); 16 | return index; 17 | }; 18 | 19 | 20 | // Beats 94.34%of users with JavaScript 21 | const removeElement = (nums, val) => { 22 | for(let i=0; i a - b); 7 | const result = []; 8 | const queue = deck.map((_, i) => i); 9 | deck.forEach((card) => { 10 | const idx = queue.shift(); 11 | result[idx] = card; 12 | if(queue.length > 0) { 13 | queue.push(queue.shift()); 14 | } 15 | }); 16 | return result; 17 | }; 18 | -------------------------------------------------------------------------------- /ReverseLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {ListNode} 11 | */ 12 | var reverseList = function(head) { 13 | let prev = null; 14 | while(head) { 15 | const nextNode = head.next; 16 | head.next = prev; 17 | prev = head; 18 | head = nextNode; 19 | } 20 | return prev; 21 | }; 22 | -------------------------------------------------------------------------------- /ReverseLinkedListII.js: -------------------------------------------------------------------------------- 1 | * Definition for singly-linked list. 2 | /* 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @param {number} left 11 | * @param {number} right 12 | * @return {ListNode} 13 | */ 14 | var reverseBetween = function(head, left, right) { 15 | let previousNode = null; 16 | let traverseNode = head; 17 | while(left > 1) { 18 | previousNode = traverseNode; 19 | traverseNode = traverseNode.next; 20 | left--; 21 | right--; 22 | } 23 | let connection = previousNode; 24 | let tail = traverseNode; 25 | let prev = null; 26 | while(right > 0) { 27 | const temp = traverseNode.next; 28 | traverseNode.next = prev; 29 | prev = traverseNode; 30 | traverseNode = temp; 31 | right--; 32 | } 33 | if(connection) connection.next = prev; 34 | else head = prev; 35 | tail.next = traverseNode; 36 | return head; 37 | }; 38 | -------------------------------------------------------------------------------- /ReverseNodesInKGroup.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @param {number} k 11 | * @return {ListNode} 12 | */ 13 | var reverseKGroup = function(head, k) { 14 | let count = 0; 15 | let node = head; 16 | while(node && count !== k) { 17 | node = node.next; 18 | count++; 19 | } 20 | if(count === k) { 21 | node = reverseKGroup(node, k); 22 | while(count > 0) { 23 | let temp = head.next; 24 | head.next = node; 25 | node = head; 26 | head = temp; 27 | count--; 28 | } 29 | head = node; 30 | } 31 | return head; 32 | }; 33 | -------------------------------------------------------------------------------- /ReverseString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | for(int i=0; i<=(s.length-1)/2; i++){ 4 | char ch = s[i]; 5 | s[i] = s[s.length-1-i]; 6 | s[s.length-1-i] = ch; 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ReverseString.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {character[]} s 3 | * @return {void} Do not return anything, modify s in-place instead. 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var reverseString = function(s) { 7 | const n = s.length - 1; 8 | for(let i=0; i<=Math.floor(n / 2); i++) { 9 | const tempChar = s[i]; 10 | s[i] = s[n - i]; 11 | s[n - i] = tempChar; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /ReverseWordsInAGivenString.js: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to reverse words in a given string. 4 | reverseWords(s) 5 | { 6 | // code here 7 | const result = s.split('.').reverse().join('.'); 8 | return result; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /RomanToInteger.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | 4 | HashMap map = new HashMap<>(); 5 | map.put('I', 1); 6 | map.put('V', 5); 7 | map.put('X', 10); 8 | map.put('L', 50); 9 | map.put('C', 100); 10 | map.put('D', 500); 11 | map.put('M', 1000); 12 | 13 | int res = 0; 14 | 15 | for(int i=0; i0 && map.get(s.charAt(i)) > map.get(s.charAt(i-1))){ 18 | res += map.get(s.charAt(i)) - 2*map.get(s.charAt(i-1)); 19 | }else{ 20 | res += map.get(s.charAt(i)); 21 | } 22 | } 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /RotateArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {void} Do not return anything, modify nums in-place instead. 5 | */ 6 | // TC: O(N) SC: O(1) 7 | var rotate = function(nums, k) { 8 | const rotate = (start, end) => { 9 | while(start < end) { 10 | const temp = nums[start]; 11 | nums[start] = nums[end]; 12 | nums[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | k %= nums.length; 18 | const pivotIdx = nums.length - k - 1; 19 | // First Rotation 20 | rotate(0, pivotIdx); 21 | //Second Rotation 22 | rotate(pivotIdx + 1, nums.length - 1); 23 | // Final Rotation 24 | rotate(0, nums.length - 1); 25 | }; 26 | -------------------------------------------------------------------------------- /RotateImage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | // TC: O(n^2) SC: O(1) 6 | var rotate = function(matrix) { 7 | const reverse = (nums) => { 8 | let start = 0, end = nums.length - 1; 9 | while(start < end) { 10 | const temp = nums[start]; 11 | nums[start] = nums[end]; 12 | nums[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | for(let i=0; i 1) { 28 | traverseNode = traverseNode.next; 29 | rotations--; 30 | } 31 | 32 | head = traverseNode.next; 33 | traverseNode.next = null; 34 | return head; 35 | 36 | }; 37 | -------------------------------------------------------------------------------- /RotateListGFG.js: -------------------------------------------------------------------------------- 1 | /* 2 | class Node{ 3 | constructor(data){ 4 | this.data = data; 5 | this.next = null; 6 | } 7 | } 8 | */ 9 | 10 | class Solution { 11 | //Function to rotate a linked list. 12 | rotate(head, k) 13 | { 14 | //your code here 15 | if(!head && !head.next) return head; 16 | let traverseNode = head; 17 | let size = 1; 18 | while(traverseNode && traverseNode.next) { 19 | traverseNode = traverseNode.next; 20 | size++; 21 | } 22 | if(size === k) return head; 23 | k = k % size; 24 | traverseNode.next = head; 25 | traverseNode = traverseNode.next; 26 | let rotations = k; 27 | 28 | while(rotations > 1) { 29 | traverseNode = traverseNode.next; 30 | rotations--; 31 | } 32 | 33 | head = traverseNode.next; 34 | traverseNode.next = null; 35 | return head; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /RotateString.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} goal 4 | * @return {boolean} 5 | */ 6 | // TC: O(N) SC: O(N) 7 | var rotateString = function(s, goal) { 8 | if(s.length !== goal.length) return false; 9 | const sDouble = s + s; 10 | for(let i=0; i { 12 | while(start <= end) { 13 | const mid = start + Math.floor((end - start) / 2); 14 | if(nums[mid] === 1) { 15 | end = mid - 1; 16 | } 17 | else { 18 | start = mid + 1; 19 | } 20 | } 21 | return start; 22 | } 23 | let maxOne = 0; 24 | let count = Infinity; 25 | for(let i=0; i= m ? -1 : maxOne; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /RunningSumof1dArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] runningSum(int[] nums) { 3 | int sum = 0; 4 | for(int i=0; i val) return searchBST(root.left, val); 18 | else return searchBST(root.right, val); 19 | }; 20 | -------------------------------------------------------------------------------- /SearchInRotatedSortedArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | // TC: O(logN) SC: O(1) 7 | var search = function(nums, target) { 8 | const binarySearch = (nums, start, end, target) => { 9 | while(start <= end) { 10 | const mid = start + Math.floor((end - start) / 2); 11 | if(nums[mid] === target) return mid; 12 | else if(nums[mid] < target) start = mid + 1; 13 | else end = mid - 1; 14 | } 15 | return -1; 16 | } 17 | const pivot = ((start, end) => { 18 | while(start < end){ 19 | const mid = start + Math.floor((end - start) / 2); 20 | if(nums[mid] < nums[end]) end = mid; 21 | else start = mid + 1; 22 | } 23 | return start; 24 | })(0, nums.length - 1); 25 | if(target <= nums[nums.length - 1]) return binarySearch(nums, pivot, nums.length - 1, target); 26 | else return binarySearch(nums, 0, pivot - 1, target); 27 | }; 28 | -------------------------------------------------------------------------------- /SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 0 ms, faster than 100.00% of Java online submissions for Search Insert Position. 3 | Memory Usage: 41.8 MB, less than 90.75% of Java online submissions for Search Insert Position. 4 | */ 5 | class Solution { 6 | public int searchInsert(int[] nums, int target) { 7 | 8 | int start = 0; 9 | int end = nums.length - 1; 10 | 11 | while(start <= end){ 12 | 13 | int mid = start + (end - start) / 2; 14 | 15 | if(nums[mid] >= target){ 16 | end = mid - 1; 17 | }else{ 18 | start = mid + 1; 19 | } 20 | 21 | } 22 | 23 | return start; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SearchInsertPosition.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | var searchInsert = function(nums, target) { 7 | let start = 0, end = nums.length; 8 | while(start < end) { 9 | const mid = start + Math.floor((end - start) / 2); 10 | if(nums[mid] === target) return mid; 11 | if(nums[mid] < target) start = mid + 1; 12 | else end = mid; 13 | } 14 | return start; 15 | }; 16 | -------------------------------------------------------------------------------- /SetMatrixZeroes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var setZeroes = function(matrix) { 7 | 8 | let isColZero = false; 9 | const rows = matrix.length; 10 | const cols = matrix[0].length; 11 | 12 | for(let i=0; i=0; i--) { 22 | for(let j=cols - 1; j>0; j--) { 23 | if(matrix[i][0] === 0 || matrix[0][j] === 0) { 24 | matrix[i][j] = 0; 25 | } 26 | } 27 | if(isColZero) matrix[i][0] = 0; 28 | } 29 | 30 | }; 31 | -------------------------------------------------------------------------------- /ShuffleTheArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} n 4 | * @return {number[]} 5 | */ 6 | var shuffle = function(nums, n) { 7 | if(nums.length === 1) return nums; 8 | const result = []; 9 | let odd = 1; 10 | let even = 0; 11 | const mid = Math.floor(2*n / 2); 12 | nums.forEach((num, i) => { 13 | 14 | if(i < mid) { 15 | result[even] = num; 16 | even += 2; 17 | } 18 | else { 19 | result[odd] = num; 20 | odd += 2; 21 | } 22 | 23 | }) 24 | return result; 25 | }; 26 | -------------------------------------------------------------------------------- /SingleNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNumber(int[] nums) { 3 | int ans = nums[0]; 4 | for(int i = 1; i< nums.length;i++) { 5 | ans ^= nums[i]; 6 | } 7 | return ans; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Sleep.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} millis 3 | */ 4 | async function sleep(millis) { 5 | return new Promise(resolve => setTimeout(resolve, millis)); 6 | } 7 | -------------------------------------------------------------------------------- /SmallestEvenMultiple.java: -------------------------------------------------------------------------------- 1 | // TC : O(1) SC : O(1) 2 | class Solution { 3 | public int smallestEvenMultiple(int n) { 4 | 5 | // If n gives 0 as a remainder when divided by 2, we simply return n 6 | if(n%2 == 0){ 7 | return n; 8 | } 9 | // If not, then we return 2 multiplied by n as the result 10 | else{ 11 | return 2*n; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /SmallestNumberInInfiniteSet.js: -------------------------------------------------------------------------------- 1 | class SmallestInfiniteSet { 2 | constructor() { 3 | this.nums = new Array(1001).fill(true); 4 | } 5 | popSmallest() { 6 | for(let i=1; i a - b); 8 | let left = 1; 9 | let right = nums.length; 10 | while(left <= right) { 11 | const mid = Math.floor(left + (right - left) / 2); 12 | let count = 0; 13 | for(let i=0; i s) 7 | { 8 | //add code here. 9 | s.push(a); 10 | min = Math.min(min, a); 11 | } 12 | public int pop(Stack s) 13 | { 14 | //add code here. 15 | if(s.isEmpty()){ 16 | return -1; 17 | } 18 | return s.pop(); 19 | } 20 | public int min(Stack s) 21 | { 22 | //add code here. 23 | if(s.isEmpty()) return 0; 24 | 25 | return min; 26 | } 27 | public boolean isFull(Stacks, int n) 28 | { 29 | //add code here. 30 | if(s.size() == n){ 31 | return true; 32 | } 33 | return false; 34 | } 35 | public boolean isEmpty(Stacks) 36 | { 37 | //add code here. 38 | if(s.size()==0){ 39 | return true; 40 | } 41 | 42 | return false; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /SpiralMatrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number[]} 4 | */ 5 | var spiralOrder = function(matrix) { 6 | let rowStart = 0, rowEnd = matrix.length - 1; 7 | let colStart = 0, colEnd = matrix[0].length - 1; 8 | const result = []; 9 | while(rowStart <= rowEnd && colStart <= colEnd) { 10 | // Moving East 11 | for(let i=colStart; i <=colEnd; i++) result.push(matrix[rowStart][i]); 12 | rowStart++; 13 | 14 | // Moving South 15 | for(let i=rowStart; i <=rowEnd; i++) result.push(matrix[i][colEnd]); 16 | colEnd--; 17 | 18 | if(rowStart > rowEnd || colStart > colEnd) break; 19 | 20 | // Moving West 21 | for(let i=colEnd; i >= colStart; i--) result.push(matrix[rowEnd][i]); 22 | rowEnd--; 23 | 24 | if(rowStart > rowEnd || colStart > colEnd) break; 25 | 26 | // Moving North 27 | for(let i=rowEnd; i >= rowStart; i--) result.push(matrix[i][colStart]); 28 | colStart++; 29 | } 30 | return result; 31 | }; 32 | -------------------------------------------------------------------------------- /SpiralMatrixII.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number[][]} 4 | */ 5 | var generateMatrix = function(n) { 6 | const matrixLength = n; 7 | let num = 1; 8 | const result = []; 9 | for(let i=0; i=colStart; i--) { 29 | result[rowEnd][i] = num; 30 | num++; 31 | } 32 | rowEnd--; 33 | for(let i=rowEnd; i>=rowStart; i--) { 34 | result[i][colStart] = num; 35 | num++; 36 | } 37 | colStart++; 38 | } 39 | return result; 40 | }; 41 | -------------------------------------------------------------------------------- /SqrtX.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var mySqrt = function(x) { 6 | let start = 1, end = Math.floor(x / 2); 7 | if(x === 1) return 1; 8 | while(start <= end) { 9 | const mid = start + Math.floor((end - start) / 2); 10 | if(mid * mid === x) return mid; 11 | else if(mid * mid < x) start = mid + 1; 12 | else if(mid * mid > x) end = mid - 1; 13 | 14 | } 15 | return start-1; 16 | }; 17 | -------------------------------------------------------------------------------- /SquaresOfASortedArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sortedSquares(int[] nums) { 3 | int[]ans = new int[nums.length]; 4 | int start = 0, end = nums.length-1; 5 | int index = end; 6 | 7 | while(start<=end){ 8 | if(nums[start]*nums[start] > nums[end]*nums[end]){ 9 | ans[index] = nums[start]*nums[start]; 10 | index--; 11 | start++; 12 | }else{ 13 | ans[index] = nums[end]*nums[end]; 14 | index--; 15 | end--; 16 | } 17 | } 18 | 19 | return ans; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /SubarraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraySum(int[] nums, int k) { 3 | 4 | HashMap map = new HashMap<>(); 5 | map.put(0,1); 6 | int count = 0; 7 | int sum = 0; 8 | 9 | for(int i=0; i { 11 | sum += num; 12 | if(map.has(sum - k)) { 13 | count += map.get(sum - k); 14 | } 15 | map.set(sum, (map.get(sum) || 0) + 1); 16 | }); 17 | return count; 18 | }; 19 | -------------------------------------------------------------------------------- /SubarrayWith0Sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @returns {boolean} 5 | */ 6 | class Solution { 7 | //Function to check whether there is a subarray present with 0-sum or not. 8 | subArrayExists(arr, n){ 9 | // code here 10 | const set = new Set(); 11 | let sum = 0; 12 | 13 | for(let i=0; i { 19 | 20 | 21 | if(num === 0) currentSum--; 22 | else currentSum++; 23 | 24 | if(currentSum === 0) count++; 25 | 26 | if(map.has(currentSum)) { 27 | count += map.get(currentSum); 28 | map.set(currentSum, map.get(currentSum) + 1); 29 | } 30 | else { 31 | map.set(currentSum, 1); 32 | } 33 | 34 | 35 | }); 36 | 37 | return count; 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Subsets.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 0 ms, faster than 100.00% of Java online submissions for Subsets. 3 | Memory Usage: 42.2 MB, less than 96.08% of Java online submissions for Subsets. 4 | */ 5 | 6 | // TC: O(N * 2^N) SC: O(N) 7 | class Solution { 8 | public List> subsets(int[] nums) { 9 | 10 | List> result = new ArrayList<>(); 11 | backtracking(0, nums, new ArrayList(), result); 12 | return result; 13 | 14 | } 15 | 16 | void backtracking(int index, int[] nums, List current, List> result){ 17 | 18 | result.add(new ArrayList<>(current)); 19 | 20 | for(int i = index; i < nums.length; i++){ 21 | 22 | current.add(nums[i]); 23 | backtracking(i + 1, nums, current, result); 24 | current.remove(current.size() - 1); 25 | 26 | } 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Subsets.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var subsets = function(nums) { 6 | const result = []; 7 | const backtrack = (currentIdx, store) => { 8 | if(store.length > nums.length) return; 9 | result.push([...store]); 10 | for(let i=currentIdx; i a - b); 7 | 8 | const result = []; 9 | 10 | const backtrack = (currentIdx, store) => { 11 | if(store.length > nums.length) return; 12 | result.push([...store]); 13 | for(let i=currentIdx; i { 16 | if(!root && !subRoot) return true; 17 | if(!root || !subRoot) return false; 18 | if(root.val !== subRoot.val) return false; 19 | return isIdenticalSubRoot(root.left, subRoot.left) && isIdenticalSubRoot(root.right, subRoot.right); 20 | } 21 | var isSubtree = function(root, subRoot) { 22 | if(!root && !subRoot) return true; 23 | if(!root || !subRoot) return false; 24 | if(isIdenticalSubRoot(root, subRoot)) { 25 | return true; 26 | } 27 | return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); 28 | }; 29 | -------------------------------------------------------------------------------- /SumOfNumberAndItsReverse.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean sumOfNumberAndReverse(int num) { 3 | for(int i=0; i<=num; i++){ 4 | 5 | StringBuilder str = new StringBuilder(); 6 | str.append(i+""); 7 | String t = str.toString(); 8 | str.reverse(); 9 | 10 | int palin1 = Integer.parseInt(str.toString()); 11 | int palin2 = Integer.parseInt(t); 12 | 13 | if(palin1 + palin2 == num){ 14 | return true; 15 | } 16 | 17 | } 18 | 19 | return false; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /SwapNodesInPairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {ListNode} 11 | */ 12 | 13 | var swapPairs = function(head) { 14 | let result = new ListNode(0); 15 | result.next = head; 16 | 17 | let resultPointer = result; 18 | 19 | while(resultPointer.next && resultPointer.next.next) { 20 | let firstNode = resultPointer.next; 21 | let secondNode = resultPointer.next.next; 22 | firstNode.next = secondNode.next; 23 | resultPointer.next = secondNode; 24 | resultPointer.next.next = firstNode; 25 | resultPointer = resultPointer.next.next; 26 | } 27 | return result.next; 28 | }; 29 | -------------------------------------------------------------------------------- /SymmetricTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | /** 10 | * @param {TreeNode} root 11 | * @return {boolean} 12 | */ 13 | 14 | const detectSymm = (left, right) => { 15 | if(!left && !right) return true; 16 | if(!left || !right) return false; 17 | return (left.val === right.val) && detectSymm(left.left, right.right) && detectSymm(left.right, right.left); 18 | } 19 | 20 | var isSymmetric = function(root) { 21 | return detectSymm(root, root); 22 | }; 23 | -------------------------------------------------------------------------------- /TakingInputFromConsoleJS.js: -------------------------------------------------------------------------------- 1 | const readline = require('readline'); 2 | 3 | const rl = readline.createInterface({ 4 | input: process.stdin 5 | }); 6 | const data = []; 7 | rl.on('line', (inputData) => { 8 | data.push(inputData); 9 | }); 10 | 11 | rl.on('close', () => { 12 | console.log(data); 13 | }); 14 | -------------------------------------------------------------------------------- /TheNumberOfWeakCharactersInTheGame.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfWeakCharacters(int[][] prop) { 3 | 4 | //if attack same then decreasing order of defense else increasing order of attack 5 | Arrays.sort(prop,(a,b)-> a[0]==b[0]? b[1]-a[1] : a[0]-b[0]); 6 | 7 | int min=Integer.MIN_VALUE; 8 | int ans=0; 9 | 10 | for(int i=prop.length-1;i>=0;i--){ 11 | int[] arr=prop[i]; 12 | int att=arr[0]; 13 | int def=arr[1]; 14 | 15 | if(def 0) { 10 | count++; 11 | } 12 | else { 13 | count = 0; 14 | } 15 | if(count === 3) return true; 16 | } 17 | return false; 18 | }; 19 | -------------------------------------------------------------------------------- /ToeplitzMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Runtime: 1 ms, faster than 93.83% of Java online submissions for Toeplitz Matrix. 3 | Memory Usage: 41.9 MB, less than 99.84% of Java online submissions for Toeplitz Matrix. 4 | */ 5 | // Simple TC: O(N*M) SC: O(1) Solution 6 | class Solution { 7 | public boolean isToeplitzMatrix(int[][] matrix) { 8 | int rowLength = matrix.length; 9 | int colLength = matrix[0].length; 10 | 11 | for(int i=0; i 0 && j > 0 && matrix[i][j] != matrix[i-1][j-1]){ 14 | return false; 15 | } 16 | } 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /TwoSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | Map seen = new HashMap<>(); 4 | int remaining = 0; 5 | for(int i =0;i=0; i--) { 37 | for(let j=n-2; j>=0; j--) { 38 | dp[i][j] = dp[i + 1][j] + dp[i][j + 1]; 39 | } 40 | } 41 | return dp[0][0]; 42 | }; 43 | -------------------------------------------------------------------------------- /ValidAnagram.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isAnagram(String s, String t) { 3 | int[] charCount = new int[26]; 4 | for(char c : s.toCharArray()){ 5 | charCount[c-'a']++; 6 | } 7 | int[] charCountT = new int[26]; 8 | for(char c : t.toCharArray()){ 9 | charCountT[c-'a']++; 10 | } 11 | for(int i=0; i<26; i++){ 12 | if(charCount[i] != charCountT[i]){ 13 | return false; 14 | } 15 | } 16 | return true; 17 | } 18 | } 19 | 20 | 21 | /* 22 | class Solution { 23 | public boolean isAnagram(String s, String t) { 24 | char[] str = s.toCharArray(); 25 | char[] ttr = t.toCharArray(); 26 | 27 | Arrays.sort(str); 28 | Arrays.sort(ttr); 29 | String sol1 = new String(str); 30 | String sol2 = new String(ttr); 31 | 32 | if(sol1.equals(sol2)) 33 | return true; 34 | 35 | else return false; 36 | } 37 | } 38 | 39 | */ 40 | -------------------------------------------------------------------------------- /ValidAnagram.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} t 4 | * @return {boolean} 5 | */ 6 | var isAnagram = function(s, t) { 7 | const charArray = new Array(26).fill(0); 8 | if(s.length !== t.length) return false; 9 | for(let i=0; i el === 0); 16 | }; 17 | -------------------------------------------------------------------------------- /ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(String s) { 3 | String res = ""; 4 | for(char c : s.toCharArray()){ 5 | if(Character.isDigit(c) || Character.isLetter(c)){ 6 | res = res + c; 7 | } 8 | } 9 | 10 | res = res.toLowerCase(); 11 | 12 | int leftPointer = 0; 13 | int rightPointer = res.length()-1; 14 | 15 | while(leftPointer <= rightPointer){ 16 | if(res.charAt(leftPointer) != res.charAt(rightPointer)){ 17 | return false; 18 | } 19 | 20 | leftPointer++; 21 | rightPointer--; 22 | 23 | } 24 | 25 | return true; 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ValidPalindrome.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | // TC: O(N) SC: O(1) 6 | var isPalindrome = function(s) { 7 | const isLetter = (ch) => (ch.charCodeAt(0) >= 97 && ch.charCodeAt(0) <= 122) ? true : false; 8 | const isDigit = (ch) => (ch.charCodeAt(0) >= 48 && ch.charCodeAt(0) <= 57) ? true : false; 9 | 10 | s = s.toLowerCase(); 11 | let start = 0, end = s.length - 1; 12 | 13 | while(start < end) { 14 | if((isLetter(s[start]) || isDigit(s[start])) && (isLetter(s[end]) || isDigit(s[end]))) { 15 | if(s[start] !== s[end]) { 16 | return false; 17 | } 18 | else { 19 | start++; 20 | end--; 21 | } 22 | } 23 | else if(!(isLetter(s[start]) || isDigit(s[start]))) { 24 | start++; 25 | } 26 | else if(!(isLetter(s[end]) || isDigit(s[end]))) { 27 | end--; 28 | } 29 | } 30 | return true; 31 | }; 32 | -------------------------------------------------------------------------------- /ValidPalindromeII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean validPalindrome(String s) { 3 | int i=0,j=s.length()-1; 4 | while(i stack[stack.length - 1]; 8 | const isEmpty = () => stack.length === 0; 9 | for(let c of s) { 10 | if(c === '(' || c === '{' || c === '[') stack.push(c); 11 | else if(c === ')' && peek() === '(') stack.pop(); 12 | else if(c === '}' && peek() === '{') stack.pop(); 13 | else if(c === ']' && peek() === '[') stack.pop(); 14 | else return false; 15 | } 16 | return isEmpty(); 17 | }; 18 | -------------------------------------------------------------------------------- /ValidPerfectSquare.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @return {boolean} 4 | */ 5 | 6 | const isPerfectSquare = (num) => { 7 | if(num === 1) return true; 8 | let start = 1, end = Math.floor(num / 2); 9 | while(start <= end) { 10 | const mid = start + Math.floor((end - start) / 2); 11 | if(mid * mid === num) return true; 12 | else if(mid * mid < num) start = mid + 1; 13 | else end = mid - 1; 14 | } 15 | return false; 16 | } 17 | 18 | // var isPerfectSquare = function(num) { 19 | // squareRoot = num ** 0.5; 20 | // if(squareRoot === Math.floor(squareRoot)) return true; 21 | // else return false; 22 | // }; 23 | -------------------------------------------------------------------------------- /ValidSudoku.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {character[][]} board 3 | * @return {boolean} 4 | */ 5 | var isValidSudoku = function(board) { 6 | const set = new Set(); 7 | for(let i=0; i 4 || parts.length < 4) return 0; 11 | for(let i=0; i 3 || +part > 255 || 14 | +part === 0 && part.length > 1 || part.length > 1 && part.startsWith('0')) { 15 | return 0; 16 | } 17 | } 18 | return 1; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ValidateBinarySearchTree.js: -------------------------------------------------------------------------------- 1 | var isValidBST = function(root) { 2 | const validateBST = (root, min, max) => { 3 | // Base Case: Empty subtree is valid 4 | if (!root) return true; 5 | 6 | // Current Node Violates BST Property: 7 | if (root.val <= min || root.val >= max) return false; 8 | 9 | // Validate Left Subtree (values must be smaller than the current node) 10 | const leftIsValid = validateBST(root.left, min, root.val); 11 | 12 | // Early Termination (Left subtree is already invalid) 13 | if (!leftIsValid) return false; 14 | 15 | // Validate Right Subtree (values must be larger than the current node) 16 | return validateBST(root.right, root.val, max); 17 | } 18 | 19 | // Initial Value Ranges: 20 | const min = -Infinity; 21 | const max = Infinity; 22 | 23 | // Start Validation: 24 | return validateBST(root, min, max); 25 | }; 26 | -------------------------------------------------------------------------------- /ValueEqualToIndexValue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} n 4 | * @returns {number[]} 5 | */ 6 | 7 | class Solution{ 8 | valueEqualToIndex(arr,n){ 9 | //code here 10 | return arr.filter((e, i) => e === i + 1); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /WaveArray.js: -------------------------------------------------------------------------------- 1 | // TC: O(N) SC: O(1) 2 | class Solution { 3 | constructor(arr = []) { 4 | this.arr = arr; 5 | this.n = arr.length; 6 | } 7 | 8 | /** 9 | * @param {number[]} arr 10 | * return {void} 11 | */ 12 | convertToWave(arr) 13 | { 14 | // your code here 15 | const swap = (nums, i, j) => { 16 | const temp = nums[i]; 17 | nums[i] = nums[j]; 18 | nums[j] = temp; 19 | } 20 | 21 | for(let i=0; i 0 && row < numRows - 1 && middleCharIndex < s.length) { 23 | result += s[middleCharIndex]; 24 | } 25 | } 26 | } 27 | 28 | return result; 29 | }; 30 | --------------------------------------------------------------------------------