├── AllOoneDataStructure.java ├── AllPathsSourceToEndGraph.java ├── AlternatingGroupsII.java ├── ApplyOperationsToAnArray.java ├── ArrayPeak.java ├── ArrayPermutation.java ├── ArraySubset.java ├── BalancedParanthesis.java ├── BellmanfordAlgorithm.java ├── BestTimeToBuyAndSell3.java ├── BestTimetoBuyandSellStock.java ├── BitwiseXOROfAllPairings.java ├── BuildAMatrixWithConditions.java ├── CapacityToShipPackagesWithInDDays.java ├── CheapestFlightsWithinKStops.java ├── CheckIfNumberIsASumOfPowersOfThree.java ├── CheckIfOneStringSwapCanMakeStringsEqual.java ├── CheckIfTwoStringsAreEquivalent.java ├── CheckifWordEqualsSummationofTwoWords.java ├── ChocolateDistributionProblem.java ├── ClearDigits.java ├── ClosestPrimeNumbersInRange.java ├── CommanElements.java ├── CommonMatrixElements.java ├── ConstructBinaryTreeFromPreorderAndPostOrder.java ├── ConstructKPalindromeStrings.java ├── ConstructSmallestNumberFromDIString.java ├── ConstructTheLexicographicallyLargestValidSequence.java ├── ContainerWithMostWater.java ├── CountAndSay.java ├── CountInversions.java ├── CountItemsMatchingARule.java ├── CountMoreThanN-K.java ├── CountNumberOfBadPairs.java ├── CountNumberOfMaximumBitwise-ORSubsets.java ├── CountOfSubstringsContainingEveryVowelAndKConsonantsII.java ├── CountPairsWithGivenum.java ├── CountPalindromicSubsequences.java ├── CountPrefixAndSuffixPairs.java ├── CountServersThatCommunicate.java ├── CountSquares.java ├── CountSubIsIland.java ├── CountTheNumberOfCompleteComponents.java ├── CountTheNumberOfConsistentStrings.java ├── CountTheReversals.java ├── CountTotalNumberOfColoredCells.java ├── CountVowelsStringInRanges.java ├── CountandSay.java ├── CousinsInBinaryTreeII.java ├── DefanginganIPAddress.java ├── DeleteNodesFromLinkedListPresentInArray.java ├── DesignANumberContainerSystem.java ├── DesignAStackWithIncrements.java ├── DesignCircularDeque.java ├── DifferentWaystoAddParentheses.java ├── DijkstraAlgorithm.java ├── DivideArrayIntoEqualPairs.java ├── DivideIntervalsIntoMinimumNumberofGroups.java ├── DividePlayersIntoTeamsOfEqualSkills.java ├── DuplicateCount.java ├── ExtraCharactersInAString.java ├── FindElementsInAContaminatedBinaryTree.java ├── FindEventualSafeStates.java ├── FindKthBitInNthBinaryString.java ├── FindMinimumInRotatedSortedArray.java ├── FindMissingAndRepeatedValues.java ├── FindThePrefixCommonArrayOfTwoArrays.java ├── FindThePunishmentNumberOfAnInteger.java ├── FindTheStudentThatWillReplaceTheChalk.java ├── FindUniqueBinaryString.java ├── FindValidMatrixGivenRowAndColumnSums.java ├── FindtheDuplicateNumber.java ├── FindtheNumberOfDistinctColorsAmongTheBalls.java ├── FirstAndLastOccuranceOfElement.java ├── FirstCompletelyPaintedRow.java ├── FirstRepeatedWords.java ├── FirstThreeLargest.java ├── FlipEquivalentBinaryTrees.java ├── FlowerPlantingWithNoAdjacent.java ├── FloydWarshall.java ├── FractionAdditionSubstraction.java ├── GasStation.java ├── HouseRobberIV.java ├── InsertGreatestCommonDivisorsinLinkedList.java ├── IntegerToEnglishWords.java ├── IsGraphBipartite.java ├── IterativeReverseLinkedList.java ├── JewelsAndStones.java ├── Kadane's_Algorithm.java ├── Kahn'sAlgorithm.java ├── KosarajuAlgo.java ├── KruskalsAlgorithm.java ├── KthDistinctStringInAnArray.java ├── KthLargestElementInAStream.java ├── KthLargestSumInABinaryTree.java ├── KthSmallestElementInASortedMatrix.java ├── LargeFactorial.java ├── LargestNumber.java ├── LengthOfLongestFibonacciSubsequence.java ├── LetterTilePossibilities-1.java ├── LetterTilePossibilities.java ├── LexicographicalNumbers.java ├── LinkedListInBinaryTree.java ├── LongerContiguousSegmentsOfOnesThanZeros.java ├── LongestCommonSubsequence.java ├── LongestHappyString.java ├── LongestNiceSubarray.java ├── LowestCommonAncestor.java ├── LuckyNumbersInAMatrix.java ├── MagicSquaresInGrid.java ├── MajorityElementBoyerMooreVoting.java ├── MakeTwoArraysEqualbyReversingSubarrays.java ├── MaxChunksToMakeSortedII.java ├── MaxSumOfAPairWithEqualSumOfDigits.java ├── MaximalScoreAfterApplyingKOperations.java ├── MaximizeTheMinimumGameScore.java ├── MaximumAbsoluteSumOfAnySubarray.java ├── MaximumCountOfPositiveIntegerAndNegativeInteger.java ├── MaximumEmployeesToBeInvitedToAMeeting.java ├── MaximumProductSubarray.java ├── MaximumRectangleInMatrix.java ├── MaximumScoreAfterSplittingAString.java ├── MaximumSwap.java ├── MaximumWidthRamp.java ├── MedianOfRowWiseSortedMatrix.java ├── MedianOfSortedArrays.java ├── MergeIntervals.java ├── MergeSort.java ├── MergeTwo2DArraysBySummingValues.java ├── MergeWithoutExtraSpace.java ├── MiddleOfThree.java ├── MinAddToMakeStringValid.java ├── MinMaxArray.java ├── MinNumberOfFlips.java ├── MinimizeTheHeights.java ├── MinimumAddToMakeParenthesisValid.java ├── MinimumBitFlipsToConvertNumber.java ├── MinimumCostToMakeAtleastOneValidPathInGrid.java ├── MinimumCostWalkInWeightedGraph.java ├── MinimumCosttoConvertStringI.java ├── MinimumLengthofStringAfterOperations.java ├── MinimumNumberOfOperationsToMoveAllBallsToEachBox.java ├── MinimumNumberOfSwapsToMakeStringBalanced.java ├── MinimumNumberofDaystoDisconnectIsland.java ├── MinimumOperationsToExceedThresholdValueII.java ├── MinimumOperationstoMakeBinaryArrayElementsEqualtoOneI.java ├── MinimumRecolorsToGetKConsecutiveBlackBlocks.java ├── MinimumStringLengthAfterRemovingSubstrings.java ├── MinimumSwapsAndKTogether.java ├── MinimumTimeToRepairCars.java ├── Minimum_number_of_jumps.java ├── MissingAndRepeating.java ├── MyCallendar2.java ├── NeighbouringBitwiseXOR.java ├── NetworkDelayTime.java ├── NextGreaterNumberWithSameDigitSum.java ├── NextPermutation.java ├── NumberOfGoodLeafNodes.java ├── NumberOfOperationsToMakeNetworkConnected.java ├── NumberOfSmallestUnoccupiedChair.java ├── NumberOfSubarraysWithOddSum.java ├── NumberOfSubstringsContainingAllThreeCharacters.java ├── NumberOfWaysToSplitArray.java ├── PalindromeString.java ├── PalindromicArray.java ├── ParsingABooleanExpression.java ├── PartitionArrayAccordingToGivenPivot.java ├── PascalTriangle.java ├── PathWithMaximumProbability.java ├── PermutationInString.java ├── PrimsAlgorithm.java ├── PrintNumPadPermutation.java ├── ProductOfTheLastKNumbers.java ├── QueriesOnAPermutationWithKey.java ├── RabinKarp.java ├── RangeSumOfSortedSubarraySums.java ├── RankTransformofanArray.java ├── RatInAMazeProblem.java ├── RearrangeArrayAlternatively.java ├── RearrangeArrayInAlternatingPositions.java ├── RecoveraTreeFromPreorderTraversal.java ├── RedundantConnection.java ├── RegionsCutBySlashes.java ├── RemoveAllOccurrencesOfASubstring.java ├── RemoveConsecutiveCharacters.java ├── ReverseOnlyLetters.java ├── ReverseString.java ├── RomanToInteger.java ├── RotateMatrix90Degree.java ├── RotateStrings.java ├── RowWithMax1s.java ├── SatisfiabilityOfEqualityEquations.java ├── SearchInA2DMatrix.java ├── SearchingInArrayWhereElementsDifferByK.java ├── SecondMinimumTimeToReachDestination.java ├── SecondMostRepeatedString.java ├── SentenceSimilarityIII.java ├── SentenceToNumberPadSequence.java ├── SeparateBlackAndWhiteBalls.java ├── ShiftingLettersII.java ├── ShuffleString.java ├── SmallestRangeCoveringElementsFromKLists.java ├── SmallestWindowThatContainsElements.java ├── SortThePeople.java ├── SortingTheSentence.java ├── SpiralMatrix.java ├── SplitAStringIntoTheMaxNumberOfUniqueSubstrings.java ├── SplitArrayLargestSum.java ├── SplitBinaryString.java ├── SplitLinkedListInParts.java ├── SquareRootUsingBinarySearch.java ├── StringMatchingInAnArray.java ├── StringPermutations.java ├── StringRotations.java ├── StringSubsequences.java ├── StringTransformationByInsertingAtFront.java ├── SubarraySumEqualsK.java ├── SubarraySumGreaterThanX.java ├── SubarrayWithZeroSum.java ├── SubrectangleQueries.java ├── SumOfAllLengthSubarrays.java ├── TargetArrayInGivenOrder.java ├── TextJustification.java ├── ThekthLexicographicalStringOfAllHappyStringsOfLengthN.java ├── ThreeWayPartitioning.java ├── TrappingRainWater.java ├── TrappingRainwater2.java ├── TreeBalancedBinaryTree.java ├── TreeBinaryTreePathToNode.java ├── TreeBinaryTreePaths.java ├── TreeBottomView.java ├── TreeBoundaryTraversalBinaryTree.java ├── TreeDiameter.java ├── TreeInOrderIterative.java ├── TreeInorder.java ├── TreeLeftViewBinaryTree.java ├── TreeLevelOrder.java ├── TreeMaxDepthBinaryTree.java ├── TreeMaximumPathSumBinaryTree.java ├── TreePathToGivenNode.java ├── TreePostOrderIterative.java ├── TreePostorder.java ├── TreePreOrderIterative.java ├── TreePreorder.java ├── TreeRepBinary.java ├── TreeRightViewBinaryTree.java ├── TreeSameTree.java ├── TreeSymmetricBinaryTree.java ├── TreeTopView.java ├── TreeZigZagBinaryTree.java ├── TripletSum.java ├── TupleWithSameProduct.java ├── TwoSumIISortedArray.java ├── UncommonWordsfromTwoSentences.java ├── UniqueLength3PalindromicSubsequence.java ├── ValidParenthesis.java ├── ValueEqualToIndexValue.java ├── WalkingRobotSimulation.java ├── WordsSubsets.java ├── XOROperationInAnArray.java ├── checkIFArrayPairsAreDivisiblebyK.java ├── checkIfParenthesisStringCanBeValid.java ├── convert1DArrayTo2D.java ├── countingWordsWithAGivenString.java ├── courseSchedule4.java ├── divideNodesIntoMaximumNumberOfGroups.java ├── findMissingObservations.java ├── findTheClosestPallindrome.java ├── findTheLengthOfLongestCommonPrefix ├── gridGame.java ├── isomorphicStrings.java ├── largestLocal.java ├── makeLexicographicallySmallestArrayBySwappingElements.java ├── mapOfHighestPeak.java ├── maximumNumberOfFishesInAGrid.java ├── minimizeXor.java ├── minimumAdjacentSwapsForBalanceBrackets.java ├── minimumCostToConvertString1.java ├── minimumSwapsToGroup1sTogether.java ├── minimumTimeDifference.java ├── minimumWindowSubstrin.java ├── minimumWindowSubstring.java ├── modifiedGraphEdges.java ├── myCalendar1.java ├── numberOfAtoms.java ├── shortestCommonSupersequence.java ├── spiralMatrix3.java ├── spiralMatrix4.java ├── sumOfDigitsOfStringAfterConvert.java └── sumOfPrefixScoresOfStrings.java /AllPathsSourceToEndGraph.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public static void backTrack(int graph[][], int element, List> list,List sublist){ 4 | // Base Case 5 | if(element==graph.length-1) 6 | { 7 | list.add(new ArrayList<>(sublist)); 8 | return; 9 | } 10 | 11 | for(int i=0;i> allPathsSourceTarget(int[][] graph) { 20 | List sublist = new ArrayList(); 21 | List> list = new ArrayList>(); 22 | sublist.add(0); 23 | backTrack(graph,0,list,sublist); 24 | return list; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /AlternatingGroupsII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfAlternatingGroups(int[] colors, int k) { 3 | int res=0; 4 | int left=0; 5 | int n = colors.length; 6 | // N+K 7 | for(int right=1;right < (n + k -1); right++){ // exp.. 8 | // skip entire subarray 9 | if(colors[right%n] == colors[(right-1)%n]){ 10 | left = right; 11 | } 12 | if(right - left + 1 == k){ 13 | res++; 14 | left++; // move to next subarray or shrinking phase 15 | } 16 | } 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ApplyOperationsToAnArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] applyOperations(int[] nums) { 3 | int nz=0; 4 | int n = nums.length; 5 | for(int i=0;i=arr[mid-1]) && (mid==n-1 || arr[mid]>=arr[mid+1])) 17 | { 18 | return mid; 19 | } 20 | 21 | else if(mid>0 && arr[mid-1]>arr[mid]) 22 | { 23 | hi=mid-1; 24 | } 25 | 26 | else 27 | { 28 | lo=mid+1; 29 | } 30 | 31 | } 32 | return 0; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ArrayPermutation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> permute(int[] nums) { 3 | List> list = new ArrayList>(); 4 | permute(nums,0,list); 5 | return list; 6 | } 7 | public static void swap(int nums[],int x,int y) 8 | { 9 | int p = nums[x]; 10 | nums[x] = nums[y]; 11 | nums[y] = p; 12 | } 13 | public static void permute(int nums[],int index,List> list) 14 | { 15 | if(index==nums.length-1) 16 | { 17 | List l = new ArrayList<>(); 18 | for(int i=0;i set = new HashSet(); 5 | 6 | for(int i=0;i stack = new Stack(); 31 | for(int i=0;i> edges, int S) { 12 | // Write your code here 13 | int dist[] = new int[V]; 14 | Arrays.fill(dist,(int)1e8); 15 | dist[S] = 0; 16 | for(int i=0;i edge : edges){ 19 | int u = edge.get(0); 20 | int v = edge.get(1); 21 | int w = edge.get(2); 22 | if(dist[u]!=(int)1e8 && dist[u] + w < dist[v]){ 23 | dist[v] = dist[u] + w; 24 | isChanged=true; 25 | } 26 | } 27 | if(!isChanged){ 28 | break; //if cur relation is not chaning any dist then no need to check further! 29 | } 30 | } 31 | 32 | for(ArrayList edge : edges){ 33 | int u = edge.get(0); 34 | int v = edge.get(1); 35 | int w = edge.get(2); 36 | if(dist[u]!=(int)1e8 && dist[u] + w < dist[v]){ 37 | return new int[]{-1}; 38 | // dist[v] = dist[u] + w; 39 | } 40 | } 41 | return dist; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSell3.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | 4 | int n=prices.length; 5 | int left[] = new int[n]; 6 | int right[]= new int[n]; 7 | int lmin=prices[0],rmax=prices[n-1]; 8 | // First purchase 9 | 10 | for(int i=1;i=0;i--) 17 | { 18 | right[i] = Math.max(right[i+1],rmax-prices[i]); 19 | rmax=Math.max(rmax,prices[i]); 20 | } 21 | 22 | int profit=right[0]; 23 | 24 | for(int i=1;iprofit) profit=prices[i]-min; 17 | } 18 | } 19 | return profit; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /BitwiseXOROfAllPairings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int xorAllNums(int[] nums1, int[] nums2) { 3 | // n + m 4 | int n = nums1.length; 5 | int res=0; 6 | if(n%2!=0){ 7 | for(int num : nums2){ 8 | res^=num; 9 | } 10 | } 11 | int m = nums2.length; 12 | if(m%2!=0){ 13 | for(int num : nums1){ 14 | res^=num; 15 | } 16 | } 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CapacityToShipPackagesWithInDDays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(int cap,int weights[],int days,int n) 3 | { 4 | int numDays=0; 5 | int sumOfWeights=0; 6 | for(int i=0;icap) return false; 9 | sumOfWeights+=weights[i]; 10 | if(sumOfWeights>cap) 11 | { 12 | numDays++; 13 | sumOfWeights=weights[i]; 14 | } 15 | } 16 | numDays++; 17 | return numDays<=days; 18 | } 19 | public int shipWithinDays(int[] weights, int days) { 20 | 21 | int minCap=Integer.MIN_VALUE; 22 | int maxCap=0; 23 | for(int i=0;i> adj = new HashMap<>(); 4 | for (int[] i : flights) 5 | adj.computeIfAbsent(i[0], value -> new ArrayList<>()).add(new int[] { i[1], i[2] }); 6 | 7 | int[] stops = new int[n]; 8 | Arrays.fill(stops, Integer.MAX_VALUE); 9 | PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); 10 | // {dist_from_src_node, node, number_of_stops_from_src_node} 11 | pq.offer(new int[] { 0, src, 0 }); 12 | 13 | while (!pq.isEmpty()) { 14 | int[] temp = pq.poll(); 15 | int dist = temp[0]; 16 | int node = temp[1]; 17 | int steps = temp[2]; 18 | if (steps > stops[node] || steps > k + 1) 19 | continue; 20 | stops[node] = steps; 21 | if (node == dst) 22 | return dist; 23 | if (!adj.containsKey(node)) 24 | continue; 25 | for (int[] a : adj.get(node)) { 26 | pq.offer(new int[] { dist + a[1], a[0], steps + 1 }); 27 | } 28 | } 29 | return -1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CheckIfNumberIsASumOfPowersOfThree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkPowersOfThree(int n) { 3 | while(n>0){ 4 | if((n%3) == 2){ 5 | return false; 6 | } 7 | n/=3; 8 | } 9 | return true; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /CheckIfOneStringSwapCanMakeStringsEqual.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean areAlmostEqual(String s1, String s2) { 3 | int count=0; 4 | int i=0; 5 | int j=0; 6 | int n = s1.length(); 7 | for(int p=0;p2) return false; 11 | else{ 12 | if(count == 1) i=p; 13 | else j=p; 14 | } 15 | } 16 | } 17 | return (s1.charAt(i) == s2.charAt(j) 18 | && s2.charAt(i) == s1.charAt(j)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CheckIfTwoStringsAreEquivalent.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean arrayStringsAreEqual(String[] word1, String[] word2) { 3 | StringBuilder w1 = new StringBuilder(); 4 | StringBuilder w2 = new StringBuilder(); 5 | for(String s1: word1) w1.append(s1); 6 | for(String s2: word2) w2.append(s2); 7 | return w1.toString().equals(w2.toString()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CheckifWordEqualsSummationofTwoWords.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public boolean isSumEqual(String firstWord, String secondWord, String targetWord) 4 | { 5 | return (findVal(firstWord) + findVal(secondWord) == findVal(targetWord)); 6 | 7 | } 8 | public static int findVal(String word) 9 | { 10 | String n1=""; 11 | for(int i=0;i a, long n, long m) 4 | { 5 | // your code here 6 | Collections.sort(a); 7 | long minDiff = Long.MAX_VALUE; 8 | for(int i=0;i+m-1 O(R log(logR)) 11 | for (int p = 2; p * p <= right; p++) { 12 | if (prime[p]) { 13 | for (int i = p * p; i <= right; i += p) 14 | prime[i] = false; 15 | } 16 | } 17 | // R-L 18 | // find min diff b/w pair of prime numbers 19 | int res[] = new int[]{-1,-1}; 20 | int minDiff = Integer.MAX_VALUE; 21 | int prev=-1; 22 | for (int i = left; i <= right; i++) { 23 | if (prime[i]){ 24 | if(prev == -1){ 25 | prev = i; 26 | }else{ 27 | if(i - prev < minDiff){ 28 | res[0] = prev; 29 | res[1] = i; 30 | minDiff = i-prev; 31 | } 32 | prev=i; 33 | } 34 | } 35 | } 36 | return res; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /CommanElements.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | ArrayList commonElements(int A[], int B[], int C[], int n1, int n2, int n3) 4 | { 5 | // code here 6 | // Declare an Array list to store results 7 | ArrayList arr = new ArrayList<>(); 8 | int i=0,j=0,k=0; 9 | while(iB[j]) j++; 13 | else 14 | { 15 | // This is for checking duplicacy 16 | if(i>0 && A[i]==A[i-1]) 17 | { 18 | i++; 19 | continue; 20 | } 21 | // Now we will search the common element in third array! 22 | // k map = new HashMap<>(); 18 | public TreeNode constructFromPrePost(int[] preorder, int[] postorder) { 19 | int n = postorder.length; 20 | for(int i=0;ii2 || j1>j2){ 29 | return null; 30 | } 31 | TreeNode root = new TreeNode(preorder[i1]); 32 | if(i1 == i2){ 33 | return root; 34 | } 35 | // find preorder[i1 + 1] in postorder 36 | int r = map.get(preorder[i1+1]); 37 | int size = r-j1+1; 38 | root.left = recur(i1+1, i1 + size, j1, r, preorder, postorder); 39 | root.right = recur(i1+size+1, i2, r+1, j2-1, preorder, postorder); 40 | return root; 41 | } 42 | 43 | } 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /ConstructKPalindromeStrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canConstruct(String s, int k) { 3 | int n = s.length(); 4 | if(n < k) return false; 5 | if(n == k) return true; 6 | //find freq 7 | int count[] = new int[26]; 8 | for(int i=0;i pattern.length()) { 14 | for (int i = 0; i < num.length; i++) { 15 | result.append(num[i]); 16 | } 17 | return true; // Found the valid lexicographically smallest number 18 | } 19 | 20 | for (int digit = 1; digit <= 9; digit++) { 21 | if (!used[digit] && (index == 0 || isValid(num[index - 1], digit, pattern.charAt(index - 1)))) { 22 | used[digit] = true; 23 | num[index] = digit; 24 | if (backtrack(pattern, index + 1, num, used, result)) { 25 | return true; 26 | } 27 | num[index] = 0; 28 | used[digit] = false; // Backtrack 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | private boolean isValid(int lastDigit, int currentDigit, char condition) { 35 | return (condition == 'I' && lastDigit < currentDigit) || (condition == 'D' && lastDigit > currentDigit); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /ConstructTheLexicographicallyLargestValidSequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] constructDistancedSequence(int n) { 3 | boolean used[] = new boolean[n+1]; 4 | int seq[] = new int[2*n-1]; 5 | backtrack(0,used, seq, n); 6 | return seq; 7 | } 8 | public boolean backtrack(int index, boolean used[], int seq[], int n){ 9 | while(index < seq.length && seq[index]!=0) index++; 10 | if(index == seq.length) return true; 11 | for(int i=n;i>=1;i--){ 12 | if(used[i]) continue; 13 | if(i==1){ 14 | seq[index] = i; 15 | used[i] = true; 16 | if(backtrack(index+1,used,seq,n)) return true; 17 | // if we cannot find answer 18 | seq[index]=0; 19 | used[i] = false; 20 | }else if(index + i < seq.length && seq[index+i] == 0){ 21 | seq[index] = i; 22 | seq[index + i] = i; 23 | used[i] = true; 24 | if(backtrack(index+1,used,seq,n)) return true; 25 | // if we cannot find answer 26 | seq[index]=0; 27 | seq[index + i]=0; 28 | used[i] = false; 29 | } 30 | } 31 | return false; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) 3 | { 4 | int b1=0; 5 | int b2=height.length-1; 6 | int r=0; 7 | while(b1> items, String ruleKey, String ruleValue) { 3 | 4 | int ans=0; 5 | for(List l : items) 6 | { 7 | if((ruleKey.equals("type"))&&((l.get(0)).equals(ruleValue))) 8 | { 9 | ans++; 10 | } 11 | else if((ruleKey.equals("color"))&&((l.get(1)).equals(ruleValue))) 12 | { 13 | ans++; 14 | } 15 | else if((ruleKey.equals("name"))&&((l.get(2)).equals(ruleValue))) 16 | { 17 | ans++; 18 | } 19 | 20 | } 21 | 22 | return ans; 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /CountNumberOfBadPairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long countBadPairs(int[] nums) { 3 | long n = nums.length; 4 | long goodPairs=0; 5 | long totalPairs = n*(n-1)/2; 6 | HashMap map = new HashMap<>(); 7 | for(int i=0;i0 && freq['e'-'a']>0 && freq['i'-'a']>0 11 | && freq['o'-'a']>0 && freq['u'-'a']>0); 12 | } 13 | 14 | private long atleast(int k, String words){ 15 | long count=0; 16 | int curConsonant=0; 17 | int freq[] = new int[26]; 18 | int n = words.length(); 19 | int left=0; 20 | for(int right=0;right=k && isAllVowelsPresent(freq)){ 28 | count += (n - right); 29 | char c = words.charAt(left); 30 | if(isConsonant(c)){ 31 | curConsonant--; 32 | } 33 | freq[c-'a']--; 34 | left++; 35 | } 36 | } 37 | return count; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /CountPairsWithGivenum.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int getPairsCount(int[] arr, int n, int k) 4 | { 5 | int counter=0; 6 | HashMap map = new HashMap<>(); 7 | for(int i=0;i=str.length() || end<0) return 0; 14 | // single element is always palindrome 15 | if(start==end) return 1; 16 | // check twice and subtract 17 | else if (str.charAt(start) == str.charAt(end)) 18 | return recursion(str,start+1, end) + recursion(str,start, end-1) + 1; 19 | 20 | else 21 | return recursion(str,start+1, end) + recursion(str,start, end-1) - recursion(str,start+1, end-1); 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /CountPrefixAndSuffixPairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPrefixSuffixPairs(String[] words) { 3 | int n = words.length; 4 | int count = 0; 5 | for (int i = 0; i < n-1; i++) { 6 | for (int j = i + 1; j < n; j++) { 7 | String str1 = words[i]; 8 | String str2 = words[j]; 9 | if (str1.length() > str2.length()) continue; 10 | if (str2.startsWith(str1) && str2.endsWith(str1)) { 11 | ++count; 12 | } 13 | } 14 | } 15 | return count; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /CountServersThatCommunicate.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countServers(int[][] grid) { 3 | int n = grid.length; 4 | int m = grid[0].length; 5 | int rowCount[] = new int[n]; 6 | int colCount[] = new int[m]; 7 | int count=0; 8 | for(int i=0;i=0 && nextC>=0 && nextR set = new HashSet(); 5 | for(int i=0;i set = new HashSet<>(Arrays.asList('a','e','i','o','u')); 25 | char first = word.charAt(0); 26 | char last = word.charAt(word.length()-1); 27 | if(set.contains(first) && set.contains(last)){ 28 | return 1; 29 | } 30 | return 0; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CountandSay.java: -------------------------------------------------------------------------------- 1 | // Approach 1: Recursion! 2 | class Solution { 3 | public String countAndSay(int n) { 4 | if(n==1) return "1"; 5 | String s=countAndSay(n-1); 6 | String res=""; 7 | int count=1,flag=0; 8 | for(int i=0;i queue = new LinkedList<>(); 5 | queue.offer(root); 6 | int prevSum = root.val; 7 | while(!queue.isEmpty()){ 8 | int size = queue.size(); 9 | int curSum=0; 10 | for(int i=0;i0){ 31 | operations[index-1] += operations[index]; 32 | } 33 | operations[index] = 0; 34 | index--; 35 | size--; 36 | return val; 37 | } 38 | 39 | public void increment(int k, int val) { 40 | if(isEmpty()){ 41 | return; 42 | } 43 | int num = Math.min(size,k); 44 | operations[num-1] += val; 45 | } 46 | 47 | private boolean isFull(){ 48 | return (size == capacity); 49 | } 50 | 51 | private boolean isEmpty(){ 52 | return (size == 0); 53 | } 54 | } 55 | 56 | /** 57 | * Your CustomStack object will be instantiated and called as such: 58 | * CustomStack obj = new CustomStack(maxSize); 59 | * obj.push(x); 60 | * int param_2 = obj.pop(); 61 | * obj.increment(k,val); 62 | */ 63 | -------------------------------------------------------------------------------- /DijkstraAlgorithm.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //User function Template for Java 4 | 5 | 6 | class Solution 7 | { 8 | //Function to find the shortest distance of all the vertices 9 | //from the source vertex S. 10 | static int[] dijkstra(int V, ArrayList>> adj, int S) 11 | { 12 | // Write your code here 13 | // [node, dist] 14 | PriorityQueue pq = new PriorityQueue<>(new Comparator(){ 15 | public int compare(int p1[], int p2[]){ 16 | return p1[1] - p2[1]; 17 | } 18 | }); 19 | int dist[] = new int[V]; 20 | Arrays.fill(dist,Integer.MAX_VALUE); 21 | dist[S] = 0; 22 | pq.offer(new int[]{S,0}); 23 | while(!pq.isEmpty()){ 24 | int pair[] = pq.poll(); 25 | int u = pair[0]; 26 | int d = pair[1]; 27 | if(d > dist[u]) continue; 28 | for(ArrayList neighbour : adj.get(u)){ 29 | int v = neighbour.get(0); 30 | int w = neighbour.get(1); 31 | if(dist[u] + w < dist[v]){ 32 | dist[v] = dist[u] + w; 33 | pq.offer(new int[]{v,dist[v]}); 34 | } 35 | } 36 | 37 | } 38 | return dist; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /DivideArrayIntoEqualPairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean divideArray(int[] nums) { 3 | HashSet set = new HashSet<>(); 4 | for(int num : nums){ 5 | if(set.contains(num)){ 6 | set.remove(num); 7 | }else{ 8 | set.add(num); 9 | } 10 | } 11 | return (set.size()==0); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DivideIntervalsIntoMinimumNumberofGroups.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minGroups(int[][] intervals) { 3 | //find range 4 | int min = Integer.MAX_VALUE; 5 | int max = Integer.MIN_VALUE; 6 | int n = intervals.length; 7 | for(int i=0;i map = new HashMap<>(); 11 | for(int i=0;i e : map.entrySet()) 16 | { 17 | System.out.println(e.getKey() + ":" + e.getValue()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ExtraCharactersInAString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int dp[] = new int[50]; 3 | public int minExtraChar(String s, String[] dictionary) { 4 | int n = s.length(); 5 | Arrays.fill(dp,-1); 6 | HashSet dictionarySet = new HashSet<>(Arrays.asList(dictionary)); 7 | return recur(s,dictionarySet,0); 8 | } 9 | public int recur(String s, HashSet dictionary, int index){ 10 | if(index==s.length()){ //empty string 11 | return 0; 12 | } 13 | if(dp[index]!=-1){ 14 | return dp[index]; 15 | } 16 | StringBuilder sb = new StringBuilder(); 17 | int minExtraChar = Integer.MAX_VALUE; 18 | for(int i=index;i set = new HashSet<>(); 18 | public FindElements(TreeNode root) { 19 | dfs(root,0); 20 | } 21 | 22 | public boolean find(int target) { 23 | return set.contains(target); 24 | 25 | } 26 | public void dfs(TreeNode root, int val){ 27 | if(root==null) return; 28 | root.val = val; 29 | set.add(val); 30 | dfs(root.left, 2*val+1); 31 | dfs(root.right, 2*val+2); 32 | } 33 | } 34 | 35 | /** 36 | * Your FindElements object will be instantiated and called as such: 37 | * FindElements obj = new FindElements(root); 38 | * boolean param_1 = obj.find(target); 39 | */ 40 | -------------------------------------------------------------------------------- /FindEventualSafeStates.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List eventualSafeNodes(int[][] graph) { 3 | // V+E 4 | // V 5 | HashMap map = new HashMap<>(); 6 | int n = graph.length; 7 | List res = new ArrayList<>(); 8 | for(int i=0;i map){ 16 | if(map.containsKey(node)){ 17 | return map.get(node); 18 | } 19 | 20 | map.put(node,false); 21 | for(int neighbour : graph[node]){ 22 | if(!dfs(neighbour, graph, map)){ 23 | return false; 24 | } 25 | } 26 | map.put(node,true); 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /FindKthBitInNthBinaryString.java: -------------------------------------------------------------------------------- 1 | // findKthBit - recursion 2 | class Solution { 3 | public char findKthBit(int n, int k) { 4 | int len = (int)Math.pow(2,n) - 1; 5 | return recur(len,k); 6 | } 7 | public char recur(int len, int k){ 8 | //base case 9 | if(len == 1){ 10 | return '0'; 11 | } 12 | int half = len/2; 13 | int middle = half+1; 14 | System.out.println("len -> "+ len + " ,middle-> " + middle + " ,k-> "+ k); 15 | if(k==middle){ 16 | return '1'; 17 | }else if(k0 && nums[mid] < nums[mid-1]) return nums[mid]; 18 | // if you are inside the sorted array then move towards the unsorted array 19 | else if(nums[mid] < nums[end]) end = mid-1; 20 | // if you are inside the unsorted array then move towards the last element of unsorted array 21 | else if(nums[mid] > nums[end]) start = mid+1; 22 | 23 | } 24 | return -1; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /FindMissingAndRepeatedValues.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findMissingAndRepeatedValues(int[][] grid) { 3 | int n=grid.length; 4 | int sq = n*n; 5 | int set[] = new int[sq+1]; 6 | // 1,sq 7 | int curSum=0; 8 | int ans[] = new int[2]; 9 | for(int i=0;i set = new HashSet<>(); 8 | for(String num : nums){ 9 | set.add(num); 10 | } 11 | res=new StringBuilder(""); 12 | backtrack(nums,n,set,res); 13 | return res.toString(); 14 | } 15 | public boolean backtrack(String nums[], int n,HashSet set, StringBuilder res){ 16 | //base case 17 | if(res.length() == n){ 18 | if(!set.contains(res.toString())){ 19 | return true; 20 | } 21 | return false; 22 | } 23 | for(char ch='0';ch<='1';ch++){ 24 | res.append(ch); 25 | if(backtrack(nums,n,set,res)){ 26 | return true; 27 | } 28 | res.deleteCharAt(res.length()-1); 29 | } 30 | return false; 31 | } 32 | } 33 | 34 | 35 | //O(N) 36 | class Solution { 37 | public String findDifferentBinaryString(String[] nums) { 38 | int n = nums.length; 39 | StringBuilder res = new StringBuilder(""); 40 | for(int i=0;i colorMap = new HashMap<>(); 4 | HashMap ballMap = new HashMap<>(); 5 | int n = queries.length; 6 | int res[] = new int[n]; 7 | for(int i=0;itarget) hi=mid-1; 44 | else lo=mid+1; 45 | } 46 | return index; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /FirstCompletelyPaintedRow.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int firstCompleteIndex(int[] arr, int[][] mat) { 3 | int n = mat.length; //rows 4 | int m = mat[0].length; //cols 5 | int rowCount[] = new int[n]; 6 | int colCount[] = new int[m]; 7 | // num -> (r,c) 8 | HashMap map = new HashMap<>(); 9 | for(int i=0;i set = new HashSet<>(); 11 | if(str.length()==0) 12 | { 13 | System.out.println("Not Found!"); 14 | return; 15 | } 16 | String words[] = str.split(" "); 17 | for(String s : words) 18 | { 19 | if(set.contains(s)) 20 | { 21 | System.out.println("First repeated is: "+s); 22 | return; 23 | } 24 | set.add(s); 25 | } 26 | System.out.println("Not Found"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /FirstThreeLargest.java: -------------------------------------------------------------------------------- 1 | public class FirstThreeLargest{ 2 | public static void Main(String args[]) 3 | { 4 | int arr[] = {2,7,9,3,6,1,11,8}; 5 | solve(arr); 6 | } 7 | public static void solve(int arr[]) 8 | { 9 | int n=arr.length; 10 | int first = Integer.MIN_VALUE, second=Integer.MIN_VALUE,third=Integer.MIN_VALUE; 11 | for(int i=0;iend){ 7 | end = num; 8 | } 9 | if(num < start){ 10 | start = num; 11 | } 12 | } 13 | int ans=0; 14 | while(start<=end){ 15 | int mid = start + (end-start)/2; 16 | if(isRobberyPossible(mid, nums, k)){ 17 | ans = mid; 18 | end = mid-1; 19 | }else{ 20 | start = mid+1; 21 | } 22 | } 23 | return ans; 24 | } 25 | public boolean isRobberyPossible(int capability, int nums[], int minHouses){ 26 | int housesRobbed=0; 27 | for(int i=0;i= minHouses) return true; 33 | } 34 | return false; 35 | } 36 | } 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /InsertGreatestCommonDivisorsinLinkedList.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findGCD(int a, int b){ 3 | if(b==0) return a; 4 | return findGCD(b,a%b); 5 | } 6 | public ListNode insertGreatestCommonDivisors(ListNode head) { 7 | if(head.next == null) return head; 8 | ListNode cur = head; 9 | while(cur.next!=null){ 10 | int max = Math.max(cur.val,cur.next.val); 11 | int min = Math.min(cur.val,cur.next.val); 12 | int gcd = findGCD(max, min); 13 | ListNode gcdNode = new ListNode(gcd); 14 | gcdNode.next = cur.next; 15 | cur.next = gcdNode; 16 | cur = gcdNode.next; 17 | } 18 | return head; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /IntegerToEnglishWords.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | String[] belowTen = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; 3 | String[] belowTwenty = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; 4 | String[] belowHundred = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; 5 | public String numberToWords(int num) { 6 | if(num==0){ 7 | return "Zero"; 8 | } 9 | if(num<10){ 10 | return belowTen[num]; 11 | } 12 | if(num<20){ 13 | return belowTwenty[num-10]; 14 | } 15 | if(num<100){//74, 70 16 | return belowHundred[num/10] + (num%10!=0?" " + belowTen[num%10]:""); 17 | } 18 | if(num<1000){ //9 00 19 | return belowTen[num/100] + " Hundred" + (num%100!=0?" " + numberToWords(num%100):""); 20 | } 21 | if(num<1000000){ //9000 -- 999 000 22 | return numberToWords(num/1000) + " Thousand" + (num%1000!=0?" " + numberToWords(num%1000):""); 23 | } 24 | if(num<1000000000){ //999 129786 25 | return numberToWords(num/1000000) + " Million" + (num%1000000!=0?" " + numberToWords(num%1000000):""); 26 | } 27 | return numberToWords(num/1000000000) + " Billion" + (num%1000000000!=0?" " + numberToWords(num%1000000000):""); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /IsGraphBipartite.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // depth first search 3 | public boolean color(int src, int graph[][], int color[]){ 4 | Queue queue = new LinkedList<>(); 5 | queue.offer(src); 6 | color[src] = 0; 7 | while(!queue.isEmpty()){ 8 | int node = queue.poll(); 9 | for(int neighbour : graph[node]){ 10 | if(color[neighbour]==-1){ 11 | color[neighbour] = 1 - color[node]; 12 | queue.offer(neighbour); 13 | }else if(color[neighbour] == color[node]){ 14 | return false; 15 | } 16 | } 17 | } 18 | return true; 19 | } 20 | public boolean isBipartite(int[][] graph) { 21 | int n = graph.length; 22 | int color[] = new int[n]; 23 | Arrays.fill(color,-1); 24 | for(int i=0;i> adj) 5 | { 6 | // add your code here 7 | int indegree[] = new int[V]; //0 8 | for(int u=0;u queue = new LinkedList<>(); 14 | for(int i=0;i res = new ArrayList<>(); 22 | while(!queue.isEmpty()){ 23 | int node = queue.poll(); 24 | res.add(node); 25 | for(int neighbour : adj.get(node)){ 26 | indegree[neighbour]--; 27 | if(indegree[neighbour]==0){ 28 | queue.offer(neighbour); 29 | } 30 | } 31 | } 32 | 33 | if(res.size() != V){ 34 | return new int[V]; 35 | } 36 | 37 | int ans[] = new int[V]; 38 | for(int i=0;i distinct = new HashSet<>(); 5 | HashSet duplicate = new HashSet<>(); 6 | for(String str : arr){ 7 | if(duplicate.contains(str)){ 8 | continue; 9 | } 10 | if(distinct.contains(str)){ 11 | distinct.remove(str); 12 | duplicate.add(str); 13 | }else{ 14 | distinct.add(str); 15 | } 16 | } 17 | for(String str : arr){ 18 | if(!duplicate.contains(str)){ 19 | k--; 20 | } 21 | if(k==0){ 22 | return str; 23 | } 24 | } 25 | return ""; 26 | } 27 | } 28 | 29 | // hashmap 30 | class Solution { 31 | public String kthDistinct(String[] arr, int k) { 32 | HashMap freqMap = new HashMap<>(); 33 | for(String str : arr){ 34 | freqMap.put(str,freqMap.getOrDefault(str,0)+1); 35 | } 36 | for(String str : arr){ 37 | if(freqMap.get(str)==1){ 38 | k--; 39 | } 40 | if(k==0){ 41 | return str; 42 | } 43 | } 44 | return ""; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /KthLargestElementInAStream.java: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | PriorityQueue pq; 3 | int k; 4 | public KthLargest(int k, int[] nums) { 5 | this.k = k; 6 | pq = new PriorityQueue<>(); 7 | for(int num : nums){ 8 | add(num); 9 | } 10 | } 11 | 12 | public int add(int val) { 13 | if(pq.size() pq.peek()){ 14 | pq.offer(val); 15 | if(pq.size()>k){ 16 | pq.poll(); 17 | } 18 | } 19 | return pq.peek(); 20 | } 21 | } 22 | 23 | /** 24 | * Your KthLargest object will be instantiated and called as such: 25 | * KthLargest obj = new KthLargest(k, nums); 26 | * int param_1 = obj.add(val); 27 | */ 28 | -------------------------------------------------------------------------------- /KthLargestSumInABinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public long kthLargestLevelSum(TreeNode root, int k) { 18 | 19 | // BF 20 | // max heap 21 | //bfs - min heap. 22 | Queue queue = new LinkedList<>(); 23 | PriorityQueue pq = new PriorityQueue<>(); 24 | queue.offer(root); 25 | while(!queue.isEmpty()){ 26 | int size = queue.size(); 27 | long sum = 0l; 28 | for(int i=0;ik){ 40 | pq.poll(); 41 | } 42 | } 43 | //-1 case 44 | if(pq.size() factorial(int n) 5 | { 6 | // declare an arrayList 7 | ArrayList result = new ArrayList(); 8 | int size=0,c=0; 9 | // Adding 1 at 0th index 10 | result.add(0,1); 11 | // Updating size 12 | size=1; 13 | // Decalre a variable to traverse numbers from 2 to n 14 | int val=2; 15 | while(val<=n) 16 | { 17 | // Traverse array list from right to left 18 | for(int i=size-1;i>=0;i--) 19 | { 20 | // Update value in arrayList 21 | int temp=result.get(i)*val + c; 22 | // Store the last digit at index and add remaining to carry 23 | result.set(i,temp%10); 24 | // update carry 25 | c=temp/10; 26 | } 27 | // insert carry digit by digit to the begining of the ArrayList 28 | while(c!=0) 29 | { 30 | result.add(0,c%10); 31 | c=c/10; 32 | size++; 33 | } 34 | val++; 35 | } 36 | return result; 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /LargestNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String largestNumber(int[] nums) { 3 | int n = nums.length; 4 | String elements[] = new String[n]; 5 | for(int i=0;i(){ 10 | public int compare(String a, String b){ 11 | String first = a + b; 12 | String sec = b + a; 13 | return sec.compareTo(first); //K 14 | } 15 | }); 16 | if(elements[0].equals("0")){ 17 | return "0"; 18 | } 19 | // N 20 | StringBuilder sb = new StringBuilder(); 21 | for(String val : elements){ 22 | sb.append(val); 23 | } 24 | return sb.toString(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LetterTilePossibilities-1.java: -------------------------------------------------------------------------------- 1 | // recursion with character index 2 | class Solution { 3 | int len; 4 | public int numTilePossibilities(String tiles) { 5 | len = tiles.length(); 6 | boolean used[] = new boolean[len]; 7 | HashSet set = new HashSet<>(); 8 | backtrack(tiles, used, set, ""); 9 | return set.size() - 1; 10 | } 11 | public void backtrack(String tiles, boolean used[], HashSet set, String cur){ 12 | if(set.contains(cur)) return; 13 | set.add(cur); 14 | for(int i=0;i set, Boolean visited[]){ 3 | // Base Case 4 | if(output.length()>0) 5 | { 6 | if(set.contains(output)) 7 | return; 8 | set.add(output); 9 | } 10 | for(int i=0;i set = new HashSet(); 21 | Boolean visited[] = new Boolean[tiles.length()]; 22 | Arrays.fill(visited, Boolean.FALSE); 23 | backtrack(tiles,"",set, visited); 24 | return set.size(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LexicographicalNumbers.java: -------------------------------------------------------------------------------- 1 | //DFS 2 | class Solution { 3 | public List lexicalOrder(int n) { 4 | List res = new ArrayList<>(); 5 | for(int i=1;i<10;i++){ 6 | if(i>n) break; 7 | dfs(i,n,res); 8 | } 9 | return res; 10 | } 11 | public void dfs(int curNum, int target, Listres){ 12 | if(curNum>target){ 13 | return; 14 | } 15 | res.add(curNum); 16 | for(int d=0;d<10;d++){ 17 | if(curNum*10+d>target){ 18 | break; 19 | } 20 | dfs(curNum*10+d,target,res); 21 | } 22 | } 23 | } 24 | 25 | 26 | 27 | //Iterative 28 | class Solution { 29 | public List lexicalOrder(int n) { 30 | List res = new ArrayList<>(); 31 | int curNum=1; 32 | for(int i=1;i<=n;i++){ 33 | res.add(curNum); 34 | if(curNum*10 <= n){ 35 | curNum*=10; 36 | }else{ 37 | while(curNum%10 == 9 || curNum==n){ 38 | curNum/=10; 39 | } 40 | curNum+=1; 41 | } 42 | } 43 | return res; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /LinkedListInBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean dfs(ListNode head, TreeNode node){ 3 | if(head == null) return true; 4 | if(node == null) return false; 5 | if(head.val != node.val) return false; 6 | return dfs( head.next, node.left) || dfs( head.next, node.right); 7 | } 8 | public boolean isSubPath(ListNode head, TreeNode root) { 9 | if(root == null) return false; 10 | if(root.val == head.val){ 11 | if(dfs(head,root)){ 12 | return true; 13 | } 14 | } 15 | return isSubPath( head, root.left) || isSubPath( head, root.right); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LongerContiguousSegmentsOfOnesThanZeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkZeroOnes(String s) { 3 | int ones=0,twos=0; 4 | if(s.charAt(0)=='1') ones=1; 5 | else twos=1; 6 | int temp=1; 7 | for(int i=1;itwos); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | //Hashing Solution 2 | class Solution 3 | { 4 | // arr[] : the input array 5 | // N : size of the array arr[] 6 | 7 | //Function to return length of longest subsequence of consecutive integers. 8 | static int findLongestConseqSubseq(int arr[], int N) 9 | { 10 | // add your code here 11 | HashSet set = new HashSet(); 12 | for(int i=0;i luckyNumbers (int[][] matrix) { 3 | int rows = matrix.length; 4 | int cols = matrix[0].length; 5 | int maxOfRowMins=Integer.MIN_VALUE; 6 | for(int i=0;i res = new ArrayList<>(); 14 | for(int i=0;isize/2); 14 | } 15 | static int majorityElement(int a[], int size) 16 | { 17 | // your code here 18 | 19 | int candidate=-1; 20 | int votes=0; 21 | for(int i=0;i=0 ;i--){ 8 | right[i] = Math.min(right[i+1] , arr[i]); 9 | } 10 | int count =0 ; 11 | int min = Integer.MIN_VALUE; 12 | for(int i =0 ; i < arr.length ;i++){ 13 | min = Math.max(min , arr[i]); 14 | 15 | if(min <= right[i+1]){ 16 | count++; 17 | } 18 | } 19 | return count; 20 | } 21 | } 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /MaxSumOfAPairWithEqualSumOfDigits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getDigitSum(int num){ 3 | int sum=0; 4 | while(num>0){ 5 | sum += (num%10); 6 | num/=10; 7 | } 8 | return sum; 9 | } 10 | public int maximumSum(int[] nums) { 11 | // HashMap map = new HashMap<>(); 12 | int map[] = new int[82]; 13 | int ans=-1; 14 | for(int num : nums){ 15 | int digitSum = getDigitSum(num); 16 | if(map[digitSum]>0){ 17 | // int prevNum = map.get(digitSum); 18 | int prevNum = map[digitSum]; 19 | ans = Math.max(prevNum + num, ans); 20 | map[digitSum] = Math.max(prevNum,num); 21 | // map.put(digitSum, Math.max(prevNum,num)); 22 | }else{ 23 | map[digitSum] = num; 24 | // map.put(digitSum,num); 25 | } 26 | } 27 | return ans; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /MaximalScoreAfterApplyingKOperations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long maxKelements(int[] nums, int k) { 3 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 4 | int n= nums.length; 5 | for(int i=0;i0){ 10 | int val = pq.poll(); 11 | score+=val; 12 | pq.offer((int)Math.ceil(val/3.0)); 13 | k--; 14 | } 15 | return score; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /MaximumAbsoluteSumOfAnySubarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxAbsoluteSum(int[] nums) { 3 | int maxSum = Integer.MIN_VALUE; 4 | int minSum = Integer.MAX_VALUE; 5 | int curPSum=0; 6 | int curNSum=0; 7 | for(int num : nums){ 8 | // pos 9 | curPSum += num; 10 | maxSum = Math.max(maxSum,curPSum); 11 | if(curPSum < 0){ 12 | curPSum = 0; 13 | } 14 | // neg 15 | curNSum += num; 16 | minSum = Math.min(minSum,curNSum); 17 | if(curNSum > 0){ 18 | curNSum = 0; 19 | } 20 | } 21 | return Math.max(maxSum, Math.abs(minSum)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /MaximumCountOfPositiveIntegerAndNegativeInteger.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximumCount(int[] nums) { 3 | //first >-1 -> neg 4 | // first >0 -> pos 5 | int n = nums.length; 6 | int end = n-1; 7 | int negPos = binarySearch(nums, 0, end, -1); //log(n) 8 | int posPos = binarySearch(nums, negPos, end, 0); //log(n - negPos) 9 | int posCount = (n - posPos); 10 | return Math.max(negPos,posCount); 11 | } 12 | public int binarySearch(int nums[], int start, int end, int target){ 13 | while(start<=end){ 14 | int mid = start + (end-start)/2; 15 | if(nums[mid]<=target){ 16 | start = mid+1; 17 | }else{ 18 | end=mid-1; 19 | } 20 | } 21 | return start; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find maximum product subarray 3 | long maxProduct(int[] arr, int n) { 4 | // code here 5 | long max=arr[0]; 6 | long min=arr[0]; 7 | long res=arr[0]; 8 | for(int i=1;i=0;i--){ 10 | if(numArr[i] > maxElement){ 11 | maxElement = numArr[i]; 12 | maxIndex = i; 13 | }else if(numArr[i] < maxElement){ 14 | swapIdx1 = i; 15 | swapIdx2 = maxIndex; 16 | } 17 | } 18 | 19 | //perform swapping 20 | if(swapIdx1!=-1){ 21 | char temp = numArr[swapIdx1]; 22 | numArr[swapIdx1] = numArr[swapIdx2]; 23 | numArr[swapIdx2] = temp; 24 | } 25 | return Integer.parseInt(new String(numArr)); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /MaximumWidthRamp.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | Stack stack = new Stack<>(); //N 4 | int n = nums.length; 5 | // N 6 | for(int i=0;i nums[i]){ 8 | stack.push(i); 9 | } 10 | } 11 | int ans = Integer.MIN_VALUE; 12 | // N + N-1 13 | for(int i=n-1;i>=0;i--){ 14 | while(!stack.isEmpty() && nums[stack.peek()] <= nums[i]){ 15 | ans = Math.max(ans, i - stack.pop()); 16 | } 17 | if(stack.isEmpty()){ 18 | break; 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /MedianOfRowWiseSortedMatrix.java: -------------------------------------------------------------------------------- 1 | //User function Template for Java 2 | 3 | class Solution { 4 | int median(int matrix[][], int r, int c) { 5 | // code here 6 | 7 | int startVal=0,endVal=2000,midVal; 8 | int n=r*c; 9 | while(startVal<=endVal) 10 | { 11 | midVal=(endVal+startVal)/2; 12 | int ans=0; 13 | for(int i=0;i nums2.length){ 7 | return(findMedianSortedArrays(nums2, nums1)); 8 | } 9 | int n1=nums1.length; 10 | int n2=nums2.length; 11 | int lo=0,hi=n1; 12 | while(lo<=hi) 13 | { 14 | // Initialize the cuts or partitions 15 | int cut1=lo+(hi-lo)/2; 16 | // Total required - already present 17 | int cut2=((n1+n2)/2)-cut1; 18 | 19 | // Initialize l1,l2,r1,r2 20 | int l1= (cut1==0)?Integer.MIN_VALUE:nums1[cut1-1]; 21 | int l2= (cut2==0)?Integer.MIN_VALUE:nums2[cut2-1]; 22 | int r1= (cut1==n1)?Integer.MAX_VALUE:nums1[cut1]; 23 | int r2= (cut2==n2)?Integer.MAX_VALUE:nums2[cut2]; 24 | 25 | // Shift element to the left 26 | if(l1>r2) hi=cut1-1; 27 | else if(l2>r1) lo=cut1+1; 28 | else 29 | { 30 | // Check for even length 31 | if((n1+n2)%2==0) 32 | return (double)(Math.max(l1,l2)+Math.min(r1,r2))/2; 33 | else 34 | return (double)(Math.min(r1,r2)); 35 | } 36 | // To avoid error 37 | } 38 | return 0.0; 39 | } 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /MergeIntervals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] merge(int[][] intervals) { 3 | // Sorting 4 | for(int i=0;iintervals[j+1][0]) 10 | { 11 | //Swap 12 | int temp[]=new int[2]; 13 | temp[0]=intervals[j][0]; 14 | temp[1]=intervals[j][1]; 15 | intervals[j][0]=intervals[j+1][0]; 16 | intervals[j][1]=intervals[j+1][1]; 17 | intervals[j+1][0]=temp[0]; 18 | intervals[j+1][1]=temp[1]; 19 | flag=1; 20 | } 21 | } 22 | if(flag==0) 23 | { 24 | break; 25 | } 26 | } 27 | List res=new ArrayList<>(); 28 | int current_interval[]=intervals[0]; 29 | res.add(current_interval); 30 | for(int i=0;i res = new ArrayList<>(); 4 | int n = nums1.length; 5 | int m = nums2.length; 6 | int i=0; 7 | int j=0; 8 | while(iB) 6 | { 7 | if(AC) return B; 10 | 11 | else return C; 12 | } 13 | else 14 | { 15 | if(BC) return A; 18 | 19 | else return C; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /MinAddToMakeStringValid.java: -------------------------------------------------------------------------------- 1 | //stack approach 2 | class Solution { 3 | public int minAddToMakeValid(String s) { 4 | Stack stack = new Stack<>(); 5 | for(int i=0;imaxi) 25 | maxi = a[i]; 26 | if(a[i]=k) 11 | { 12 | max=Math.max(arr[i-1]+k,arr[n-1]-k); 13 | min=Math.min(arr[i]-k,arr[0]+k); 14 | r=Math.min(r,max-min); 15 | } 16 | else 17 | { 18 | continue; 19 | } 20 | } 21 | return r; 22 | } 23 | } -------------------------------------------------------------------------------- /MinimumAddToMakeParenthesisValid.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minAddToMakeValid(String s) { 3 | 4 | int open=0,close=0; 5 | // look only for invalid pairs 6 | 7 | for(int i=0;i0){ //set bits O(32) 6 | xor = xor & (xor-1); 7 | count++; 8 | } 9 | return count; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MinimumLengthofStringAfterOperations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumLength(String s) { 3 | // N + 26 4 | int freq[] = new int[26]; 5 | int n = s.length(); 6 | for(int i=0;i0){ 12 | if(freq[i]%2==0){ 13 | count+=2; 14 | }else{ 15 | count+=1; 16 | } 17 | } 18 | } 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /MinimumNumberOfSwapsToMakeStringBalanced.java: -------------------------------------------------------------------------------- 1 | //Stack Solution 2 | class Solution { 3 | public int minSwaps(String s) { 4 | Stack stack = new Stack(); 5 | int open=0,close=0; 6 | for(int i=0;i stack = new Stack(); 28 | int open=0,close=0; 29 | for(int i=0;i pq = new PriorityQueue<>(); 4 | for(int num : nums) pq.offer((long)num); 5 | int op=0; 6 | while(pq.size()>=2){ 7 | long x = pq.poll(); 8 | if(x>=k) break; 9 | long y = pq.poll(); 10 | long res = Math.min(x,y)*2 + Math.max(x,y); 11 | pq.offer(res); 12 | op++; 13 | } 14 | return op; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /MinimumOperationstoMakeBinaryArrayElementsEqualtoOneI.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(int[] nums) { 3 | int n=nums.length; 4 | int count=0; 5 | for(int s=0;s<(n-2);s++){ 6 | if(nums[s]==0){ 7 | nums[s] = 1 - nums[s]; 8 | nums[s+1] = 1 - nums[s+1]; 9 | nums[s+2] = 1 - nums[s+2]; 10 | count++; 11 | } 12 | } 13 | if(nums[n-1] ==0 || nums[n-2]==0){ 14 | return -1; 15 | } 16 | return count; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /MinimumRecolorsToGetKConsecutiveBlackBlocks.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumRecolors(String blocks, int k) { 3 | //first window 4 | int w=0; 5 | for(int i=0;i stack = new Stack<>(); 5 | for(int i=0;ik) nonFav++; 15 | } 16 | 17 | int l=0,r=fav-1, result = Integer.MAX_VALUE; 18 | 19 | while(rk) nonFav++; 24 | if(lk) nonFav--; 25 | l++; 26 | } 27 | 28 | return (result == Integer.MAX_VALUE)?0:result; 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /MinimumTimeToRepairCars.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long repairCars(int[] ranks, int cars) { 3 | long start = Long.MAX_VALUE; 4 | long end = Long.MIN_VALUE; 5 | for (int rank : ranks){ 6 | end = Math.max(end, rank); 7 | start = Math.min(start,rank); 8 | } 9 | end = end * cars * cars; 10 | long ans=0; 11 | while (start <= end) { 12 | long mid = start + (end - start) / 2; 13 | if (isCarsRepaired(mid, ranks,cars)){ 14 | ans = mid; 15 | end=mid-1; 16 | } 17 | else { 18 | start=mid+1; 19 | } 20 | } 21 | 22 | return ans; 23 | } 24 | public boolean isCarsRepaired(long time, int ranks[], int carsToBeRepaired){ 25 | long carsRepaired = 0; 26 | for (int rank : ranks){ 27 | carsRepaired += (long) (Math.sqrt((1.0 * time) / rank)); 28 | if(carsRepaired>=carsToBeRepaired) return true; 29 | } 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Minimum_number_of_jumps.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int minJumps(int[] arr){ 3 | // your code here 4 | if(arr.length==1) 5 | return 0; 6 | 7 | if(arr[0]==0) 8 | return -1; 9 | 10 | int jump=0,halt=0; 11 | int maxDist=Integer.MIN_VALUE; 12 | for(int i=0;i=maxDist) 15 | maxDist=arr[i]+i; 16 | 17 | if(i==halt) 18 | { 19 | halt=maxDist; 20 | jump++; 21 | if(halt>=arr.length-1) 22 | break; 23 | } 24 | } 25 | return (halt>=arr.length-1)?jump:-1; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /MissingAndRepeating.java: -------------------------------------------------------------------------------- 1 | class Solve 2 | { 3 | int[] findTwoElement(int arr[], int n) 4 | { 5 | // code here 6 | int result[] = new int[2]; 7 | 8 | int sum=0; 9 | 10 | int origSum=0; 11 | 12 | for(int i=0;i=0 && nums[i]>=nums[i+1]) i--; 8 | if(i>=0) 9 | { 10 | j=nums.length-1; 11 | while(nums[j]<=nums[i]) j--; 12 | swap(nums,i,j); 13 | } 14 | reverse(nums,i+1,nums.length-1); 15 | } 16 | 17 | public static void swap(int nums[],int i,int j) 18 | { 19 | int temp=nums[i]; 20 | nums[i]=nums[j]; 21 | nums[j]=temp; 22 | } 23 | 24 | public static void reverse(int nums[],int i,int j) 25 | { 26 | while(i(){ 6 | public int compare(int a[], int b[]){ 7 | return a[0] - b[0]; 8 | } 9 | }); 10 | //[lt,chairNo] 11 | PriorityQueue occupied = new PriorityQueue<>(new Comparator(){ 12 | public int compare(int a[], int b[]){ 13 | return a[0] - b[0]; 14 | } 15 | }); 16 | PriorityQueue available = new PriorityQueue<>(); 17 | int chairNo=0; 18 | for(int time[] : times){ 19 | int arrTime = time[0]; 20 | int leavingTime = time[1]; 21 | while(!occupied.isEmpty() && occupied.peek()[0] <= arrTime){ 22 | available.offer(occupied.poll()[1]); 23 | } 24 | int currentChairNo; 25 | if(available.isEmpty()){ 26 | currentChairNo = chairNo; 27 | chairNo++; 28 | }else{ 29 | currentChairNo = available.poll(); 30 | } 31 | if(targetArrival == arrTime) return currentChairNo; 32 | occupied.offer(new int[]{leavingTime, currentChairNo}); 33 | } 34 | return -1; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /NumberOfSubarraysWithOddSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numOfSubarrays(int[] arr) { 3 | int Mod=1000000007; 4 | int evenC=1; 5 | int oddC=0; 6 | int prefix=0; 7 | int res=0; 8 | for(int num : arr){ 9 | prefix+=num; 10 | if(prefix%2==0){ 11 | res += oddC; 12 | evenC++; 13 | }else{ 14 | res += evenC; 15 | oddC++; 16 | } 17 | res = res % Mod; 18 | } 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /NumberOfSubstringsContainingAllThreeCharacters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubstrings(String s) { 3 | int freq[] = new int[3]; 4 | int count=0; 5 | int curCount=0; 6 | int left=0; 7 | int n = s.length(); 8 | for(int right=0;right= right){ 15 | count++; 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | 22 | //only left sum 23 | class Solution { 24 | public int waysToSplitArray(int[] nums) { 25 | long total = 0; 26 | long left = 0; 27 | for(int num : nums){ 28 | total += num; 29 | } 30 | int n = nums.length; 31 | int count=0; 32 | for(int i=0;i= total){ 35 | count++; 36 | } 37 | } 38 | return count; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /PalindromeString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int isPlaindrome(String S) { 3 | // code here 4 | int start=0; 5 | int end=S.length()-1; 6 | while(start pivot){ 10 | gCount++; 11 | }else{ 12 | pCount++; 13 | } 14 | } 15 | int i=0; 16 | int j=lCount; 17 | int k=lCount + pCount; 18 | int res[] = new int[nums.length]; 19 | for(int num : nums){ 20 | if(num < pivot){ 21 | res[i] = num; 22 | i++; 23 | }else if(num > pivot){ 24 | res[k] = num; 25 | k++; 26 | }else{ 27 | res[j] = num; 28 | j++; 29 | } 30 | } 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /PascalTriangle.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public List> generate(int numRows) 4 | { 5 | // Declare list of list for storing results 6 | List> pascalTriangle = new ArrayList>(); 7 | pascalTriangle.add(0,new ArrayList(Arrays.asList(1))); 8 | 9 | int row =2; 10 | 11 | while(row<=numRows) 12 | { 13 | List temp = new ArrayList<>(); 14 | temp.add(0,1); 15 | int start=1,end=row-1; 16 | for(int i=start;i prob[v]){ 14 | prob[v] = prob[u] * sp; 15 | isChanged=true; 16 | } 17 | if(prob[v] * sp > prob[u]){ 18 | prob[u] = prob[v] * sp; 19 | isChanged=true; 20 | } 21 | j++; 22 | } 23 | if(!isChanged){ 24 | break; 25 | } 26 | } 27 | return prob[end_node]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | // User function Template for Java 4 | 5 | class Solution { 6 | static int spanningTree(int V, int E, List> adj) { 7 | // Code Here. 8 | //(parent, node, weight) 9 | PriorityQueue pq = new PriorityQueue<>(new Comparator<>(){ 10 | public int compare(int pair1[], int pair2[]){ 11 | return pair1[2] - pair2[2]; 12 | } 13 | }); 14 | int sum=0; 15 | ArrayList edges = new ArrayList<>(); 16 | boolean visited[] = new boolean[V]; 17 | pq.offer(new int[]{-1,0,0}); 18 | while(!pq.isEmpty()){ 19 | int object[] = pq.poll(); 20 | int parent = object[0]; 21 | int node = object[1]; 22 | int weight = object[2]; 23 | if(visited[node]) continue; 24 | visited[node] = true; 25 | if(parent!=-1){ 26 | edges.add(new int[]{parent, node}); 27 | sum += weight; 28 | } 29 | 30 | for(int neighbourObject[] : adj.get(node)){ 31 | int neighbourNode = neighbourObject[0]; 32 | int neighbourWeight = neighbourObject[1]; 33 | if(!visited[neighbourNode]){ 34 | pq.offer(new int[]{node,neighbourNode,neighbourWeight}); 35 | } 36 | } 37 | } 38 | return sum; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ProductOfTheLastKNumbers.java: -------------------------------------------------------------------------------- 1 | class ProductOfNumbers { 2 | ArrayList list = new ArrayList<>(); 3 | public ProductOfNumbers() { 4 | list.clear(); 5 | } 6 | 7 | public void add(int num) { 8 | if(num==0){ 9 | list.clear(); 10 | return; 11 | } 12 | int prev = (list.size()==0)?1:list.get(list.size()-1); 13 | list.add(prev * num); 14 | } 15 | 16 | public int getProduct(int k) { 17 | int s = list.size(); 18 | if(s result = new ArrayList<>(); 4 | int ans[] = new int[queries.length]; 5 | for(int i=1;i<=m;i++) 6 | { 7 | result.add(i); 8 | } 9 | for(int i=0;i pq = new PriorityQueue<>(new Comparator(){ 6 | public int compare(int a[], int b[]){ 7 | return a[0] - b[0]; 8 | } 9 | }); 10 | for(int i=0;i= left-1){ 17 | sum = (sum + cur[0])%mod; 18 | } 19 | // [3,2] 20 | if(cur[1]+1 list, String path, int visited[][]) 3 | { 4 | // Dead Ends 5 | if(r<0 || c<0 || r>=n || c>=n || visited[r][c]==1 || m[r][c]==0) 6 | { 7 | if(path.length()>1) 8 | path=path.substring(0,path.length()-1); 9 | else 10 | path=""; 11 | return; 12 | } 13 | // Base Case 14 | if(r==n-1 && c==n-1) 15 | { 16 | list.add(path); 17 | return; 18 | } 19 | visited[r][c]=1; 20 | backTrack(r+1,c,m,n,list,path+"D",visited); 21 | backTrack(r,c-1,m,n,list,path+"L",visited); 22 | backTrack(r,c+1,m,n,list,path+"R",visited); 23 | backTrack(r-1,c,m,n,list,path+"U",visited); 24 | // backtrack 25 | visited[r][c]=0; 26 | } 27 | public static ArrayList findPath(int[][] m, int n) { 28 | // Your code here 29 | ArrayList list = new ArrayList(); 30 | int visited[][] = new int[n][n]; 31 | backTrack(0,0,m,n,list,"",visited); 32 | return list; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /RearrangeArrayAlternatively.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | // temp: input array 4 | // n: size of array 5 | //Function to rearrange the array elements alternately. 6 | public static void rearrange(int arr[], int n){ 7 | 8 | // Your code here 9 | int j=0,k=n-1; 10 | int key=arr[n-1]+1; 11 | for(int i=0;i= m){ 9 | String sub = sb.substring(sb.length()-m); 10 | if(sub.equals(part)){ 11 | sb.setLength(sb.length()-m); 12 | } 13 | } 14 | } 15 | return sb.toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RemoveConsecutiveCharacters.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public String removeConsecutiveCharacter(String S){ 3 | String res=""; 4 | int n =S.length(); 5 | for(int i=0;i 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 n=s.length(); 14 | int output=0; 15 | for(int i=0;i=0;j--) 12 | { 13 | if(arr[i][j]==1) 14 | { 15 | row=i; 16 | // We will not see same column again 17 | col--; 18 | } 19 | // if you see zero 0 then skip that row 20 | else{ 21 | break; 22 | } 23 | } 24 | } 25 | return row; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SearchInA2DMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static boolean binSearch(int matrix[],int target) 3 | { 4 | int start=0,end=matrix.length-1; 5 | while(start<=end) 6 | { 7 | int mid = start+(end-start)/2; 8 | if(matrix[mid]==target) 9 | return true; 10 | else if(target=matrix[i][0] && target<=matrix[i][m-1]) 28 | { 29 | result=binSearch(matrix[i],target); 30 | } 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /SearchingInArrayWhereElementsDifferByK.java: -------------------------------------------------------------------------------- 1 | class Complete{ 2 | 3 | 4 | // Function for finding maximum and value pair 5 | public static int search (int arr[], int n, int x, int k) { 6 | //Complete the function 7 | 8 | int index=0; 9 | 10 | while(index map = new HashMap<>(); 7 | 8 | for(int i=0;i> itr = map.entrySet().iterator(); 16 | 17 | while (itr.hasNext()) 18 | { 19 | Map.Entry entry = itr.next(); 20 | int v = entry.getValue(); 21 | if( v > first_max) 22 | { 23 | sec_max = first_max; 24 | first_max = v; 25 | } 26 | else if (v > sec_max && v != first_max) 27 | sec_max = v; 28 | } 29 | 30 | itr = map.entrySet().iterator(); 31 | 32 | while (itr.hasNext()) 33 | { 34 | Map.Entry entry = itr.next(); 35 | int v = entry.getValue(); 36 | if (v == sec_max) 37 | return entry.getKey(); 38 | } 39 | return null; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SentenceSimilarityIII.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //tc N+M + Min(n,m) 3 | //sc n+m 4 | public boolean areSentencesSimilar(String sentence1, String sentence2) { 5 | if(sentence1.length()>sentence2.length()){ 6 | return areSentencesSimilar(sentence2, sentence1); 7 | } 8 | String smallerWords[] = sentence1.split(" "); 9 | String largerWords[] = sentence2.split(" "); 10 | int start=0; 11 | int end1=smallerWords.length-1; 12 | int end2=largerWords.length-1; 13 | //find prefix words 14 | while(start<=end1 && smallerWords[start].equals(largerWords[start])){ 15 | start++; 16 | } 17 | //find suffix words 18 | while(start<=end1 && smallerWords[end1].equals(largerWords[end2])){ 19 | end1--; 20 | end2--; 21 | } 22 | return (start>end1); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SentenceToNumberPadSequence.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | String printSequence(String sentence) 4 | { 5 | // code here 6 | String output=""; 7 | 8 | String arr[] = {"2","22","222", "3","33","333","4","44","444","5","55","555","6","66","666", "7","77","777","7777","8","88","888","9","99","999","9999"}; 9 | 10 | for(int i=0;i> nums) { 3 | //min heap 4 | // [element, listIndex, elementIndex] 5 | PriorityQueue pq = new PriorityQueue<>(new Comparator(){ 6 | public int compare(int a[], int b[]){ 7 | return a[0] - b[0]; //inc 8 | } 9 | }); 10 | int k = nums.size(); 11 | int max = Integer.MIN_VALUE; 12 | 13 | for (int i = 0; i < k; i++) { 14 | int minVal = nums.get(i).get(0); 15 | pq.offer(new int[]{minVal, i, 0}); 16 | max = Math.max(max, minVal); 17 | } 18 | int[] minRange = {0, Integer.MAX_VALUE}; 19 | while (true) { 20 | int top[] = pq.poll(); 21 | int minElement = top[0], listIndex = top[1], elementIndex = top[2]; 22 | if (max - minElement < minRange[1] - minRange[0]) { 23 | minRange[0] = minElement; 24 | minRange[1] = max; 25 | } 26 | if (elementIndex == nums.get(listIndex).size() - 1) break; 27 | int next = nums.get(listIndex).get(elementIndex + 1); 28 | max = Math.max(max, next); 29 | pq.offer(new int[]{next, listIndex, elementIndex + 1}); 30 | } 31 | return minRange; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /SortThePeople.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String[] sortPeople(String[] names, int[] heights) { 3 | int n = heights.length; 4 | Integer index[] = new Integer[n]; 5 | //ON 6 | for(Integer i=0;i(){ 12 | public int compare(Integer a, Integer b){ 13 | return heights[b] - heights[a]; 14 | } 15 | }); 16 | String res[] = new String[n]; 17 | int i=0; 18 | // On 19 | for(Integer ind : index){ 20 | res[i] = names[ind]; 21 | i++; 22 | } 23 | return res; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SortingTheSentence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String sortSentence(String s) { 3 | String arr[] = s.split(" "); 4 | String temp[] = new String[arr.length]; 5 | String res=""; 6 | 7 | for(int i=0;iset = new HashSet<>(); 6 | backtrack(s,set,0); 7 | return maxCount; 8 | } 9 | // tc: n * 2^n 10 | // sc: n substring 11 | public void backtrack(String s, HashSet set, int index){ 12 | //base case 13 | int n = s.length(); 14 | if(index==n){ 15 | maxCount = Math.max(maxCount,set.size()); 16 | return; 17 | } 18 | //loop 19 | for(int i=index;imid) return false; 10 | sum+=nums[i]; 11 | if(sum>mid) 12 | { 13 | // increment number of subarray 14 | noOfSubarrays++; 15 | // start a new subarray if required size is exceeded 16 | sum=nums[i]; 17 | } 18 | } 19 | noOfSubarrays++; 20 | if(noOfSubarrays<=m) return true; 21 | return false; 22 | } 23 | 24 | public int splitArray(int[] nums, int m) { 25 | int start=Integer.MIN_VALUE,end=0; 26 | int n=nums.length; 27 | // calculate min and max of the range 28 | for(int i=0;i0){ 35 | prev = temp; 36 | temp = temp.next; 37 | extra--; 38 | } 39 | prev.next = null; //detach previous list 40 | res[i] = curHead; //insert head 41 | } 42 | return res; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /SquareRootUsingBinarySearch.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int x) { 3 | 4 | int start=1; 5 | int end=x; 6 | 7 | while(start<=end) 8 | { 9 | int mid = start+(end-start)/2; 10 | if(mid<=x/mid) start=mid+1; 11 | else end=mid-1; 12 | } 13 | return end; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /StringPermutations.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class StringPermutation { 3 | public static void main(String args[]) 4 | { 5 | String s="ABC"; 6 | permute(0,s); 7 | } 8 | public static String swap(String s,int a,int b) 9 | { 10 | char ch[] = s.toCharArray(); 11 | char p=ch[a]; 12 | ch[a]=ch[b]; 13 | ch[b]=p; 14 | return String.valueOf(ch); 15 | } 16 | public static void permute(int index, String s) 17 | { 18 | // bASE 19 | if(index==s.length()-1) 20 | { 21 | System.out.println(s); 22 | return; 23 | } 24 | 25 | // logic 26 | for(int i=index;i0) i-=j; 19 | j=0; 20 | } 21 | i++; 22 | if(j==n2) return true; 23 | } 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /StringSubsequences.java: -------------------------------------------------------------------------------- 1 | public class StringSubsequences 2 | { 3 | 4 | public static void main(String[] args) 5 | { 6 | subSequence("abc","",0); 7 | } 8 | 9 | public static void subSequence(String input, String output, int index) 10 | { 11 | 12 | // Base Case 13 | if(index>=input.length()) 14 | { 15 | for(int i=0;i=0) 24 | { 25 | if(A.charAt(p1)!=B.charAt(p2)) 26 | { 27 | res++; 28 | } 29 | else 30 | { 31 | p2--; 32 | } 33 | p1--; 34 | } 35 | return res; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /SubarraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraySum(int[] nums, int k) { 3 | 4 | HashMap map = new HashMap<>(); 5 | 6 | int sum=0,r=0; 7 | 8 | map.put(0,1); // key is 0 and value is 1 9 | 10 | for(int i=0;i res = new HashSet<>(); 7 | // Variable to calculate sum 8 | int sum=0; 9 | // Traversing the array 10 | for(int i=0;i temp; 5 | public SubrectangleQueries(int[][] rectangle) { 6 | arr=rectangle; 7 | temp = new ArrayList<>(); 8 | } 9 | 10 | public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { 11 | temp.add(new int[]{row1,col1,row2,col2,newValue}); 12 | } 13 | 14 | public int getValue(int row, int col) { 15 | int result = arr[row][col]; 16 | for(int a[]:temp) 17 | { 18 | if(row>=a[0] && row<=a[2] && col>=a[1] && col<=a[3]) 19 | { 20 | result=a[4]; 21 | } 22 | } 23 | return result; 24 | } 25 | } 26 | /** 27 | * Your SubrectangleQueries object will be instantiated and called as such: 28 | * SubrectangleQueries obj = new SubrectangleQueries(rectangle); 29 | * obj.updateSubrectangle(row1,col1,row2,col2,newValue); 30 | * int param_2 = obj.getValue(row,col); 31 | */ 32 | -------------------------------------------------------------------------------- /SumOfAllLengthSubarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOddLengthSubarrays(int[] arr) 3 | { 4 | int l=arr.length; 5 | int sum=0; 6 | for(int i=0;i=pos;i--) 7 | { 8 | arr[i+1]=arr[i]; 9 | } 10 | } 11 | public int[] createTargetArray(int[] nums, int[] index) { 12 | int target[] = new int[nums.length]; 13 | for(int i=0;i temp = new ArrayList<>(); 33 | int[] target = new int[nums.length]; 34 | 35 | for (int i = 0; i < nums.length; i++) temp.add(index[i], nums[i]); 36 | 37 | for (int j = 0; j < temp.size(); j++) target[j] = temp.get(j); 38 | 39 | return target; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /ThekthLexicographicalStringOfAllHappyStringsOfLengthN.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | String res; 3 | int count; 4 | public String getHappyString(int n, int k) { 5 | count=0; 6 | res=""; 7 | backtrack(n,k,new StringBuilder("")); 8 | return res; 9 | } 10 | public boolean backtrack(int n, int k, StringBuilder cur){ 11 | //base case 12 | if(cur.length() == n){ 13 | count++; 14 | if(count==k){ 15 | res = cur.toString(); 16 | return true; 17 | } 18 | return false; 19 | } 20 | for(char ch='a';ch<='c';ch++){ //2 21 | int len = cur.length(); 22 | if(len>0 && cur.charAt(len-1) == ch) continue; 23 | cur.append(ch); 24 | if(backtrack(n,k,cur)){ 25 | return true; 26 | } 27 | cur.deleteCharAt(cur.length()-1); 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ThreeWayPartitioning.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | //Function to partition the array around the range such 3 | //that array is divided into three parts. 4 | public static void swap(int arr[], int a, int b) 5 | { 6 | int x=arr[a]; 7 | arr[a]=arr[b]; 8 | arr[b]=x; 9 | } 10 | public void threeWayPartition(int array[], int a, int b) 11 | { 12 | // code here 13 | int l = 0; 14 | int r = array.length-1; 15 | int i=0; 16 | for(i=0;i<=r;i++) 17 | { 18 | if(array[i]b) 24 | { 25 | swap(array,r,i); 26 | r--; 27 | i--; 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] height) { 3 | int result=0; 4 | int i = 0, j = height.length - 1; 5 | int left_max = 0, right_max = 0; 6 | 7 | while(i<=j) 8 | { 9 | if(height[i]left_max) left_max=height[i]; 12 | else result+=left_max-height[i]; 13 | i++; 14 | } 15 | else 16 | { 17 | if(height[j]>right_max) right_max=height[j]; 18 | else result+=right_max-height[j]; 19 | j--; 20 | } 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /TreeBalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDepth(TreeNode root) 3 | { 4 | // Base Case 5 | if(root==null) return 0; 6 | // recursion calls 7 | int lh=maxDepth(root.left); 8 | int rh=maxDepth(root.right); 9 | // non favourable 10 | if(lh==-1 || rh==-1) return -1; 11 | if(Math.abs(lh-rh)>1) return -1; 12 | // depth of the tree 13 | return 1+Math.max(lh,rh); 14 | } 15 | 16 | public boolean isBalanced(TreeNode root) { 17 | if(maxDepth(root)==-1) return false; 18 | return true; 19 | 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /TreeBinaryTreePathToNode.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList solve(TreeNode A, int B) { 3 | ArrayList list = new ArrayList<>(); 4 | if(A==null) return list; 5 | travel(A,B,list); 6 | return list; 7 | } 8 | public static boolean travel(TreeNode root, int B,ArrayList list) 9 | { 10 | if(root==null) return false; 11 | 12 | list.add(root.val); 13 | 14 | if(root.val==B) return true; 15 | 16 | if(travel(root.left,B,list) || travel(root.right,B,list)) 17 | return true; 18 | list.remove(list.size()-1); 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /TreeBinaryTreePaths.java: -------------------------------------------------------------------------------- 1 | // Root to Leaf Paths 2 | class Solution { 3 | 4 | public List binaryTreePaths(TreeNode root) 5 | { 6 | ArrayList list = new ArrayList<>(); 7 | if(root==null) return list; 8 | paths(root,"",list); 9 | return list; 10 | } 11 | 12 | public static boolean paths(TreeNode root,String S, ArrayList list) 13 | { 14 | if(root.left==null && root.right==null) 15 | { 16 | list.add(S+root.val); 17 | return true; 18 | } 19 | if(root.left!=null) paths(root.left,S+root.val+"->",list); 20 | if(root.right!=null) paths(root.right,S+root.val+"->",list); 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /TreeBottomView.java: -------------------------------------------------------------------------------- 1 | class Pair{ 2 | int vertical; 3 | Node node; 4 | Pair(Node n,int v) 5 | { 6 | vertical = v; 7 | node = n; 8 | } 9 | } 10 | class Solution 11 | { 12 | //Function to return a list containing the bottom view of the given tree. 13 | public ArrayList bottomView(Node root) 14 | { 15 | // Code here 16 | 17 | ArrayList ans = new ArrayList<>(); 18 | if(root == null) return ans; 19 | TreeMap map = new TreeMap<>(); 20 | Queue q = new LinkedList<>(); 21 | q.add(new Pair(root,0)); 22 | while(!q.isEmpty()) { 23 | Pair temp = q.remove(); 24 | int v = temp.vertical; 25 | Node n = temp.node; 26 | map.put(v, n.data); 27 | if(n.left != null) { 28 | q.add(new Pair(n.left,v-1)); 29 | } 30 | if(n.right != null) { 31 | q.add(new Pair(n.right,v+1)); 32 | } 33 | } 34 | 35 | for (Map.Entry entry : map.entrySet()) { 36 | ans.add(entry.getValue()); 37 | } 38 | return ans; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /TreeBoundaryTraversalBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | ArrayList printBoundary(Node node) 4 | { 5 | ArrayList list = new ArrayList<>(); 6 | if(node.left!=null || node.right!=null) list.add(node.data); 7 | leftBoundary(node,list); 8 | leafNodes(node,list); 9 | rightBoundary(node,list); 10 | return list; 11 | } 12 | 13 | void leftBoundary(Node node, ArrayList list) 14 | { 15 | node=node.left; 16 | if(node==null) return; 17 | while(node!=null) 18 | { 19 | if(node.left!=null || node.right!=null ) list.add(node.data); 20 | if(node.left!=null) node=node.left; 21 | else node=node.right; 22 | } 23 | } 24 | 25 | void rightBoundary(Node node, ArrayList list) 26 | { 27 | node=node.right; 28 | Stack stack = new Stack(); 29 | if(node==null) return; 30 | while(node!=null) 31 | { 32 | if(node.left!=null || node.right!=null ) stack.push((node.data)); 33 | if(node.right!=null) node=node.right; 34 | else node=node.left; 35 | } 36 | while(!stack.isEmpty()) 37 | { 38 | list.add(stack.pop()); 39 | } 40 | } 41 | 42 | void leafNodes(Node node, ArrayList list) 43 | { 44 | if(node.left==null && node.right==null) 45 | { 46 | list.add(node.data); 47 | return; 48 | } 49 | if(node.left!=null) leafNodes(node.left,list); 50 | if(node.right!=null) leafNodes(node.right,list); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /TreeDiameter.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int maxi=0; 3 | public int diameterOfBinaryTree(TreeNode root) { 4 | 5 | if(root == null) return 0; 6 | int ans[]=new int[1]; 7 | findDiameter(root,ans); 8 | return ans[0]; 9 | 10 | } 11 | public int findDiameter(TreeNode root, int maxi[]) 12 | { 13 | if(root == null) return 0; 14 | int left = findDiameter(root.left,maxi); 15 | int right = findDiameter(root.right,maxi); 16 | maxi[0]=Math.max(maxi[0],left+right); 17 | return 1+Math.max(left,right); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /TreeInOrderIterative.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List inorderTraversal(TreeNode root) { 3 | Stack stack = new Stack(); 4 | List inOrder = new ArrayList(); 5 | if(root==null) return inOrder; 6 | while(true) 7 | { 8 | if(root!=null) 9 | { 10 | stack.push(root); 11 | root=root.left; 12 | } 13 | else 14 | { 15 | if(stack.isEmpty()) break; 16 | root=stack.pop(); 17 | inOrder.add(root.val); 18 | root=root.right; 19 | } 20 | } 21 | return inOrder; 22 | 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /TreeInorder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void inorder(TreeNode node,List list) 3 | { 4 | if(node==null) return; 5 | inorder(node.left,list); 6 | list.add(node.val); 7 | inorder(node.right,list); 8 | } 9 | public List inorderTraversal(TreeNode root) { 10 | List list = new ArrayList(); 11 | inorder(root,list); 12 | return list; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TreeLeftViewBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Tree 2 | { 3 | //Function to return list containing elements of left view of binary tree. 4 | ArrayList leftView(Node root) 5 | { 6 | // Your code here 7 | ArrayList list = new ArrayList<>(); 8 | if(root==null) return list; 9 | Queue queue = new LinkedList<>(); 10 | queue.add(root); 11 | while(!queue.isEmpty()) 12 | { 13 | int level = queue.size(); 14 | for(int i=0;i> levelOrder(TreeNode root) { 3 | List> list = new ArrayList>(); 4 | if(root==null) return list; 5 | Queue queue = new LinkedList(); 6 | queue.offer(root); 7 | while(!queue.isEmpty()) 8 | { 9 | int nodesPresent=queue.size(); 10 | List sublist = new ArrayList(); 11 | for(int i=0;i solve(TreeNode A, int B) { 3 | ArrayList list = new ArrayList<>(); 4 | if(A==null) return list; 5 | travel(A,B,list); 6 | return list; 7 | } 8 | public static boolean travel(TreeNode root, int B,ArrayList list) 9 | { 10 | if(root==null) return false; 11 | 12 | list.add(root.val); 13 | 14 | if(root.val==B) return true; 15 | 16 | if(travel(root.left,B,list) || travel(root.right,B,list)) 17 | return true; 18 | list.remove(list.size()-1); 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /TreePostorder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void postorder(TreeNode node,List list) 3 | { 4 | if(node==null) return; 5 | postorder(node.left,list); 6 | postorder(node.right,list); 7 | list.add(node.val); 8 | } 9 | public List postorderTraversal(TreeNode root) { 10 | List list = new ArrayList(); 11 | postorder(root,list); 12 | return list; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TreePreOrderIterative.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List preorderTraversal(TreeNode root) { 3 | Stack stack = new Stack<>(); 4 | List preOrder = new ArrayList(); 5 | if(root==null) return preOrder; 6 | stack.push(root); 7 | while(!stack.isEmpty()) 8 | { 9 | root=stack.pop(); 10 | preOrder.add(root.val); 11 | if(root.right!=null) 12 | { 13 | stack.push(root.right); 14 | } 15 | if(root.left!=null) 16 | { 17 | stack.push(root.left); 18 | } 19 | } 20 | return preOrder; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /TreePreorder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void preorder(TreeNode root,List list) 3 | { 4 | if(root==null) return; 5 | list.add(root.val); 6 | preorder(root.left,list); 7 | preorder(root.right,list); 8 | } 9 | public List preorderTraversal(TreeNode root) { 10 | List list = new ArrayList(); 11 | preorder(root,list); 12 | return list; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TreeRepBinary.java: -------------------------------------------------------------------------------- 1 | public class TreeRepBinary 2 | { 3 | public static void main(String[] args) { 4 | Node root = new Node(1); 5 | root.left = new Node(2); 6 | root.right = new Node(3); 7 | root.left.left = new Node(4); 8 | } 9 | } 10 | class Node 11 | { 12 | int data; 13 | Node left; 14 | Node right; 15 | public Node(int data) 16 | { 17 | this.data=data; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /TreeRightViewBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List rightSideView(TreeNode root) { 3 | 4 | // Your code here 5 | List list = new ArrayList<>(); 6 | if(root==null) return list; 7 | Queue queue = new LinkedList<>(); 8 | queue.add(root); 9 | while(!queue.isEmpty()) 10 | { 11 | int level = queue.size(); 12 | for(int i=0;i topView(Node root) 16 | { 17 | // add your code 18 | TreeMap map = new TreeMap<>(); 19 | 20 | ArrayList list = new ArrayList<>(); 21 | 22 | if(root==null) return list; 23 | 24 | Queue q = new LinkedList<>(); 25 | 26 | q.add(new Pair(root,0)); 27 | 28 | while(!q.isEmpty()) 29 | { 30 | Pair p = q.remove(); 31 | 32 | int v = p.vertical; 33 | 34 | Node node = p.node; 35 | 36 | if(map.get(v)==null) 37 | { 38 | map.put(v,node.data); 39 | } 40 | 41 | if(node.left!=null) 42 | { 43 | q.add(new Pair(node.left,v-1)); 44 | } 45 | 46 | if(node.right!=null) 47 | { 48 | q.add(new Pair(node.right,v+1)); 49 | } 50 | } 51 | for (Map.Entry entry : map.entrySet()) { 52 | list.add(entry.getValue()); 53 | } 54 | return list; 55 | 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /TreeZigZagBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> zigzagLevelOrder(TreeNode root) { 3 | 4 | List> list = new ArrayList>(); 5 | 6 | if(root == null) return list; 7 | 8 | boolean flag = true; 9 | 10 | Queue queue = new LinkedList(); 11 | 12 | queue.add(root); 13 | 14 | while(!queue.isEmpty()) 15 | { 16 | int level = queue.size(); 17 | List subList = new ArrayList<>(); 18 | for(int i=0;i set = new HashSet<>(); 11 | int toFind=X-A[i]; 12 | for(int j=i+1;j productMap = new HashMap<>(); 4 | int n = nums.length; 5 | for(int i=0;i entry : productMap.entrySet()){ 13 | int product = entry.getKey(); 14 | int count = entry.getValue(); 15 | if(count>=2){ 16 | int comb = (count * (count-1))/2; 17 | ans = ans + comb*8; 18 | } 19 | } 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /TwoSumIISortedArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | int start=0; 4 | int end=numbers.length-1; 5 | while(start map = new HashMap<>(); 4 | // N + M 5 | for(String word : s1.split(" ")){ 6 | map.put(word,map.getOrDefault(word,0)+1); 7 | } 8 | for(String word : s2.split(" ")){ 9 | map.put(word,map.getOrDefault(word,0)+1); 10 | } 11 | ArrayList list = new ArrayList<>(); 12 | // n+m 13 | for(Map.Entry entry :map.entrySet()){ 14 | if(entry.getValue()==1){ 15 | list.add(entry.getKey()); 16 | } 17 | } 18 | String res[] = new String[list.size()]; 19 | // K 20 | list.toArray(res); 21 | return res; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ValidParenthesis.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean isOpen(char ch) 4 | { 5 | switch(ch) 6 | { 7 | case '(': 8 | return true; 9 | case '{': 10 | return true; 11 | case '[': 12 | return true; 13 | } 14 | return false; 15 | } 16 | 17 | public boolean isSame(char str, char stk) 18 | { 19 | if(isOpen(stk)) 20 | { 21 | if(str=='}' && stk=='{') return true; 22 | else if(str==')' && stk=='(') return true; 23 | else if(str==']' && stk=='[') return true; 24 | } 25 | return false; 26 | } 27 | 28 | public boolean isValid(String s) { 29 | 30 | Stack stack = new Stack<>(); 31 | for(int i=0;i valueEqualToIndex(int arr[], int n) { 3 | // code here 4 | ArrayList list = new ArrayList<>(); 5 | for(int i=0;i wordSubsets(String[] words1, String[] words2) { 3 | int freq[] = new int[26]; 4 | for(String word : words2){ //M 5 | int temp[] = getFreq(word); //p 6 | for(int i=0;i<26;i++){ //26 7 | freq[i] = Math.max(freq[i], temp[i]); 8 | } 9 | } 10 | List res = new ArrayList<>(); 11 | for(String word : words1){ //n 12 | int temp[] = getFreq(word); //p 13 | boolean flag=true; 14 | for(int i=0;i<26;i++){ //26 15 | if(freq[i] > temp[i]){ 16 | flag = false; 17 | break; 18 | } 19 | } 20 | if(flag){ 21 | res.add(word); 22 | } 23 | } 24 | return res; 25 | } 26 | public int[] getFreq(String word){ 27 | int freq[] = new int[26]; 28 | for(int i=0;i stack = new Stack<>(); 6 | Stack unlocked = new Stack<>(); 7 | for(int i=0;i checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { 3 | boolean mat[][] = new boolean[numCourses][numCourses]; 4 | for(int i=0;i ans = new ArrayList<>(); 18 | for(int i=0;i6*n){ 10 | return new int[0]; 11 | } 12 | int avg = sum/n; 13 | int rem = sum%n; 14 | int res[] = new int[n]; 15 | for(int i=0;i0){ 18 | res[i]++; 19 | rem--; 20 | } 21 | } 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /gridGame.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long gridGame(int[][] grid) { 3 | //find top sum 4 | long topSum=0; 5 | int n = grid[0].length; 6 | for(int i=0;i map = new HashMap<>(); 11 | 12 | for(int i=0;i> list = new ArrayList<>(); 11 | HashMap group = new HashMap<>(); 12 | int groupIndex = 0; 13 | list.add(new LinkedList<>()); 14 | list.get(groupIndex).offer(temp[0]); 15 | group.put(temp[0],groupIndex); 16 | for(int i=1;i limit){ 19 | groupIndex++; 20 | list.add(new LinkedList<>()); 21 | } 22 | group.put(temp[i],groupIndex); 23 | list.get(groupIndex).offer(temp[i]); 24 | } 25 | 26 | for(int i=0;i queue = new LinkedList<>(); 13 | for(int i=0;i=0 && nr=0 && nc 0 22 | //visited ->0 23 | if(r<0 || r>=rows || c<0 || c>= cols || grid[r][c] == 0){ 24 | return 0; 25 | } 26 | int ans = grid[r][c]; 27 | grid[r][c] = 0; 28 | ans += dfs(r-1,c,grid) + dfs(r,c+1,grid) + dfs(r+1,c,grid) + dfs(r,c-1,grid); 29 | return ans; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /minimizeXor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimizeXor(int num1, int num2) { 3 | //find set bits in num2 4 | int setBits = Integer.bitCount(num2); //n & n-1 logN 5 | int bit=31; 6 | int res=0; 7 | while(bit>=0 && setBits>0){ 8 | //check if bit is set in num1 and if so, set the bit in res 9 | if((num1 & (1 << bit)) !=0){ 10 | res = res | (1 << bit); 11 | setBits--; 12 | } 13 | bit--; 14 | } 15 | bit = 0; 16 | // 1011001 17 | while(setBits>0 && bit<=32){ 18 | if((num1 & (1 << bit)) == 0){ 19 | res = res | (1 << bit); 20 | setBits--; 21 | } 22 | bit++; 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /minimumAdjacentSwapsForBalanceBrackets.java: -------------------------------------------------------------------------------- 1 | //User function Template for Java 2 | class Solution{ 3 | static int minimumNumberOfSwaps(String S){ 4 | // code here 5 | int open=0; 6 | int close=0; 7 | int swap=0; 8 | int imbalance=0; 9 | for(int i=0;i0) 15 | { 16 | swap+=imbalance; 17 | imbalance--; 18 | } 19 | } 20 | else 21 | { 22 | close++; 23 | imbalance=close-open; 24 | } 25 | } 26 | return swap; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /minimumCostToConvertString1.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumCost(String source, String target, char[] original, char[] changed, int[] cost) { 3 | int[][] dis = new int[26][26]; 4 | for (int i = 0; i < 26; i++) { 5 | Arrays.fill(dis[i], Integer.MAX_VALUE); 6 | dis[i][i] = 0; 7 | } 8 | for (int i = 0; i < cost.length; i++) { 9 | int start = original[i] - 'a'; 10 | int end = changed[i] - 'a'; 11 | dis[start][end] = Math.min(dis[start][end], cost[i]); 12 | } 13 | for (int k = 0; k < 26; k++) { 14 | for (int i = 0; i < 26; i++) 15 | if (dis[i][k] < Integer.MAX_VALUE) { 16 | for (int j = 0; j < 26; j++) { 17 | if (dis[k][j] < Integer.MAX_VALUE) { 18 | dis[i][j] = Math.min(dis[i][j], dis[i][k] + dis[k][j]); 19 | } 20 | } 21 | } 22 | } 23 | long ans = 0L; 24 | for (int i = 0; i < source.length(); i++) { 25 | int c1 = source.charAt(i) - 'a'; 26 | int c2 = target.charAt(i) - 'a'; 27 | if (dis[c1][c2] == Integer.MAX_VALUE) { 28 | return -1L; 29 | } else { 30 | ans += (long)dis[c1][c2]; 31 | } 32 | } 33 | return ans; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /minimumSwapsToGroup1sTogether.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(int[] nums) { 3 | //window size - count of 1 4 | int windowSize = 0; 5 | for(int num : nums){ 6 | windowSize+=num; 7 | } 8 | //find zeros in first window 9 | int curZeros=0; 10 | for(int i=0;i timePoints) { 3 | boolean mins[] = new boolean[1440]; 4 | for(String time : timePoints){ 5 | int h = Integer.parseInt(time.substring(0,2)); 6 | int m = Integer.parseInt(time.substring(3,5)); 7 | int minutes = h*60 + m; 8 | if(mins[minutes]) return 0; 9 | mins[minutes] = true; 10 | } 11 | int prev=-1; 12 | int firstVal=-1; 13 | int minDiff = Integer.MAX_VALUE; 14 | for(int cur = 0;cur < 1440; cur++){ 15 | if(mins[cur]){ 16 | if(prev==-1){ 17 | firstVal = cur; 18 | prev = cur; 19 | }else{ 20 | minDiff = Math.min(minDiff,cur-prev); 21 | prev = cur; 22 | } 23 | } 24 | } 25 | if(prev!=-1){ 26 | minDiff = Math.min(minDiff,1440 + firstVal - prev); 27 | } 28 | return minDiff; 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /myCalendar1.java: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | TreeMap map; 3 | public MyCalendar() { 4 | map = new TreeMap<>(); 5 | } 6 | 7 | public boolean book(int start, int end) { 8 | Integer prevVal = map.lowerKey(end); 9 | if(prevVal!=null && start <= map.get(prevVal)-1){ 10 | return false; 11 | } 12 | map.put(start,end); 13 | return true; 14 | } 15 | } 16 | 17 | /** 18 | * Your MyCalendar object will be instantiated and called as such: 19 | * MyCalendar obj = new MyCalendar(); 20 | * boolean param_1 = obj.book(start,end); 21 | */ 22 | -------------------------------------------------------------------------------- /spiralMatrix3.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { 3 | int directions[][] = {{0,1},{1,0},{0,-1},{-1,0}}; 4 | int n = rows*cols; 5 | int res[][] = new int[n][2];//[[r,c],[r1,c1]... 6 | res[0][0] = rStart; 7 | res[0][1] = cStart; 8 | int count=1; 9 | int step=1; 10 | int index=0; 11 | 12 | while(count=0 && rStart=0 && cStart= leftCol ; col--) { 27 | if(head==null) break; 28 | matrix[bottomRow][col] = head.val; 29 | head = head.next; 30 | } 31 | bottomRow--; 32 | 33 | 34 | for (int row = bottomRow; row >= topRow ; row--) { 35 | if(head==null) break; 36 | matrix[row][leftCol] = head.val; 37 | head = head.next; 38 | } 39 | leftCol++; 40 | } 41 | 42 | return matrix; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /sumOfDigitsOfStringAfterConvert.java: -------------------------------------------------------------------------------- 1 | // 1st approach 2 | class Solution { 3 | public int getLucky(String s, int k) { 4 | StringBuilder sb = new StringBuilder(); 5 | for(char ch : s.toCharArray()){ 6 | sb.append(ch-96); 7 | } 8 | while(k>0){ 9 | int sum=0; 10 | for(int i=0;i0){ //log base 10 (num) 29 | sum1 += (num%10); 30 | num/=10; 31 | } 32 | } 33 | sb.append(sum1); 34 | while(k>1){ //k*z 35 | int sum=0; 36 | for(int i=0;i