├── .vscode ├── c_cpp_properties.json ├── launch.json ├── settings.json └── tasks.json ├── 01 (Mathematics(Number Theory) & Arrays) & Sliding Window ├── Arrays │ ├── 01) twoSum.cpp │ ├── 02) bestTimeToBuyAndSellStock.cpp │ ├── 03) mergeSortedArrays.cpp │ ├── 04) moveZeroes.cpp │ ├── 05) bestTimeToBuyAndSellStock(ii).cpp │ ├── 06) runningSumOf1-dArray.cpp │ ├── 07) findPivotIndex.cpp │ ├── 08) majorityElement.cpp │ ├── 09) fibonacciNumbers.cpp │ ├── 0Arrays.txt │ ├── 10) squaresOfASortedArray.cpp │ ├── 11) pascalsTriangle.cpp │ ├── 12) removeDuplicatesFromSortedArray.cpp │ ├── 13) mergeIntervals.cpp │ ├── 14) 3sum.cpp │ ├── 15) productOfArrayExceptSelf.cpp │ ├── 16) subarraySumEqualsK.cpp │ ├── 17) nextPermutation.cpp │ ├── 18) spiralMatrix.cpp │ ├── 19) containerWithMostWater.cpp │ ├── 20) trappingRainWater.cpp │ ├── 21) rotateImage.cpp │ ├── 22) removeDuplicatesFromSortedArray(ii).cpp │ ├── 23) threeSumClosest.cpp │ ├── 24) pairOfSongsWithTotalTimeDivisibleBy60.cpp │ ├── 25) fourSum.cpp │ ├── 26) findTheDuplicateNumber.cpp │ ├── 27) combinationSum.cpp │ ├── 28) jumpGame-ii.cpp │ ├── 29) maximumPointsYouCanObtainFromCards.cpp │ ├── 30) maxAreaOfPeiceOfCakeAfterHorizontalAndVerticalCuts.cpp │ ├── 31) findAllDuplicatesInAnArray.cpp │ ├── 32) kDiffPairsInAnArray.cpp │ ├── 33) jumpGame.cpp │ ├── 34) subarraySumsDivisibleByK.cpp │ ├── 35) MaximumSumSubArray-Kadane's Algo.cpp │ ├── 36) maximumProductSubarray.cpp │ ├── 37) countInversions.cpp │ ├── 38) reversePairs.cpp │ ├── 39) toeplitzMatrix.cpp │ ├── 40) whereWillTheBallFall.cpp │ ├── 41) sortTheMatrixDiagonally.cpp │ ├── 42) diagonalTraversal.cpp │ ├── 43) firstMissingPositive.cpp │ ├── 44) maxValueOfEquation.cpp │ ├── 45) countSubarraysWithXorAsK.cpp │ ├── Prefix Sum │ │ ├── 01) sumOfAllOddLengthSubarray.cpp │ │ ├── 02) rangeSumQueryImmutable.cpp │ │ ├── 03) rangeSumQuery2D-Inmutable.cpp │ │ ├── 04) rangeSumQueryMutable.cpp │ │ ├── 05) numberOfWaysToSplitArray.cpp │ │ ├── 06) matrixBlockSum.cpp │ │ └── prefixSum.cpp │ ├── Vector.cpp │ ├── a_RotationOfArray.cpp │ ├── pairWithPositiveNegativeValues.cpp │ └── twoPointerMethod.cpp ├── Mathematics(Number Theory) │ ├── 01) digitConcept.cpp │ ├── 02) primalityTest.cpp │ ├── 03) gcd,lcm.cpp │ ├── 0Maths.txt │ ├── binaryExponentiation.cpp │ ├── d_PrintAllSubStrings.cpp │ └── primeFactorisation.cpp └── Sliding Window │ ├── 00) slidingWindow.cpp │ ├── 01) maximumSumSubarrayOfSizeK.cpp │ ├── 02) firstNegativeIntegerInEveryWindow.cpp │ ├── 03) slidingWindowMaximum.cpp │ ├── 04) countOccurencesOfAnagrams.cpp │ ├── 05) longestSubarrayWithSumEqualsK.cpp │ ├── 06) longestSubstringWithK-UniqueCharacters.cpp │ ├── 07) longestSubstringWithNoRepeatingCharacters.cpp │ ├── 08) pickToys or fruitsIntoBasket.cpp │ ├── 09) minimumWindowSubstring.cpp │ ├── 10) maximumSubarray.cpp │ └── 11) takeKOfEachCharacterFromLeftAndRight.cpp ├── 02 (Searching & Sorting) ├── Searching │ ├── Binary Search │ │ ├── 00) binarySearch.cpp │ │ ├── 01) finding_occurence.cpp │ │ ├── 02) numberOfTimesSortedArrayIsRotated.cpp │ │ ├── 03) findMinimumInRotatedSortedArray.cpp │ │ ├── 04) findMinimumInRotatedSortedArray(ii).cpp │ │ ├── 05) searchInRotatedSortedArray.cpp │ │ ├── 06) searchInRotatedSortedArray(ii).cpp │ │ ├── 07) searchInsertPosition.cpp │ │ ├── 08) upperBound and lowerBound.cpp │ │ ├── 09) findPeakElement.cpp │ │ ├── 10) searchA2DMatrix.cpp │ │ ├── 11) searchA2DMatrix(ii).cpp │ │ ├── 12) searchInANearlySortedArray.cpp │ │ ├── 13) floorInASortedArray.cpp │ │ ├── 14) ceilInASortedArray.cpp │ │ ├── 15) findAnElementInInfiniteSortedArray.cpp │ │ ├── 16) indexOfFirstOneInBinarySortedInfiniteArray.cpp │ │ ├── 17) minimumDifferenceElementInSortedArray.cpp │ │ ├── 18) binarySearchOnAnswer.cpp │ │ ├── 19) allocatingMinimumNumberOfPages or capacityToShipPackageswithinD-days.cpp │ │ ├── 20) medianOfTwoSortedArrays.cpp │ │ └── 21) pow(x,n).cpp │ ├── linearSearch.cpp │ ├── linearSearch.exe │ ├── peakElement.cpp │ └── searching.txt ├── Sorting │ ├── CustomSort │ │ ├── 00) customSort.cpp │ │ ├── 01) ArrangeGivenNumbersToFormLargestNumber.cpp │ │ └── 02) sortArrayAccToCountOfSetBits │ ├── countingSort.cpp │ ├── inPLaceSorting │ │ ├── 01) selectionSort.cpp │ │ ├── 02) bubbleSort.cpp │ │ ├── 03) insertionSort.cpp │ │ ├── 04) quickSort.cpp │ │ └── heapSort.cpp │ ├── mergeSort.cpp │ ├── radixSort.cpp │ ├── sortFunctionInC++STL.cpp │ └── sorting.cpp └── TimeComplexity.txt ├── 03 (String & Its algorithms) ├── String & String Algorithms │ ├── Basic Algos │ │ ├── rabinKarpStringMatchingAlgorithm.cpp │ │ ├── slidingWindowAlgorithm.cpp │ │ └── stringHashing.cpp │ ├── Intermediate Algos │ │ ├── Z-Function.cpp │ │ ├── knuthMorrisPratt(KMP)stringMatchingAlgorithm.cpp │ │ └── trieDS.cpp │ ├── Practice Problems │ │ ├── 01) goalParserInterpretation.cpp │ │ ├── 02) student-attendance-record-i.cpp │ │ ├── 03) longestCommonPrefix.cpp │ │ ├── 04) validPalindrome(ii).cpp │ │ ├── 05) romanToInteger.cpp │ │ ├── 06) needleInTheHaystack.cpp │ │ ├── 07) implement-strStr().cpp │ │ ├── 08) applyKMPhackerearth.cpp │ │ ├── 09) adaAndPet.cpp │ │ ├── 10) longestSubstringWithoutRepeartingCharacters.cpp │ │ ├── 11) groupAnagrams.cpp │ │ ├── 12) integerToRoman.cpp │ │ ├── 13) reverseWordsInAString.cpp │ │ ├── 14) zigzagConversions.cpp │ │ └── wordQueries.cpp │ └── string.cpp ├── anagram.cpp ├── anagram.exe ├── booleanMatrixProblem.cpp └── sumOfTwoLargeNumbers.cpp ├── 04 (Linked List) ├── 01) linkedList.cpp ├── 02) insertionInSinglyLinkedList.cpp ├── 03) deletionInSinglyLinkedList.cpp ├── 04) doublyLinkedList.cpp ├── 05) XOR-LinkedLists.cpp ├── 06) circularLinkedList.cpp └── Practice Problems │ ├── 01) deleteNodeInALinkedList.cpp │ ├── 02) middleOfTheLinkedList.cpp │ ├── 03) convertingBinaryNumberInALinkedListToInteger.cpp │ ├── 04) designHashset.cpp │ ├── 05) designHashmap.cpp │ ├── 06) reverseLinkedList.cpp │ ├── 07) reverseLinkedList(ii).cpp │ ├── 08) reverseNodesInK-Groups.cpp │ ├── 09) mergeTwoSortedLists.cpp │ ├── 10) mergeK-sortedLinkedList.cpp │ ├── 11) removeDuplicatesFromSortedList.cpp │ ├── 12) linkedListCycle.cpp │ ├── 13) linkedListCycle(ii).cpp │ ├── 14) intersectionOfTwoLinkedLists.cpp │ ├── 15) palindromeLinkedList.cpp │ ├── 16) removeLinkedListElements.cpp │ ├── 17) addTwoNumbers.cpp │ ├── 18) addTwoNumber(ii).cpp │ ├── 19) copyListWithRandomPointer.cpp │ ├── 20) reorderList.cpp │ ├── 21) removeNthNodeFromTheEnd.cpp │ ├── 22) flatteningALinkedList(GFG).cpp │ ├── 23) flattenAMultiLevelDoublyLinkedList.cpp │ ├── 24) partitionList.cpp │ ├── 25) removeDuplicatesFromSortedList(ii).cpp │ ├── 26) oddEvenLinkedList.cpp │ ├── 27) sortList.cpp │ ├── 28) insertionSortList.cpp │ ├── 29) swapNodesInPairs.cpp │ ├── 30) rotateList.cpp │ └── 31) swapNodesInLL.cpp ├── 05 (Stacks and Queue and Heap Or Priority Queue ├── Heap and Priority Queue │ ├── Practice Problems │ │ ├── 01) buildMinHeap.cpp │ │ ├── 02) kthSmallestElement.cpp │ │ ├── 03) kthLargestElement.cpp │ │ ├── 04) isBinaryTreeHeap.cpp │ │ ├── 05) mergeTwoBinaryMaxHeaps.cpp │ │ ├── 06) minumumCostOfRopes.cpp │ │ ├── 07) bst to min or max heap.cpp │ │ ├── 08) mergeK-SortedArrays.cpp │ │ ├── 09) smallestRangeCoveringElementsFromK-Lists.cpp │ │ ├── 10) sortK-NearlySortedArray.cpp │ │ ├── 11) findKClosestElements.cpp │ │ ├── 12) topK-FrequentElements.cpp │ │ ├── 13) frequencySort.cpp │ │ ├── 14) K-ClosestPointsToOrigin.cpp │ │ ├── 15) MedianInADataStream.cpp │ │ ├── 16) singleThreadedCPU.cpp │ │ ├── 17) topKFrequentWords.cpp │ │ ├── 18) furthestBuildingYouCanReach.cpp │ │ ├── 19) IPC-Trainers.cpp │ │ ├── 20) reorganiseString.cpp │ │ └── 21) maximumSubsequenceScore.cpp │ ├── heap.cpp │ ├── heapSort.cpp │ ├── heapifyAlgorithm.cpp │ └── priorityqueue.cpp ├── Queues │ ├── Practice Problems │ │ └── 01) slidingWindowMaximum.cpp │ └── queue.cpp └── Stacks │ ├── Practice Problems │ ├── 01) nextGreaterElement(i).cpp │ ├── 02) nextGreaterElement(ii).cpp │ ├── 03) nextGreaterElement(iii).cpp │ ├── 04) nearestGreaterToLeft.cpp │ ├── 05) nearestSmallerElement.cpp │ ├── 05) stockSpanProblem.cpp │ ├── 06) dailyTemperatures.cpp │ ├── 07) largestRectangleInHistogram.cpp │ ├── 08) maximalRectangle.cpp │ ├── 09) trappingRainWater.cpp │ ├── 10) minStack.cpp │ ├── 11) theCelebrityProblem.cpp │ ├── 12) longestValidParentheses.cpp │ ├── 13) IterativeTowerOfHanoi.cpp │ ├── 14) ImplementStackUsingHeap.cpp │ ├── 15) ImplementStackUsingQueues.cpp │ ├── 16) ImplementQueueUsingStacks.cpp │ ├── 17) validParentheses.cpp │ ├── 18) backspaceStringCompare.cpp │ ├── 19) removeAllAdjacentDuplicatesInAString.cpp │ ├── 20) removeAllAdjacentDuplicatesInAString(ii).cpp │ ├── 21) flattenNestedListIterator.cpp │ ├── 22) sumOfSubarrayMinimums.cpp │ └── 23) evaluateReversePolistNotation.cpp │ ├── infix-prefix-postfix.cpp │ └── stacks.cpp ├── 06 (Recursion and Backtracking) ├── Practice Problems │ ├── 01) heightOfABinaryTree.cpp │ ├── 02) sortAnArray.cpp │ ├── 03) sortAStack.cpp │ ├── 04) deleteMiddleElementOfAStack.cpp │ ├── 05) reverseAStack.cpp │ ├── 06) kth-symbolInGrammer.cpp │ ├── 07) towerOfHanoi.cpp │ ├── 08) subsetsOrSubsequenceOfAString.cpp │ ├── 09) subsets.cpp │ ├── 10) subsets2.cpp │ ├── 11) permutationWithSpaces.cpp │ ├── 12) letterCasePermutation.cpp │ ├── 13) generateParentheses.cpp │ ├── 14) printN-bitBinaryNumbersHavingMore1Than0.cpp │ ├── 15) josephusProblem.cpp │ ├── 16) combinationSum.cpp │ ├── 17) combinationSum2.cpp │ ├── 18) subsetSumGFG.cpp │ ├── 19) permutations.cpp │ ├── 20) permutations(II).cpp │ ├── 21) N-Queens.cpp │ ├── 22) sudokuSolver.cpp │ ├── 23) m-coloringProblem.cpp │ ├── 24) ratInAMazeProblem.cpp │ ├── 25) kthPermutationSequence.cpp │ ├── 26) combinations.cpp │ ├── 27) beautifulArrangement.cpp │ ├── 28) decodeString.cpp │ ├── 29) knightTour.cpp │ ├── 30) wordSearch.cpp │ └── 31) uniquePaths(iii).cpp ├── backtracking.cpp └── recursion.cpp ├── 07 (Design) └── Practice Problems │ ├── 01) designBrowserHistory.cpp │ ├── 02) LRU-Cache.cpp │ ├── 03) LFU-Cache.cpp │ ├── 04) findMedianFromDataStream.cpp │ ├── 05) encodeDecodeTinyURL.cpp │ ├── 06) insertDeleteGetRandom.cpp │ └── 07) insertDeleteGetRandomDuplicatesAllowed.cpp ├── 08 (Trees) ├── 01) binaryTreePreorderTraversal.cpp ├── 02) binaryTreePostorderTraversal.cpp ├── 03) binaryTreeInorderTraversal.cpp ├── 04) binaryTreeLevelorderTraversal.cpp ├── 05) balancedBinaryTree.cpp ├── 06) diameterOfBinaryTree.cpp ├── 07) binaryTreeMaximumPathSum.cpp ├── 08) sameTree.cpp ├── 09) binaryTreeZigZagLevelorderTraversal.cpp ├── 10) boundaryTraversalInBinaryTree.cpp ├── 11) verticalOrderTraversalInABinaryTree.cpp ├── 12) topViewOfBinaryTree.cpp ├── 13) bottomViewOfBinaryTree.cpp ├── 14) binaryTreeRightSideView.cpp ├── 15) symmetricTree.cpp ├── 16) pathToGivenNode.cpp ├── 17) lowestCommonAncestorOfaBinaryTree.cpp ├── 18) maximumWidthOfBinaryTree.cpp ├── 19) childrenSumProperty.cpp ├── 20) sumTree.cpp ├── 21) allNodesK-DistanceInBinaryTree.cpp ├── 22) minimumTimeTakenToBurnABinaryTreeFromANode.cpp ├── 23) countCompleteTreeNodes.cpp ├── 24) requirementsNeededToConstructUniqueBinaryTree.cpp ├── 25) constructBinaryTreeFromPreorderAndInorder.cpp ├── 26) constructBinaryTreeFromPostorderAndInorder.cpp ├── 27) constructBinaryTreeFromPreorderAndPostorder.cpp ├── 28) serialiseAndDeserialiseBinaryTree.cpp ├── 29) flattenBinaryTreeToLinkedList.cpp ├── 30) searchInBinarySearchTree.cpp ├── 31) ceilFromBinarySearchTree.cpp ├── 32) floorFromBST.cpp ├── 33) insertInBST.cpp ├── 34) deleteNodeInBST.cpp ├── 35) kthSmallestElementInBST.cpp ├── 36) validateBinarySearchTree.cpp ├── 37) LCAofBST.cpp ├── 38) constructBSTfromPreorderTraversal.cpp ├── 39) inorderSuccessorInBST.cpp ├── 3b) PreInPostInOneTraversal.cpp ├── 40) binarySearchTreeIterator.cpp ├── 41) twoSumInBST.cpp ├── 42) recoverBinarySearchTree.cpp ├── 43) largestBSTinBinaryTree.cpp ├── 44) cousinsInABinaryTree.cpp ├── Segment Trees , Fenwick Trees, Binary Indexed Trees │ └── segmentTree.cpp ├── binarySearchTree.cpp ├── binaryTree.cpp └── tree.cpp ├── 09 (Graph Algorithms) ├── Practice Problems │ ├── Leetcode and GFG │ │ ├── 01) numberOfProvinces.cpp │ │ ├── 02) countingRoomsCSES & noOfIslandsLeetcode.cpp │ │ ├── 03) floodFill.cpp │ │ ├── 04) rottingOranges.cpp │ │ ├── 05) 01Matrix.cpp │ │ ├── 06) surroundedRegions.cpp │ │ ├── 07) numberOfEnclaves.cpp │ │ ├── 08) numberOfDistinctIslands.cpp │ │ ├── 09) findEventualSafeStates.cpp │ │ ├── 10) courseSchedule.cpp │ │ ├── 11) courseScheduleII.cpp │ │ ├── 12) alienDictionary.cpp │ │ ├── 13) wordLadder.cpp │ │ ├── 14) wordLadderII.cpp │ │ ├── 15) shortestDistanceInBinaryMaze.cpp │ │ ├── 16) pathWithMinimumEffort.cpp │ │ ├── 17) cheapestFlightsWitihinKStops.cpp │ │ ├── 18) minimumMultiplicationToReachEnd.cpp │ │ ├── 19) numberOfWaysToArriveAtDestination.cpp │ │ ├── 20) findTheCityWithSmallestNumberOfNeighboursAtThresholdDistance.cpp │ │ ├── 21) numberOfOperationsToMakeNetworkConnected.cpp │ │ ├── 22) accountsMerge.cpp │ │ ├── 23) numberOfislands(ii).cpp │ │ ├── 24) makingALargeIsland.cpp │ │ ├── 25) mostStonesRemovedWithSameRowOrColumn.cpp │ │ ├── 26) islandPerimeter.cpp │ │ ├── 27) pacificAtlanticWaterFlow.cpp │ │ ├── 29) networkDelayTime.cpp │ │ ├── 34) findTheTownJudge.cpp │ │ ├── 35) employeeImportance.cpp │ │ ├── 36) evaluateDivision.cpp │ │ ├── 38) keysAndRooms.cpp │ │ ├── 39) possibleBipartition.cpp │ │ ├── 41) regionsCutBySlashes.cpp │ │ ├── 42) numberOfClosedIslands.cpp │ │ ├── 44) redundantConnection.cpp │ │ ├── 45) timeNeededToInformAllEmployees.cpp │ │ ├── 48) satisfiabilityOfEqualityEquations.cpp │ │ ├── 49) letterCombinationOfAPhoneNumber.cpp │ │ ├── 52) cloneGraph.cpp │ │ ├── 53) allPathsFromSourceToTarget.cpp │ │ ├── 54) houseRobberIII.cpp │ │ ├── 55) snakesAndLadders.cpp │ │ ├── 56) isGraphBipartite.cpp │ │ ├── 57) minimumJumpsToReachHome.cpp │ │ └── 58) shortestBridge.cpp │ └── Others │ │ ├── 01) bishuAndHisGirlfriend.cpp │ │ ├── 02) isItATree.cpp │ │ ├── 03) InOutTimeOfNodes.cpp │ │ ├── 04) fireEscapeRoute.cpp │ │ ├── 05) diameterOfATree.cpp │ │ ├── 06) subtreeSizeUsingDFS.cpp │ │ ├── 07) feasibleRealations.cpp │ │ ├── 08) monkAndTheIslands.cpp │ │ ├── 09) primePath.cpp │ │ ├── 10) socialNetworkingGraph.cpp │ │ ├── 12) topoSortSPOJ.cpp │ │ ├── 13) roundTripCSES.cpp │ │ ├── 15) jungleRun.cpp │ │ ├── 16) minMovesToReachTargetByKnight.cpp │ │ ├── 17) bugLifeProblem.cpp │ │ ├── 18) bertownRoads.cpp │ │ ├── 19) submergingIslands.cpp │ │ ├── 20) chefAndRoundRun.cpp │ │ ├── 21) aWalkToRemember.cpp │ │ ├── 25) edgeDeletionQuesAndConcept.cpp │ │ ├── 26) NakanjSPOJ.cpp │ │ ├── 27) reverseCodechef.cpp │ │ ├── 28) snakesAndTransitionCodechef.cpp │ │ ├── 30) gregAndGraph.cpp │ │ ├── 31) cityAndFloods.cpp │ │ ├── 32) cityAndCampers.cpp │ │ └── 33) shichikujiAndPowerGrid.cpp ├── Theory │ ├── 00) graphTheory.cpp │ ├── 01) DFS.cpp │ ├── 02) BFS.cpp │ ├── 03) countingConnectedComponents.cpp │ ├── 04) countingConnectedComponentsOnGrid.cpp │ ├── 05) cycleDetectionInUndirectedGraphDFS.cpp │ ├── 06) cycleDetectionInUndirectedGraphBFS.cpp │ ├── 07) cycleDetectionInDirectedGraphDFS.cpp │ ├── 08) cycleDetectionInDirectedGraphBFS,KAHN'sAlgo.cpp │ ├── 09) topologicalSortingDFS.cpp │ ├── 10) topologicalSortingBFSorKAHN'sAlgo.cpp │ ├── 11) dfsOn2dGrid.cpp │ ├── 12) bfsOn2dGrid.cpp │ ├── 13) bipartiteGraphBFS.cpp │ ├── 14) bipartiteGraphDFS.cpp │ ├── 15) shortestPathInDAG.cpp │ ├── 16) shortestPathInUndirectedGraphWithUnitWeights.cpp │ ├── 17) singleSourceShortestPathOnTrees.cpp │ ├── 18) shortestPathInUndirectedGraphDijkstraAlgo.cpp │ ├── 19) bellmanFordAlgorithm.cpp │ ├── 20) FloydWarshallAllPairShortestPath.cpp │ ├── 21) minimumSpanningTree.cpp │ ├── 22) primsAlgorithmForMST.cpp │ ├── 23) disjointSetUnionORunionFInd.cpp │ ├── 24) kruskalsAlgorithmMinimumSpanningTree.cpp │ ├── 25) kosaraju'sAlgorithm.cpp │ ├── 26) bridgesInAGraphUsingTarjansAlgo.cpp │ ├── 27) articulationPoint.cpp │ └── 28) tarjansAlgorithmForSCC.cpp └── graphTemplates.cpp ├── 0a (STL & Time Complexity) ├── Hashing │ ├── 0 hashing.cpp │ ├── 0 map.cpp │ ├── 0 set.cpp │ ├── 1 nonRepeatingElement.cpp │ ├── 2 unionOfTwoArrays.cpp │ ├── 3 keyPair.cpp │ ├── 4 subarrayWithZeroSum.cpp │ ├── 5 winnerOfAnElection.cpp │ ├── 6 relativeSortArray.cpp │ ├── 8 sortArrayByIncreasingFrequency.cpp │ ├── 9 customSortString.cpp │ └── countSubarrayHavingOccurenceOfDistinctElementAtleastTwice.cpp ├── STL.cpp ├── STL.exe ├── Time Complexity │ └── TC of recurence relation.cpp ├── deque.cpp ├── queue.cpp ├── stack.cpp └── vector.cpp ├── 0b (Range Queries) ├── 01) rangeAddition.cpp ├── binaryIndexTree.cpp ├── segmentTree.cpp └── staticArrayQueries.cpp ├── 0c (Bit Manipulation) ├── 00) bitManipulation.cpp ├── ANDproduct.cpp ├── XorQueriesOnSubarray.cpp ├── countingBits.cpp ├── isPowerOfTwo.cpp ├── minNoOfFlipsToMakeAorBequalC.cpp ├── noOfOnes.cpp ├── sansaAndXOR.cpp └── singleNumberii.cpp ├── 10 (Greedy) ├── 01) taskSchedular.cpp ├── 02) gasStation.cpp ├── 03) maxNumberOfEventsThatCanBeAttended.cpp ├── Greedy.txt ├── activitySelectionProblem.cpp └── fractionalKnapsack.cpp ├── 11 (Dynamic Programming) ├── 0-1-KnapsackProblem or DP on subsequence (Classical Pattern) │ ├── 0-1-Knapsack.cpp │ ├── 1) subsetSum.cpp │ ├── 2) equalSumPartition.cpp │ ├── 3) countOfSubsetWithGivenSum ie countOfSubsetSum.cpp │ ├── 4) minimumSubsetSumDifference.cpp │ ├── 5) countOfSubsetWithGivenDIfference.cpp │ └── 6) targetSum(leetcode).cpp ├── 1 unbounded knapsack or DP on subsequence(Classical Pattern) │ ├── 1) unboundedKnapsack.cpp │ ├── 2) rodCutting.cpp │ ├── 3) maxRibbonCut.cpp │ ├── 4) coinChange(i).cpp │ ├── 5) coinChange(ii)GFG or coinChangeLeetcode.cpp │ ├── 6) formLargestIntegerWithDigitsThatAddUpToGivenTarget.cpp │ └── 7) minimumCostForTickets.cpp ├── 2 longest Common Subsequence or DP on strings │ ├── 1) longestCommonSubsequence(LCS)(ClassicPattern).cpp │ ├── 10) minimumNoOfDeletionMakeStringPalindrome.cpp │ ├── 11) minimumNoOfInsertionMakeStringPalindrome.cpp │ ├── 12) longestRepeatingSubsequence.cpp │ ├── 13) sequencePatternMatching.cpp │ ├── 14) distinctSubsequences.cpp │ ├── 15) editDistance.cpp │ ├── 16) wildcardMatching.cpp │ ├── 2) longestCommonSubstring.cpp │ ├── 3) printingLongestCommonSubsequence.cpp │ ├── 4) shortestCommonSuperSequence.cpp │ ├── 5) printingShortestCommonSupersequence.cpp │ ├── 6) minimumNumberOfInsertionDeletionRequiredFromStringAtoB.cpp │ ├── 8) longestPalindromicSubsequence.cpp │ └── 9) longestPalindromSubstring.cpp ├── 3 MCM(Matrix Chain Multiplication), Partition DP (Classical Pattern) │ ├── 1) matrixChainMultiplication.cpp │ ├── 2) palindromePartitioning.cpp │ ├── 3) booleanParenthesizationProblem.cpp │ ├── 4) scrambledString.cpp │ ├── 5) eggDroppingProblem.cpp │ ├── 6) minimumCostToCutTheStick.cpp │ ├── 7) burstBaloons.cpp │ ├── 8) palindromePartitioningII.cpp │ ├── 9) partitionArrayForMaximumSum.cpp │ ├── minimumDifficultyOfJobSchedule.cpp │ ├── minimumScoreTriangulationOfPolygon.cpp │ └── superEggDrop.cpp ├── 4 Fibonacci Sequence │ ├── 00) fibonacci.cpp │ ├── 01) climbingStairs.cpp │ ├── 02) frogJumpCodingNinjas.cpp │ ├── 03) frogJumpWithK-Distance.cpp │ ├── 04) frogJumpLeetcode.cpp │ ├── 05) houseRobber.cpp │ ├── 06) houseRobberII.cpp │ └── jumpGame.cpp ├── 5 DP on Grid, 2D Matrix , Shortest Path │ ├── 01) ninja'sTraining.cpp │ ├── 01) uniquePaths.cpp │ ├── 02) uniquePaths-ii.cpp │ ├── 03) minimumPathSum.cpp │ ├── 04) triangles.cpp │ ├── 05) minimumFallingPathSum.cpp │ └── 06) cherryPickupII.cpp ├── 6 DP on trees │ ├── 1) dpOnTrees.cpp │ ├── 2) diameterOfBinaryTree.cpp │ ├── 3) maxPathSumFromAnyNodeToAnyNode.cpp │ ├── 4) maxPathSumFromLeafToLeaf.cpp │ ├── 5) diameterOfN-AryTree.cpp │ └── 6) binaryLifting.cpp ├── 7 Digit DP │ ├── 01) boringNumbers.cpp │ ├── 02) digitSumSPOJ.cpp │ ├── 03) encoding.cpp │ ├── 04) countingNumbers.cpp │ └── digitDpTheory.cpp ├── 8 BitMask DP │ ├── 01) bitmask#1.cpp │ ├── 02) travellingSalesmanProblem.cpp │ ├── 03) findTheShortestSuperstring.cpp │ ├── 04) fish.cpp │ ├── 05) littleElephantAndT-shirts.cpp │ ├── 06) countingTilings.cpp │ └── bitmasking.cpp ├── 9 Longest Increasing Subsequence │ ├── 01) longestIncreasingSubsequence.cpp │ ├── 02) longestDivisibleSubset.cpp │ ├── 03) longestStringChain.cpp │ ├── 04) longestBitonicSubsequence.cpp │ └── 05) numberOfLongestIncreasingSubsequence.cpp ├── Practice Problems │ ├── 02) maximalRectangle.cpp │ ├── 03) countSquareSubmatricesWithAllOnes.cpp │ ├── Best Time To Buy and Sell Stocks , DP on stocks │ │ ├── 01) bestTimeToBuyAndSellStocks.cpp │ │ ├── 02) bestTimeToBuyAndSellStock(ii).cpp │ │ ├── 03) bestTimeToBuyAndSellStock(iii).cpp │ │ ├── 04) bestTimeToBuyAndSellStock(iv).cpp │ │ ├── 05) bestTimeToBuyAndSellStockWithCooldown.cpp │ │ └── 06) bestTimeToBuyAndSellStocksWithTransactionFee.cpp │ ├── assemblyLineScheduling.cpp │ ├── beatifulArray.cpp │ ├── catchSome.cpp │ ├── longestIncreasingSubsequence.cpp │ ├── maximumProfitInJobScheduling.cpp │ ├── niceCodingInterviewProblem.cpp │ ├── perfectSquares.cpp │ ├── removeBoxes.cpp │ ├── strangePrinter.cpp │ ├── twoKeysKeyboard.cpp │ ├── twoPersonTraversalOfSequenceOfCities.cpp │ ├── vasyaAndBinaryStrings.cpp │ └── wordBreak.cpp └── dynamicProgramming.txt ├── 12 (CSES Solutions) └── Dynamic Programming │ ├── 1) diceCombination.cpp │ ├── 10) rectangleCutting.cpp │ ├── 11) twoSets(ii).cpp │ ├── 12) projects.cpp │ ├── 13) countingTowers.cpp │ ├── 14) countingTilings.cpp │ ├── 2) coinCombinationsII.cpp │ ├── 3) gridPaths.cpp │ ├── 4) removingDigits.cpp │ ├── 5) bookShop.cpp │ ├── 6) coinCombinations(i).cpp │ ├── 7) arrayDescription.cpp │ ├── 8) editDistance.cpp │ └── 9) longestIncreasingSubsequence.cpp ├── README.md ├── templates ├── manglani.cpp ├── my.cpp ├── priyansh.cpp └── rachitJain.cpp └── text.cpp /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Win32", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "defines": [ 9 | "_DEBUG", 10 | "UNICODE", 11 | "_UNICODE" 12 | ], 13 | "windowsSdkVersion": "10.0.17763.0", 14 | "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe", 15 | "cStandard": "c17", 16 | "cppStandard": "c++17", 17 | "intelliSenseMode": "msvc-x64" 18 | } 19 | ], 20 | "version": 4 21 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "g++.exe - Build and debug active file", 9 | "type": "cppdbg", 10 | "request": "launch", 11 | "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", 12 | "args": [], 13 | "stopAtEntry": false, 14 | "cwd": "C:\\MinGW\\bin", 15 | "environment": [], 16 | "console": "externalTerminal", 17 | "MIMode": "gdb", 18 | "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", 19 | "setupCommands": [ 20 | { 21 | "description": "Enable pretty-printing for gdb", 22 | "text": "-enable-pretty-printing", 23 | "ignoreFailures": true 24 | } 25 | ], 26 | "preLaunchTask": "C/C++: g++.exe build active file" 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.errorSquiggles": "Disabled", 3 | "files.associations": { 4 | "ostream": "cpp", 5 | "exception": "cpp", 6 | "memory": "cpp", 7 | "utility": "cpp", 8 | "xstring": "cpp", 9 | "chrono": "cpp", 10 | "random": "cpp", 11 | "limits": "cpp", 12 | "valarray": "cpp", 13 | "cmath": "cpp", 14 | "cstddef": "cpp", 15 | "cstdint": "cpp", 16 | "cstdio": "cpp", 17 | "cstdlib": "cpp", 18 | "cstring": "cpp", 19 | "cwchar": "cpp", 20 | "deque": "cpp", 21 | "initializer_list": "cpp", 22 | "ios": "cpp", 23 | "iosfwd": "cpp", 24 | "iostream": "cpp", 25 | "istream": "cpp", 26 | "list": "cpp", 27 | "new": "cpp", 28 | "stack": "cpp", 29 | "stdexcept": "cpp", 30 | "streambuf": "cpp", 31 | "system_error": "cpp", 32 | "tuple": "cpp", 33 | "type_traits": "cpp", 34 | "typeinfo": "cpp", 35 | "unordered_map": "cpp", 36 | "vector": "cpp", 37 | "xfacet": "cpp", 38 | "xhash": "cpp", 39 | "xiosbase": "cpp", 40 | "xlocale": "cpp", 41 | "xlocinfo": "cpp", 42 | "xlocnum": "cpp", 43 | "xmemory": "cpp", 44 | "xmemory0": "cpp", 45 | "xstddef": "cpp", 46 | "xtr1common": "cpp", 47 | "xutility": "cpp" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: g++.exe build active file", 6 | "command": "C:\\MinGW\\bin\\g++.exe", 7 | "args": [ 8 | "-g", 9 | "${file}", 10 | "-o", 11 | "${fileDirname}\\${fileBasenameNoExtension}.exe" 12 | ], 13 | "options": { 14 | "cwd": "C:\\MinGW\\bin" 15 | }, 16 | "problemMatcher": [ 17 | "$gcc" 18 | ], 19 | "group": { 20 | "kind": "build", 21 | "isDefault": true 22 | }, 23 | "detail": "Task generated by Debugger." 24 | } 25 | ], 26 | "version": "2.0.0" 27 | } -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/02) bestTimeToBuyAndSellStock.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | https://youtu.be/XIWykOHE1SE 4 | 5 | // Brute Force O(n^2) gives TLE: 6 | class Solution { 7 | public: 8 | int maxProfit(vector& prices) { 9 | int maxProfit = 0; 10 | int profit = 0; 11 | for(int i=0; i maxProfit){ 15 | maxProfit = profit; 16 | } 17 | } 18 | } 19 | return maxProfit; 20 | } 21 | }; 22 | 23 | // Optimised Approach: Time: O(n), Space: O(1) 24 | int maxProfit(vector& prices) { 25 | int min_price = INT_MAX; // min price till now 26 | int profit = 0; 27 | for(int i=0; i& nums1, int m, vector& nums2, int n){ 10 | int i = m-1; 11 | int j = n-1; 12 | int k = m+n-1; 13 | 14 | while(i>=0 && j>=0){ 15 | if(nums1[i] > nums2[j]){ 16 | nums1[k--] = nums1[i--]; // k position pe jo badi value hogi wo jaegi either from i or j 17 | } 18 | else{ 19 | nums1[k--] = nums2[j--]; 20 | } 21 | 22 | } 23 | while(i>=0){ // the code will also work without this while block as well 24 | nums1[k--] = nums1[i--]; 25 | } 26 | 27 | while(j>=0){ 28 | nums1[k--] = nums2[j--]; 29 | } 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/04) moveZeroes.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/move-zeroes/ 2 | 3 | https://youtu.be/mgzcjQ1x9Mw 4 | 5 | 6 | void moveZeroes(vector& nums) { 7 | int j=0; 8 | for(int i=0; i& prices) { 8 | int profit=0; 9 | for(int i=1; iprices[i-1]){ 11 | profit += (prices[i] - prices[i-1]); 12 | } 13 | } 14 | return profit; 15 | } 16 | }; 17 | 18 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/06) runningSumOf1-dArray.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/running-sum-of-1d-array/ 2 | 3 | class Solution { 4 | public: 5 | vector runningSum(vector& nums) { 6 | for(int i=1; i runningSum(vector& nums) { 19 | for(int i=0; i& nums) { 10 | int sum=0; 11 | int leftsum = 0; 12 | int n = nums.size(); 13 | 14 | int sum = accumulate(begin(nums), end(nums), 0); 15 | 16 | for(int i=0; i& nums) { 31 | int tsum = accumulate(begin(nums), end(nums), 0); 32 | for (int i = 0, lsum = 0; i < nums.size(); lsum += nums[i++]) 33 | if (lsum * 2 == tsum - nums[i]) 34 | return i; 35 | return -1; 36 | } 37 | 38 | // OR (Better) 39 | 40 | class Solution { 41 | public: 42 | int pivotIndex(vector& nums) { 43 | int n = nums.size(); 44 | int leftSum=0; 45 | int rightSum = accumulate(nums.begin(), nums.end(), 0); // this will first become total sum then will be reduced gradually to become right array sum 46 | for(int i=0; i sortedSquares(vector& nums) { 7 | int n = nums.size(); 8 | for(int i=0; i sortedSquares(vector& nums) { 24 | int n = nums.size(); 25 | vector res(n); 26 | 27 | int l=0; 28 | int r=n-1; 29 | 30 | for(int i=0; i abs(nums[r])){ 32 | res[n-i-1] = nums[l] * nums[l++]; 33 | // l++; 34 | else{ 35 | res[n-i-1] = nums[r] * nums[r--]; 36 | // r--; 37 | } 38 | } 39 | return res; 40 | } 41 | }; 42 | 43 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/12) removeDuplicatesFromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | 3 | // Two pointers 4 | // Left will keep track of the next position to be filled 5 | // Right will move through the array (Here below i is the right pointer) 6 | 7 | // the intution behind this -> go through all the elements, along with that check if the 8 | // current element has been included previously or not 9 | // if included skip it, else add it 10 | 11 | class Solution { 12 | public: 13 | int removeDuplicates(vector& nums) { 14 | int n = nums.size(); 15 | if (n < 1) return n; 16 | // pos is left ptr 17 | // i is right ptr 18 | int pos = 1; 19 | for (int i = 1; i < n; ++i) 20 | if (nums[i] != nums[pos - 1]) nums[pos++] = nums[i]; 21 | 22 | return pos; // number of unique elements in array. 23 | } 24 | }; -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/21) rotateImage.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rotate-image 2 | 3 | // TC = O(n^2) 4 | 5 | class Solution { 6 | public: 7 | // Every row is becoming a column. 8 | // Ans: Transpose the matrix & then reverse every row. 9 | void rotate(vector>& matrix) { 10 | int n = matrix.size(); 11 | 12 | // code for transpose of a matrix 13 | for(int i = 0; i go through all the elements, along with that check if the 5 | // current element has been included previously or not 6 | // if included skip it, else add it 7 | 8 | To keep only one instance 9 | 10 | class Solution { 11 | public: 12 | int removeDuplicates(vector& nums) { 13 | int n = nums.size(); 14 | if (n <= 1) return n; 15 | 16 | int left = 1; 17 | for (int r = 1; r < n; ++r) 18 | if (nums[r] != nums[left - 1]) nums[left++] = nums[r]; 19 | 20 | return left; // this will contain the no of unique elements in the array 21 | } 22 | }; 23 | 24 | https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 25 | 26 | Allowed to keep atmost two instances 27 | 28 | class Solution { 29 | public: 30 | int removeDuplicates(vector& nums) { 31 | int n = nums.size(); 32 | if (n <= 2) return n; 33 | 34 | int left = 2; 35 | for (int r = 2; r < n; ++r) 36 | if (nums[r] != nums[left - 2]) nums[left++] = nums[r]; 37 | 38 | return left; // this will contain the no of unique elements in the array 39 | } 40 | }; 41 | 42 | 43 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/23) threeSumClosest.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/3sum-closest/ 2 | 3 | 4 | class Solution { 5 | public: 6 | int threeSumClosest(vector& nums, int target) { 7 | int res=nums[0] + nums[1] + nums[2]; 8 | sort(nums.begin(), nums.end()); 9 | int n = nums.size(); 10 | 11 | for(int i=0; i target) e--; 22 | else s++; 23 | } 24 | } 25 | return res; 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/27) combinationSum.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/combination-sum/ 2 | 3 | // Based on recursion and backtracking 4 | 5 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/31) findAllDuplicatesInAnArray.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-all-duplicates-in-an-array/ 2 | 3 | // without the given constraints the problem can be solved by sorting or some hashmap 4 | 5 | // Thing to catch: 6 | // all the integers of nums are in the range [1, n] & we know indices are in range of [0, n-1] 7 | // Trick is how to use this thing? 8 | 9 | // "If there is a repeating number, both of them will point to the same index as we move in the array." 10 | // For ex: 11 | // [4,3,2,7,8,2,3,1] 12 | // As we move in the array the first 3 will point at position 3(index 2)(so we subtract 1), then second 3 will again point at position 3(index 2) 13 | // We will make some changes first time we encounter a position so as to distinguish if it is encountered again in the future (here making it negative) 14 | 15 | // " modifying the array elements is allowed " 16 | 17 | class Solution { 18 | public: 19 | vector findDuplicates(vector& nums) { 20 | vector res; 21 | int n = nums.size(); 22 | 23 | for(int i=0; i0){ 25 | nums[abs(nums[i]) - 1]*=(-1); 26 | } 27 | else{ 28 | res.push_back(abs(nums[i])); 29 | } 30 | } 31 | return res; 32 | } 33 | }; 34 | 35 | 36 | https://leetcode.ca/search/ 37 | 38 | And search the word duplicate for all such questions 39 | 40 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/33) jumpGame.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/jump-game/ 2 | 3 | // Greedy O(n) 4 | class Solution { 5 | public: 6 | bool canJump(vector& nums) { 7 | int n = nums.size(); 8 | int farthest = 0; 9 | 10 | for(int i=0; i=n-1; 15 | } 16 | }; 17 | 18 | 19 | // OR 20 | // we move from last element and shift it to left accordingly and check if we can reach at the start position 21 | class Solution { 22 | public: 23 | bool canJump(vector& nums) { 24 | int n = nums.size(); 25 | int goal = n-1; 26 | for(int i=n-2; i>=0; i--){ 27 | if(i+nums[i]>=goal){ // from a left element we can reach an element right to it ie the goal 28 | goal = i; 29 | } 30 | } 31 | // if(goal==0) return true; 32 | // return false; 33 | return goal==0; 34 | } 35 | }; 36 | 37 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/39) toeplitzMatrix.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/toeplitz-matrix/ 2 | 3 | Google 4 | 5 | There are multiple diagonals and all of them must have same elements among them. 6 | 7 | We can ignore 0th row and 0th column as no top left neighbour element to compare. 8 | 9 | https://youtu.be/q-WIid5qu-I 10 | 11 | class Solution { 12 | public: 13 | bool isToeplitzMatrix(vector>& matrix) { 14 | int m = matrix.size(); 15 | int n = matrix[0].size(); 16 | 17 | for(int i=1; i> diagonalSort(vector>& mat) { 24 | int m = mat.size(); 25 | int n = mat[0].size(); 26 | 27 | unordered_map> mp; 28 | 29 | // store diagonal elements 30 | for(int i=0; i=0; --i){ 46 | for(int j=n-1; j>=0; --j){ 47 | mat[i][j] = mp[i-j].back(); 48 | mp[i-j].pop_back(); 49 | } 50 | } 51 | return mat; 52 | } 53 | }; 54 | 55 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/42) diagonalTraversal.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/diagonal-traverse/ 2 | 3 | Traversal is / / / / / like this in bi-direction 4 | 5 | Along every diagonal value of i+j is constant (acts like an id) isi ka fayda uthana hai 6 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/44) maxValueOfEquation.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/max-value-of-equation/ 2 | 3 | yi + yj + |xi - xj| 4 | 5 | We know xj>xi 6 | Hence we can write above eqn as = 7 | yi + yj + xj - xi 8 | ans: (xj + yj) + (yi-xi) 9 | 10 | From previous indices only (yi-xi) part is changing(variable jiski max value apan use karenge hamesha) 11 | Har index k liye past max value se karenge. 12 | 13 | So we will take a priority queue. 14 | pair why? 15 | (yi-xi) jiske according sorted order m store hoga 16 | xi so that we can verify our condition. 17 | 18 | 19 | class Solution { 20 | public: 21 | int findMaxValueOfEquation(vector>& points, int k) { 22 | priority_queue> pq; // max heap 23 | int n = points.size(); 24 | int ans = INT_MIN; 25 | for(int i=0; ik)) pq.pop(); // remove the invalid elements 27 | if(!pq.empty()){ // queue still has some elements, calculate ans using the top element only 28 | ans = max(ans, points[i][0] + points[i][1] + pq.top().first); 29 | } 30 | pq.push({points[i][1]-points[i][0], points[i][0]}); 31 | } 32 | return ans; 33 | } 34 | }; 35 | 36 | TC = nlogn 37 | Sc = n 38 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/45) countSubarraysWithXorAsK.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/count-number-subarrays-given-xor/ 2 | 3 | https://youtu.be/lO9R5CaGRPY (Striver) 4 | 5 | 6 | <-------XR---------> 7 | 1 2 3 4 5 6 7 8 9 10 11 12 8 | <---Y--><----K-----> 9 | 10 | // XR, Y, K are the XOR's of that subarray 11 | 12 | // Y^K = XR 13 | // Y = XR^K // taking xor with k with side. 14 | // We know XR(prefix xor) and k(given) I can check for count of such Y's easily now. 15 | 16 | Hashmap 17 | 18 | int solve(vector &A, int k){ 19 | unordered_map mp; 20 | int cnt = 0; 21 | int xorr = 0; 22 | for(auto it: A){ 23 | xorr = xorr^it; // prefix xor 24 | if(xorr==k){ 25 | cnt++; 26 | } 27 | if(mp.find(xorr^k)!=mp.end()) 28 | cnt+=mp[xorr^k]; 29 | mp[xorr]++; 30 | } 31 | return cnt; 32 | } 33 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/Prefix Sum/03) rangeSumQuery2D-Inmutable.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/range-sum-query-2d-immutable/ 2 | 3 | // jada if else na likhna pade isliye m+1, n+1 size ki prefsum matrix li hai 4 | // this is a better practice for 2D prefix or just prefix sum type ques 5 | 6 | https://youtu.be/tk0Twx2VQy8 (Watch kar lena ek baar) 7 | 8 | Picture representation : jo area do baar use hua usko ek baar add kar dia. 9 | https://assets.leetcode.com/users/hiepit/image_1578762431.png 10 | 11 | class NumMatrix { 12 | public: 13 | vector> sum; // global declare kia hai toh all elements are 0 14 | NumMatrix(vector>& matrix) { 15 | int m = matrix.size(), n = matrix[0].size(); 16 | sum = vector>(m + 1, vector(n + 1)); // sum[i][j] is sum of all elements inside the rectangle [0,0,i,j] 17 | for (int i = 1; i <= m; i++) { 18 | for (int j = 1; j <= n; j++) { 19 | sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + matrix[i - 1][j - 1]; 20 | } 21 | } 22 | } 23 | int sumRegion(int r1, int c1, int r2, int c2) { 24 | r1++; c1++; r2++; c2++; // Since our `sum` starts by 1 so we need to increase r1, c1, r2, c2 by 1 // saari queries ko ek se badha dia 25 | return sum[r2][c2] - sum[r2][c1 - 1] - sum[r1 - 1][c2] + sum[r1 - 1][c1 - 1]; 26 | } 27 | }; 28 | /** 29 | * Your NumMatrix object will be instantiated and called as such: 30 | * NumMatrix* obj = new NumMatrix(matrix); 31 | * int param_1 = obj->sumRegion(row1,col1,row2,col2); 32 | */ 33 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/Prefix Sum/04) rangeSumQueryMutable.cpp: -------------------------------------------------------------------------------- 1 | Since there can be update queries, I cannot efficiently apply prefix sum. 2 | 3 | So, this is the topic of segment trees. 4 | 5 | 6 | https://leetcode.com/problems/range-sum-query-mutable/solutions/1281195/clean-solution-w-explanation-segment-tree-beats-100/ 7 | 8 | https://leetcode.com/problems/range-sum-query-mutable/solutions/1406686/c-java-python-2-solutions-binary-indexed-tree-segment-tree/ 9 | 10 | 11 | https://leetcode.com/problems/range-sum-query-mutable/solutions/2358579/easy-and-naive-solution-using-vector-or-array-no-segment-tree-no-tree/ 12 | Yeh koi bematlab ka but working solution hai 13 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/Prefix Sum/prefixSum.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/tag/prefix-sum/discuss/2719912/Prefix-sum-study-summary 2 | 3 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/Vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | vector v; 7 | 8 | //Push elements 9 | for(int i=1; i<=5; i++) 10 | { 11 | v.push_back(i); 12 | } 13 | cout<<"Size: "< PosNegPair(int a[], int n) { 4 | vector v, ans; // v vector will store all negative values, ans will store answer 5 | mapmp; // mp will store all positive values in ascending order. 6 | 7 | for(int i=0; i=0; i--){ // righmost value will be greatest negative but smallest positive, so we traverse from last 18 | if(mp[abs(v[i])]>0){ // we check if the absolute of that -ve value is in map. 19 | ans.push_back(v[i]); // pushing the -ve value first 20 | ans.push_back(abs(v[i])); // pushing its positive value 21 | mp[abs(v[i])]-=1; // decreasing the count of occurence from the map by 1. 22 | } 23 | } 24 | return ans; // to return a vector of int. 25 | } 26 | 27 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/twoPointerMethod.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shashwat0105/CPP-Data-Structures-and-Algorithms/9d6621248c4c15fa32267527761f1b5a59cfbfb4/01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Arrays/twoPointerMethod.cpp -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Mathematics(Number Theory)/01) digitConcept.cpp: -------------------------------------------------------------------------------- 1 | Reverse a number/Count the number of digits etc 2 | 3 | Input: 1123 4 | Output: 3211 5 | 6 | Input: 1300 7 | Output: 31 8 | 9 | int solve(int n){ 10 | int ans = 0; 11 | 12 | while(n>0){ 13 | int digit = n%10; // digit extraction 14 | ans = 10*ans+digit; 15 | n = n/10; 16 | } 17 | return ans; 18 | } 19 | 20 | The time complexity of the solution is O(digitsCount). 21 | 22 | Better Solution to just return count of digits: 23 | Number of digits in N = log10(N) + 1. 24 | Proof :- 10K-1 <= N < 10K 25 | Therefore, the time complexity of this solution is O(1). 26 | 27 | // Check palindrome 28 | // Simply compare with the reverse number 29 | 30 | // Armstrong Number 31 | https://practice.geeksforgeeks.org/problems/armstrong-numbers2727/1 32 | 33 | // This is also armstrong number you just have to play with the digits. 34 | Approach: The idea is to first count number digits (or find order). 35 | Let the number of digits be n. 36 | For every digit r in input number x, compute rn. 37 | If sum of all such values is equal to n, then return true, else false. 38 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Mathematics(Number Theory)/0Maths.txt: -------------------------------------------------------------------------------- 1 | Topics: 2 | 1) Primality Test 3 | 2) Prime factorization 4 | 3) Sieve of Eratosthenes (In a range to find whether a given no is prime or not, it generates all) 5 | 4) Binary Exponentiation (Allow us to calculate a^n in log n time) 6 | 5) Euclid Algorithm for GCD 7 | 6) Goldbach's conjecture 8 | 7) Finding number of divisors of N 9 | 8) Calculating Binomial Coefficient 10 | 9) Segmented Sieve 11 | 10) Modulo Inverse (very imp) 12 | 11) Extended Euclidean (To calculate modulo inverse(if it exists) & to solve a Linear Diophantine equation (LDE)) 13 | 12) Matrix exponentiation (Matrix^n) 14 | 13) Fibonacci numbers in O(logn) (we use matrix exponentiation for this) 15 | 14) Chinese Remainder Theorem 16 | 15) Euler Totient Function (ETF of a number n = no of integers from 1 to n whose GCD with n is 1 ie co-prime with n) example: ETF of 6 is 2 (1 and 5) 17 | 16) Sum of divisors 18 | 17) Pollard p-1 method (Integer factorization(20 digits)) 19 | 18) Pollard Rho Algorithm 20 | 21 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Mathematics(Number Theory)/binaryExponentiation.cpp: -------------------------------------------------------------------------------- 1 | // To calculate a^n in O(logn) time 2 | 3 | // Naive approach 4 | 5 | int power(int base, int n){ 6 | int res=1; 7 | for(int i-1; i<=n; i++){ 8 | res=res*base; 9 | } 10 | return res; 11 | } 12 | 13 | // Binary Exponentiation 14 | // If power is odd, res = base*res and reduce power by 1 15 | // If power is even, base*=2, and power/=2 16 | 17 | // Example 2^13 18 | res base power 19 | 1 2 13 20 | 2 2 12 21 | 2 4 6 22 | 2 16 3 23 | 32 256 2 24 | 32 256 1 25 | 8192 256 0 26 | // (final result when power becomes 0) 27 | // TC = O(log n) 28 | 29 | int power(int a, int n){ 30 | int res=1; 31 | 32 | while(n){ 33 | if(n%2){ // power is odd 34 | res*=a; 35 | n--; 36 | } 37 | else // power is even 38 | a*=a; 39 | n/=2; 40 | } 41 | return res; 42 | } 43 | 44 | // Modular Exponentiation 45 | // To calculate a^n mod p 46 | // p is some prime number 47 | 48 | int power(int a, int n, int p){ 49 | int res=1; 50 | 51 | while(n){ 52 | if(n%2){ 53 | res=(res*a)%p; 54 | n--; 55 | } 56 | else 57 | a=(a*a)%p; 58 | n/=2; 59 | } 60 | return res; 61 | } 62 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Mathematics(Number Theory)/d_PrintAllSubStrings.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all possible substrings of a given string 2 | #include 3 | using namespace std; 4 | 5 | // Function to print all sub strings 6 | void subString(char str[], int n) 7 | { 8 | // Pick starting point 9 | for (int len = 1; len <= n; len++) 10 | { 11 | // Pick ending point 12 | for (int i = 0; i <= n - len; i++) 13 | { 14 | // Print characters from current 15 | // starting point to current ending 16 | // point. 17 | int j = i + len - 1; 18 | for (int k = i; k <= j; k++) 19 | cout << str[k]; 20 | 21 | cout << endl; 22 | } 23 | } 24 | } 25 | 26 | // Driver program to test above function 27 | int main() 28 | { 29 | char str[] = "abc"; // ac is not a substring 30 | subString(str, strlen(str)); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Mathematics(Number Theory)/primeFactorisation.cpp: -------------------------------------------------------------------------------- 1 | // Prime Factorization 2 | // 100 = (2^2)*(5^2) 3 | 4 | // Brute force approach 5 | // Worst case TC = O(n) when n is a prime number 6 | 7 | void primeFactorisation(int n){ 8 | for(int i=2; i 50 -> 25, exit from for loop, check for numbers dividing 25, we get 5: 25->5->1 14 | } 15 | cout<1){ // case when n is smaller than i*i, ie n*1 is left 36 | cout< m; // map is much better than set, can store unique as well as count both are required here 12 | int maxi=-1; // for the case when there is no substring with k distinct characters 13 | while(j 14 | m[s[j]]++; 15 | if(m.size()k){ 24 | // using a while loop to continuosly reduce the element so that it gets valid 25 | while(m.size()>k){ // till this condition doesn't becomes false 26 | m[s[i]]--; 27 | if(m[s[i]]==0){ // even if the element count becomes zero it still remains inside the map we need to remove it 28 | m.erase(s[i]); 29 | } 30 | i++; 31 | } 32 | j++; 33 | } 34 | } 35 | return maxi; 36 | } 37 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Sliding Window/08) pickToys or fruitsIntoBasket.cpp: -------------------------------------------------------------------------------- 1 | Pick Toys same isme toys pick krne hai. 2 | 3 | Length of longest subarray with exactly 2 unique characters . 4 | 5 | 6 | https://leetcode.com/problems/fruit-into-baskets/ 7 | 8 | // If all the trees had just one type of fruit then ans would be count of that fruit. 9 | // Else if >1 types of fruit are there we can at max and we will take exactly two unique fruits. 10 | 11 | class Solution { 12 | public: 13 | int totalFruit(vector& fruits) { 14 | int n = fruits.size(); 15 | // edge case 16 | if(n==1) return 1; 17 | unordered_map m; 18 | int i=0, j= 0; 19 | int len=0; 20 | while(j2){ 30 | while(m.size()>2){ // jab tak yeh condition invalid nahi ho jaati 31 | m[fruits[i]]--; 32 | if(m[fruits[i]]==0) m.erase(fruits[i]); 33 | i++; 34 | } 35 | j++; 36 | } 37 | } 38 | // edge case of unique is 1 39 | if(m.size()==1){ 40 | auto it = m.begin(); 41 | return it->second; 42 | } 43 | return len; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Sliding Window/09) minimumWindowSubstring.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-window-substring/ 2 | 3 | // Hardest problem of Sliding window 4 | 5 | count= mp.size() jab bhi koi character decrement hoke zero hoga, count ko ek less kar denge. 6 | jaha count 0 ho jaega wo esi sliding window hai jo possible answer hai. 7 | count of a charcter will go in negative as well. T T T T T A , T T A , start k extra T hata denge seeing the negative count. 8 | count = 1 hua means it is no longer our ans tab j increment karenge ans milega use optimise krne k liye i increment karenge 9 | 10 | 11 | // Aditya verma solution 12 | 13 | 14 | 15 | // Other solution 16 | class Solution { 17 | public: 18 | string minWindow(string s, string t) { 19 | if(t.size()>s.size()) 20 | return ""; 21 | unordered_map mp; 22 | for(auto a:t) 23 | mp[a]++; 24 | int i=0,j=0, cnt=t.size(); 25 | int st=0; 26 | int ans=INT_MAX; 27 | while(j=0) 31 | cnt--; 32 | j++; 33 | while(cnt==0) 34 | { 35 | mp[s[i]]++; 36 | if(ans>(j-i)) 37 | { 38 | ans=j-i; 39 | st=i; 40 | } 41 | if(mp[s[i]]>0) 42 | cnt++; 43 | i++; 44 | } 45 | } 46 | return ans==INT_MAX?"":s.substr(st,ans); 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /01 (Mathematics(Number Theory) & Arrays) & Sliding Window/Sliding Window/10) maximumSubarray.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-subarray/ 2 | 3 | 4 | https://leetcode.com/problems/maximum-subarray/solutions/1470547/C++-Easy-and-Clean-Solution-or-Fastest:-0ms-or-All-Methods-or-Follow-Ups-or-Detailed-Explanation/?orderBy=most_votes 5 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Searching/Binary Search/11) searchA2DMatrix(ii).cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/search-a-2d-matrix-ii/ 2 | 3 | // Method 1 brute force is linear search O(n*m) 4 | 5 | // Method 2: Moving left and down 6 | class Solution { 7 | public: 8 | bool searchMatrix(vector>& matrix, int target) { 9 | // integers in "each" column are sorted 10 | // pointer starts from top right corner 11 | // moves leftwards if targetnum[cur] 12 | // if crosses the boundary(out of bound) then that element is not found 13 | int n = matrix.size(); 14 | int m = matrix[0].size(); 15 | int i = 0, j = m-1; 16 | while(i=0){ 17 | if(matrix[i][j]==target) return true; // if index asked return i, j 18 | if(matrix[i][j]>target) j--; 19 | else i++; 20 | } 21 | return false; 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Searching/Binary Search/12) searchInANearlySortedArray.cpp: -------------------------------------------------------------------------------- 1 | Certain elements are shifted to either of the adjacent indexes after the array was sorted, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. 2 | Basically, the element arr[i] can only be swapped with either arr[i+1] or arr[i-1]. 3 | 4 | private static int binarySearchNearlySorted(int[] a, int target) { 5 | int n = a.length; 6 | int start = 0; 7 | int end = n-1; 8 | 9 | while(start <= end) { 10 | int mid = (start + end)/2; 11 | 12 | if(target == a[mid]) { 13 | return mid; 14 | } 15 | 16 | if(mid > 0 && target == a[mid-1]) { 17 | return mid-1; 18 | } 19 | 20 | if(mid < n-1 && target == a[mid+1]) { 21 | return mid+1; 22 | } 23 | 24 | if (target < a[mid]) { 25 | end = mid-2; 26 | } else { 27 | start = mid+2; 28 | } 29 | } 30 | 31 | return -1; 32 | } 33 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Searching/Binary Search/13) floorInASortedArray.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/floor-in-a-sorted-array-1587115620/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article 2 | 3 | Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. 4 | To return index of k 5 | 6 | 7 | int findFloor(vector v, long long n, long long x){ 8 | return upper_bound(v.begin(), v.end(), x)-v.begin() -1; 9 | } 10 | 11 | // 12 | if(arr[mid]==ele) then our search is over 13 | if(arr[mid]ele) mid is not a possible candidate reject and we mvoe to mid-1 in search of smaller elements. 15 | 16 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Searching/Binary Search/14) ceilInASortedArray.cpp: -------------------------------------------------------------------------------- 1 | 2 | Ceil of A: smallest element greater than A. 3 | 4 | say ceil of 5: 5 | 8, 9, 11 , 13 can be candidate in finding ceil of 5 6 | we have to chose the best ie smallest. 7 | 8 | 9 | if(arr[mid]==ele) wahi khatam ho gaya 10 | if(arr[mid]>ele) it is a candidate we store it in res. and move towards left ie mid-1 11 | if(arr[mid]arr[high]){ 19 | low = high; 20 | high = 2*high; 21 | } 22 | // as usual binary search. 23 | binary search(arr, low, high){}; 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Searching/Binary Search/16) indexOfFirstOneInBinarySortedInfiniteArray.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/find-index-first-1-infinite-sorted-array-0s-1s/ 2 | 3 | 4 | // 0000000000000111111...... infinite 5 | 6 | // 1) first occurence of an element 7 | // 2) infinite sorted 8 | 9 | // key = 1 10 | 11 | // double kar kar k key ly karne lage beech mein, low ar high aa jae 12 | // tab binary search lagani hai first occurence wali. 13 | 14 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Searching/Binary Search/17) minimumDifferenceElementInSortedArray.cpp: -------------------------------------------------------------------------------- 1 | Array given: 1 3 4 5 8 10 15 2 | 3 | key = 12 4 | 5 | u need to return 10. 6 | 7 | while(low<=high){ 8 | if(ele==arr[mid]) return arr[mid]; 9 | else if(ele 4 | using namespace std; 5 | 6 | int linearSearch(int arr[], int n, int k) 7 | { 8 | for(int i=0; i>n; 18 | int arr[n]; 19 | for(int i=0; i>arr[i]; 22 | } 23 | int k; 24 | cin>>k; 25 | 26 | int result = linearSearch(arr, n, k); 27 | cout< 0 && arr[mid-1] > arr[mid]) : 19 | return findPeak(arr, low, (mid -1), n) 20 | 21 | // If middle element is not peak and its right neighbour is greater 22 | // than it, then right half must have a peak element 23 | else : 24 | return findPeak(arr, (mid + 1), high, n) 25 | } 26 | 27 | 28 | // In 2D array finding peak element 29 | // By brute force time complexity is O(n*m) 30 | // By optimisation it is O(mlogn) 31 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Sorting/CustomSort/00) customSort.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shashwat0105/CPP-Data-Structures-and-Algorithms/9d6621248c4c15fa32267527761f1b5a59cfbfb4/02 (Searching & Sorting)/Sorting/CustomSort/00) customSort.cpp -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Sorting/CustomSort/01) ArrangeGivenNumbersToFormLargestNumber.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/ 2 | 3 | Input: 4 | N = 5 5 | Arr[] = {3, 30, 34, 5, 9} 6 | Output: 9534330 7 | 8 | static bool mycmp(string a, string b){ 9 | return a+b>b+a; 10 | } 11 | string printLargest(vector &arr) { 12 | // code here 13 | string ans; 14 | int n = arr.size(); 15 | sort(arr.begin(), arr.end(), mycmp); 16 | 17 | for(int i=0; i sortArray(vector& nums) { 10 | int n = nums.size(); 11 | int min_idx; 12 | for(int i=0; i0 && arr[j-1] > arr[j]){ // other loop decremented from right to left 21 | swap(arr[j-1], arr[j]); 22 | j--; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Sorting/inPLaceSorting/heapSort.cpp: -------------------------------------------------------------------------------- 1 | // Time complexity O(nlogn) 2 | // In place but unstable 3 | // Min heap banate jao ar root(min element) ko delete krke kahi store kar lo 4 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Sorting/radixSort.cpp: -------------------------------------------------------------------------------- 1 | // Also called bucket sort & digital sort 2 | // Non comparative sorting algo 3 | // Uses counting sort on individual digits not on entire number 4 | // Time complexity O d(n+k) , d = no. of digits, n = no. of elements in the array, k = range 5 | // Space complexity O(n+k) // Output array same as size of input array & k is the size of count array 6 | 7 | 8 | -------------------------------------------------------------------------------- /02 (Searching & Sorting)/Sorting/sortFunctionInC++STL.cpp: -------------------------------------------------------------------------------- 1 | // By Default sorts in ascending order 2 | // Sort an array: sort(arr, arr+n) 3 | // Sort a vector: sort(vec.begin(), vec.end()) 4 | // sort(arr, arr+n, greater()) // Puts greater element before hence sorting in descending order. 5 | // We can also write our own comparator function and pass it as a third parameter. To sort in particular order 6 | #include 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | // Sorting Array 12 | int arr1 = {3,2,5,6,8,6}; 13 | int n1 = sizeof(arr1)/sizeof(arr1[0]); 14 | 15 | sort(arr1, arr1 + n1); 16 | 17 | // Sorting array in reverse order 18 | int arr2 = {2, 4, 5, 1, 3}; 19 | int n2 = sizeof(arr2)/sizeof(arr2[0]); 20 | 21 | sort(arr2, arr2+n2, greater()); 22 | 23 | // Sorting Vector 24 | vectorvec = { 3, 4, 2, 5, 8, 6}; 25 | 26 | sort(vec.begin(), vec.end()); 27 | 28 | // Printing them 29 | for(int i = 0; i O(logn) 5 | Insertion in Heap -> O(logn) 6 | Construct Heap ->O(nlogn) 7 | Delete from Heap ->O(logn) 8 | Huffman ->O(nlogn) 9 | ### V = Vertices, E = Edges 10 | Prims algorithm ->For matrix O(n^2), For Heap O((V+E)logV) 11 | Kruskal algorithm ->O(ElogE) 12 | DFS -> O(V + E) 13 | BFS -> O(V + E) 14 | All pair shortest (Floyd Warshall) -> O(n^3) 15 | Dijkstra -> O(V^2) 16 | 17 | 18 | EXTRA: 19 | Time complexity of the following loop: 20 | for (int i = 0; i <=n-1; i=i+j){ // this i=i+j is effectively i=i+k 21 | for(int j=i+1; j<=k; j++){ 22 | // constant work 23 | } 24 | } 25 | 26 | Inner loop runs k times 27 | Outer loops runs n/k times 28 | Total time (n/k)*k = O(n) Ans 29 | -------------------------------------------------------------------------------- /03 (String & Its algorithms)/String & String Algorithms/Basic Algos/rabinKarpStringMatchingAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | // Given string text of length N 2 | // Given string pattern of length M 3 | // To find all occurrences of pattern in text in TC = O(N+M) 4 | 5 | // Prerequisites: 6 | // string hashing 7 | // sliding window 8 | 9 | // Modification in the string hashing method formula during comparison. 10 | pattern * P^L == DP[R] - DP[L-1] 11 | 12 | 13 | -------------------------------------------------------------------------------- /03 (String & Its algorithms)/String & String Algorithms/Basic Algos/slidingWindowAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | // To match a given pattern from a given text(a line or a word) 2 | 3 | // TC = O(N*M) // N, M are lengths of the string 4 | 5 | #include 6 | #define lli long long int 7 | #define vi vector 8 | #define ii pair 9 | #define vii vector 10 | #define ff first 11 | #define ss second 12 | #define endl '\n' 13 | #define mod (int)1e9+7 14 | using namespace std; 15 | 16 | string T , P; // T = Large text, P = Pattern to match 17 | int LP , LT; // LP = length of pattern, LT = length of text 18 | 19 | bool match(int L , int R){ 20 | for(int i=0;i>t; 29 | 30 | cin.ignore(); 31 | 32 | while(t--) 33 | { 34 | getline(cin , T); 35 | getline(cin , P); 36 | LP = P.size(); 37 | LT = T.size(); 38 | 39 | for(int L=0 , R=LP-1; R z_function(string s) { 21 | int n = (int) s.length(); 22 | vector z(n); 23 | for (int i = 1, l = 0, r = 0; i < n; ++i) { 24 | if (i <= r) 25 | z[i] = min (r - i + 1, z[i - l]); 26 | while (i + z[i] < n && s[z[i]] == s[i + z[i]]) 27 | ++z[i]; 28 | if (i + z[i] - 1 > r) 29 | l = i, r = i + z[i] - 1; 30 | } 31 | return z; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /03 (String & Its algorithms)/String & String Algorithms/Intermediate Algos/knuthMorrisPratt(KMP)stringMatchingAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | TC = O(m+n) 2 | 3 | Terminologies used in this algo 4 | String: abskdskdjssdjskjajckasxsabcdabc 5 | Pattern: abcdabc 6 | 7 | Prefix: a, ab, abc, abcd ... (Subset of pattern but should start from the beginning) 8 | 9 | Idea of KMP: Is there any prefix repeated in other parts of the strings? 10 | 11 | Examples: P1, P2... are example of patterns 12 | P1: a b c d a b e a b f 13 | pi 0 0 0 0 1 2 0 1 2 0 14 | 15 | P2: a b c d e a b f a b c 16 | pi 0 0 0 0 0 1 2 0 1 2 3 17 | 18 | P3: a a a a b a a c d 19 | pi 0 1 2 3 0 1 2 0 0 20 | 21 | 22 | // Algorithm to create prefix array or value array or KMP 23 | // Jo string pass kar rahe ho uska prefix value array ban jaega (CRUX: Iska use krna aana chahiye bas) 24 | vector prefix_function(string s) { 25 | int n = s.size(); 26 | vector pi(n); 27 | for (int i = 1; i < n; i++) { 28 | int j = pi[i-1]; 29 | while (j > 0 && s[i] != s[j]) 30 | j = pi[j-1]; 31 | if (s[i] == s[j]) 32 | j++; 33 | pi[i] = j; 34 | } 35 | return pi; 36 | } 37 | 38 | 39 | // Watch this video in sometime in future Jab sab ho jae 40 | // https://youtu.be/__Cu92rei1s (Detailed explanation by Pepcoding) -------------------------------------------------------------------------------- /03 (String & Its algorithms)/String & String Algorithms/Practice Problems/01) goalParserInterpretation.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/goal-parser-interpretation/ 2 | 3 | class Solution { 4 | public: 5 | string interpret(string command) { 6 | string res; 7 | 8 | int n=command.size(); 9 | 10 | for(int i=0; i1){ 12 | return false; 13 | } 14 | } 15 | else if(s[i]=='L' && s[i+1]=='L' && s[i+2]=='L'){ 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | }; 22 | 23 | // 1 line python 24 | return s.count('A') <= 1 and s.count('LLL') == 0 25 | -------------------------------------------------------------------------------- /03 (String & Its algorithms)/String & String Algorithms/Practice Problems/03) longestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-common-prefix/ 2 | 3 | // Yet to brainstorm on this more 4 | 5 | class Solution { 6 | public: 7 | string longestCommonPrefix(vector& strs) { 8 | string prefix = ""; 9 | if(strs.size()==0) return prefix; 10 | 11 | for(int i=0; i=0; i--){ 10 | if(s[i] == 'V') res+= 5; 11 | if(s[i] == 'L') res+= 50; 12 | if(s[i] == 'D') res+= 500; 13 | if(s[i] == 'M') res+= 1000; 14 | 15 | if(s[i] == 'I'){ 16 | if(s[i+1]=='V' || s[i+1]=='X') res-=1; 17 | else res+=1; 18 | } 19 | if(s[i] == 'X'){ 20 | if(s[i+1]=='L' || s[i+1]=='C') res-=10; 21 | else res+=10; 22 | } 23 | if(s[i] == 'C'){ 24 | if(s[i+1]=='D' || s[i+1]=='M') res-=100; 25 | else res+=100; 26 | } 27 | } 28 | return res; 29 | } 30 | }; 31 | 32 | // Alternate solution using map 33 | class Solution { 34 | public: 35 | int romanToInt(string s) { 36 | int res=0; 37 | int n = s.size(); 38 | 39 | map m; 40 | m['I'] = 1; 41 | m['V'] = 5; 42 | m['X'] = 10; 43 | m['L'] = 50; 44 | m['C'] = 100; 45 | m['D'] = 500; 46 | m['M'] = 1000; 47 | 48 | for(int i=0; i 11 | using namespace std; 12 | 13 | int main() { 14 | string pat, text; 15 | cin>>pat>>text; 16 | string s = pat + '#' + text; 17 | 18 | int n = (int)s.length(); 19 | vector pi(n); 20 | for (int i = 1; i < n; i++) { 21 | int j = pi[i-1]; 22 | while (j > 0 && s[i] != s[j]) 23 | j = pi[j-1]; 24 | if (s[i] == s[j]) 25 | j++; 26 | pi[i] = j; 27 | } 28 | 29 | int res = 0; 30 | for(int i = pat.size(); i pi(n); 11 | for (int i = 1; i < n; i++) { 12 | int j = pi[i-1]; 13 | while (j > 0 && s[i] != s[j]) 14 | j = pi[j-1]; 15 | if (s[i] == s[j]) 16 | j++; 17 | pi[i] = j; 18 | } 19 | } 20 | 21 | cout<<(k*n - (k-1)*pi[n-1])<=n) break; 15 | 16 | int j = i+1; 17 | 18 | while(jnext==NULL) return false; // ie there is no or 1 element in the list. 21 | 22 | while(fast!=NULL && fast->next!=NULL){ 23 | slow = slow->next; 24 | fast = fast->next->next; // we have to do this, thats why the conditions in while loop 25 | if(fast==slow) return true; // fast catches slow ie there was a cycle. 26 | } 27 | return false; 28 | } 29 | }; 30 | 31 | // Proof of concept is by commonsense and by simple maths 32 | (m + an + k) = 2(m + bn + k) 33 | k = n(a-2b) - m 34 | // m = length of list not in loop 35 | // n = length of loop 36 | // a = no of rounds by fast pointer in the loop 37 | // b = no of rounds by slow pointer in the loop 38 | // k = start of loop to point where they can meet. We can see k is a finite value. Hence proved. 39 | 40 | // Even if the speed is 3x, 4x, 5x it will catch the slow pointer. 41 | 42 | -------------------------------------------------------------------------------- /04 (Linked List)/Practice Problems/23) flattenAMultiLevelDoublyLinkedList.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/ 2 | 3 | Do after revising DFS 4 | -------------------------------------------------------------------------------- /04 (Linked List)/Practice Problems/26) oddEvenLinkedList.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/odd-even-linked-list/ 2 | 3 | // Similar to partitionList problem 4 | 5 | class Solution { 6 | public: 7 | ListNode* oddEvenList(ListNode* head) { 8 | if(head==NULL || head->next==NULL) return head; 9 | 10 | ListNode *dummyLeft = new ListNode(-1); 11 | ListNode *dummyRight = new ListNode(-1); 12 | ListNode *ltail = dummyLeft; // temp1 13 | ListNode *rtail = dummyRight; // temp2 14 | 15 | int flag = 1; 16 | while(head){ 17 | if(flag==1){ 18 | ltail->next = head; 19 | ltail = ltail->next; 20 | flag--; 21 | } 22 | else if(flag==0){ 23 | rtail->next = head; 24 | rtail = rtail->next; 25 | flag++; 26 | //cout<next; 29 | } 30 | ltail->next = dummyRight->next; 31 | rtail->next = NULL; 32 | 33 | return dummyLeft->next; 34 | } 35 | }; 36 | 37 | -------------------------------------------------------------------------------- /04 (Linked List)/Practice Problems/28) insertionSortList.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/insertion-sort-list/ 2 | 3 | https://youtu.be/Kk6mXAzqX3Y 4 | 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode() : val(0), next(nullptr) {} 12 | * ListNode(int x) : val(x), next(nullptr) {} 13 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | // jo node sahi jagah pe nahi hai use utha k aage lana hai 19 | ListNode* insertionSortList(ListNode* head) { 20 | ListNode *dummy = new ListNode(-1); 21 | dummy->next = head; 22 | ListNode *cur = head, *prev = dummy; 23 | while(cur){ 24 | if(cur->next && (cur->next->val < cur->val)){ 25 | // insertion 26 | while(prev->next && (prev->next->val < cur->next->val)) prev = prev->next; 27 | 28 | // making connections 29 | ListNode *temp = prev->next; // storing ki kho na jae 30 | prev->next = cur->next; 31 | cur->next = cur->next->next; 32 | prev->next->next = temp; 33 | prev = dummy; // firse yaha se comparsion start krna padega 34 | } 35 | else cur = cur->next; // element at right position already 36 | } 37 | return dummy->next; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /04 (Linked List)/Practice Problems/30) rotateList.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/rotate-list/ 2 | 3 | // Brute force: 4 | // O(N*K) time 5 | // Everytime traverse till end and rotate k times 6 | 7 | 8 | // Optimised 9 | // As you should not rotate 1000 times if the length of the list is just 5 10 | // ie any multiple of length will give back original linked list again. 11 | 12 | // 1) count the length of the list 13 | // 2) last ->next = head; 14 | // 3) point length - k th node to NULL 15 | 16 | // If 2 rotations are to be made & length of the list is 5, 3rd node will be pointed to NULL 17 | 18 | // TC = O(N) approx, O(1) space 19 | 20 | class Solution { 21 | public: 22 | ListNode* rotateRight(ListNode* head, int k) { 23 | if(head==NULL || head->next==NULL || k==0) return head; 24 | 25 | // find length 26 | ListNode *temp = head; 27 | int len = 1; 28 | while(temp->next){ 29 | temp = temp->next; 30 | len++; 31 | } 32 | 33 | temp->next = head; // last node ko first node se join kr dia 34 | k = k%len; 35 | k = len-k; 36 | 37 | while(k--) temp = temp->next; 38 | head = temp->next; // making new head location(after making temp k next ko head node) 39 | temp->next = NULL; // temp ka connection break kar denge ar null ko point kr denge 40 | 41 | return head; 42 | } 43 | }; 44 | 45 | -------------------------------------------------------------------------------- /04 (Linked List)/Practice Problems/31) swapNodesInLL.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/swap-nodes-in-a-linked-list-without-swapping-data/ 2 | 3 | For future abhi yeh jaroori nahi qki thoda complex padta hai 4 | 5 | https://youtu.be/ws8hmOpxdIM 6 | 7 | https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ 8 | Isme kya hai ki sirf value change krne ko keh raha hai toh asan hai. 9 | 10 | // sirf value hi change krni thi 11 | class Solution { 12 | public: 13 | // We traverse the list until we reach the kth node. 14 | // Then we set "kth" to that node to remember it, set ptr2 to head and continue traversing the list, while we move both ptr1 and ptr2. 15 | // When ptr1 reaches the end - ptr2 is on the (n-k)th node. 16 | // Now we swap "kth" and "ptr2" and we're done! 17 | // Important: The problem description specifically asks to swap values, not nodes themselves. 18 | 19 | // agar nodes swap krni hai toh refer: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/solutions/1366214/Optimized-Solution-o(n)-time-or-Swapping-of-Nodes-in-Java/ (lengthy) 20 | ListNode* swapNodes(ListNode* head, int k) { 21 | ListNode *ptr1 = head, *ptr2 = head, *kth = NULL; 22 | while (--k) 23 | ptr1 = ptr1->next; 24 | 25 | kth = ptr1; 26 | ptr1 = ptr1->next; 27 | 28 | while (ptr1) { 29 | ptr1 = ptr1->next; 30 | ptr2 = ptr2->next; 31 | } 32 | swap(ptr2->val, kth->val); 33 | return head; 34 | } 35 | }; -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/01) buildMinHeap.cpp: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/build-min-heap_1171167 2 | 3 | #include 4 | using namespace std; 5 | 6 | void heapify(vector &arr, int n, int i){ 7 | int smallest = i; // The element that needs to be taken to correct place. 8 | int left = 2*i+1; // coz 0 based indexing. 9 | int right = 2*i+2; 10 | 11 | if(left arr[left]){ 12 | smallest = left; 13 | } 14 | if(right arr[right]){ 15 | smallest = right; 16 | } 17 | 18 | if(smallest!= i){ // ie smallest has been updated 19 | swap(arr[smallest], arr[i]); 20 | heapify(arr, n, smallest); // recur again for remaining 21 | } 22 | } 23 | 24 | vector buildMinHeap(vector &arr) 25 | { 26 | // Write your code here 27 | int n = arr.size(); 28 | for(int i=n/2-1; i>=0; i--){ 29 | heapify(arr, n, i); 30 | } 31 | return arr; 32 | 33 | } 34 | 35 | 36 | // Building a heap is O(N) 37 | // heapify is O(logn) 38 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/05) mergeTwoBinaryMaxHeaps.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/merge-two-binary-max-heap0144/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article 2 | 3 | class Solution{ 4 | public: 5 | void heapify(vector &arr, int n, int i){ 6 | int largest = i; 7 | int left = 2*i+1; 8 | int right = 2*i+2; 9 | 10 | if(left < n && arr[largest] < arr[left]){ 11 | largest = left; 12 | } 13 | if(right < n && arr[largest] < arr[right]){ 14 | largest = right; 15 | } 16 | 17 | if(largest!=i){ 18 | swap(arr[largest], arr[i]); 19 | heapify(arr, n, largest); 20 | } 21 | } 22 | 23 | vector mergeHeaps(vector &a, vector &b, int n, int m) { 24 | // your code here 25 | vector ans; 26 | for(auto i: a){ 27 | ans.push_back(i); 28 | } 29 | for(auto i:b){ 30 | ans.push_back(i); 31 | } 32 | 33 | // heapify 34 | int size = ans.size(); 35 | for(int i = size/2 - 1; i>=0; i--){ // ie call for first half of the array 36 | heapify(ans, size, i); 37 | } 38 | return ans; 39 | } 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/06) minumumCostOfRopes.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/1 2 | 3 | long long minCost(long long arr[], long long n) { 4 | // Your code here 5 | priority_queue, greater> pq; // min heap 6 | 7 | for(int i=0; i 1){ 14 | long long a = pq.top(); 15 | pq.pop(); 16 | 17 | long long b = pq.top(); 18 | pq.pop(); 19 | 20 | long long sum = a+b; 21 | cost += sum; 22 | 23 | pq.push(sum); 24 | } 25 | return cost; 26 | } 27 | 28 | // Yeh concept bhi bahot imp hai in heap ki, top k do elements nikale ar fr unse kuch operation kia ar dobara heap m daal dia. 29 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/07) bst to min or max heap.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/bst-to-max-heap/1 2 | 3 | To max heap 4 | 5 | 1 2 3 4 5 6 7 6 | 7 | 7 8 | / \ 9 | 3 6 10 | / \ / \ 11 | 1 2 4 5 12 | 13 | 1 then 2 then 3 14 | 4 then 5 then 6 15 | left then right then root (post order ki hint) // We have to convert in a "special" maxheap 16 | And inorder of a bst gives array in sorted order 17 | 18 | class Solution{ 19 | public: 20 | vector arr; 21 | int i=0; 22 | void convertToMaxHeapUtil(Node* root){ 23 | // Your code goes here 24 | inorder(root); 25 | postorder(root); 26 | } 27 | 28 | void inorder(Node *root){ 29 | if(root==NULL) return; 30 | 31 | inorder(root->left); 32 | arr.push_back(root->data); 33 | inorder(root->right); 34 | } 35 | 36 | void postorder(Node *root){ 37 | if(root==NULL) return; 38 | 39 | postorder(root->left); 40 | postorder(root->right); 41 | root->data = arr[i]; // nodes ki value change krte gaye. 42 | i++; 43 | } 44 | 45 | }; 46 | 47 | 48 | To min heap 49 | https://www.geeksforgeeks.org/convert-bst-min-heap/ 50 | 51 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/08) mergeK-SortedArrays.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/merge-k-sorted-arrays/ 2 | 3 | https://www.geeksforgeeks.org/merge-k-sorted-arrays-set-2-different-sized-arrays/ (This has better code) 4 | 5 | // The process must start with creating a MinHeap and inserting the first element of all the k arrays. 6 | // Remove the root element of Minheap and put it in the output array and insert the next element from the array of removed element. 7 | // To get the result the step must continue until there is no element left in the MinHeap. 8 | 9 | Time Complexity: O(N Log k) 10 | Auxiliary Space: O(N) 11 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/10) sortK-NearlySortedArray.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/nearly-sorted-1587115620/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article 2 | 3 | // K-K groups m move krke heap bana k smallest element nikal k lete jao. 4 | // Elements at max k positions pe hai 5 | 6 | Asked in Flipkart 7 | 8 | vector nearlySorted(int arr[], int n, int k){ 9 | // Your code here 10 | vector ans; 11 | priority_queue, greater> pq; // min heap. 12 | for(int i=0; ik){ 15 | ans.push_back(pq.top()); 16 | pq.pop(); 17 | } 18 | } 19 | while(!pq.empty()){ // adding remaining heap elements to the heap. 20 | ans.push_back(pq.top()); 21 | pq.pop(); 22 | } 23 | return ans; 24 | } 25 | 26 | Time Complexity: 27 | O(k) to build the initial min-heap 28 | O((n-k)logk) for remaining elements. 29 | Thus we get O(nlogk) overall TC. 30 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/14) K-ClosestPointsToOrigin.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/k-closest-points-to-origin/ 2 | 3 | To minimise sqrt(x^2 + y^2) ie we will make this key. 4 | Will same as storing (x^2 + y^2) coz hona toh sort hi hai. 5 | 6 | Other pair half will be the coordinates. 7 | 8 | class Solution { 9 | public: 10 | vector> kClosest(vector>& points, int k) { 11 | priority_queue>> pq; // max heap kth smallest nikalna hai 12 | 13 | int n = points.size(); 14 | for(int i=0; ik) pq.pop(); 18 | } 19 | 20 | vector> ans; 21 | while(!pq.empty()){ 22 | pair q = pq.top().second; 23 | ans.push_back({q.first, q.second}); 24 | pq.pop(); 25 | } 26 | return ans; 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/15) MedianInADataStream.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-median-from-data-stream/ 2 | 3 | MUST DO: 4 | 5 | Refer my submissions 6 | 7 | Yet to watch: 8 | 9 | https://youtu.be/EcNbRjEcb14 (Keerti Purswani) 10 | https://youtu.be/cjQNm2eS6Lw (hello world) 11 | 12 | https://youtu.be/jnj87BSi9Is (MIK) 13 | 14 | 15 | Follow up ans: 16 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/17) topKFrequentWords.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/top-k-frequent-words/ 2 | 3 | class Solution { 4 | public: 5 | typedef pair P; 6 | 7 | struct cmp { 8 | bool operator()(P& a, P& b){ 9 | return a.second > b.second || (a.second == b.second && a.first < b.first); 10 | } 11 | }; 12 | // dikkat yahi hai ki yeh chahta hai ki agar frequency same ho toh alphabetical bhi ho jae, nahi toh jiski freqency jada wo pehle aa jae. Isliye custom likhna hi padega 13 | 14 | vector topKFrequent(vector& words, int k) { 15 | int n = words.size(); 16 | 17 | unordered_map m; 18 | for(auto &word: words){ 19 | m[word]++; 20 | } 21 | 22 | priority_queue, cmp> pq; // jada frequency walo ko preserve krna hai 23 | 24 | for(auto &x: m){ 25 | auto freq = x.second; 26 | auto word = x.first; 27 | pq.push({word, freq}); 28 | if(pq.size()>k) pq.pop(); 29 | } 30 | vector ans; 31 | while(!pq.empty()){ 32 | ans.push_back(pq.top().first); 33 | pq.pop(); 34 | } 35 | reverse(ans.begin(), ans.end()); 36 | return ans; 37 | } 38 | }; 39 | 40 | https://github.com/MAZHARMIK/Interview_DS_Algo/blob/master/Heap/Top%20K%20Frequent%20Words.cpp (MIK) 41 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/19) IPC-Trainers.cpp: -------------------------------------------------------------------------------- 1 | https://www.codechef.com/problems/IPCTRAIN 2 | 3 | Good ques on heap DS 4 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Heap and Priority Queue/Practice Problems/21) maximumSubsequenceScore.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/maximum-subsequence-score/ 2 | 3 | https://youtu.be/z9oUzKhEYJU (MIK) For explanation 4 | 5 | Problem when two arrays of equal length are given and heap is to be used 6 | 7 | Similar problems: 8 | https://leetcode.com/problems/maximum-performance-of-a-team/ 9 | 10 | https://leetcode.com/problems/minimum-cost-to-hire-k-workers/ 11 | 12 | Just see my submissions. -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Queues/queue.cpp: -------------------------------------------------------------------------------- 1 | https://www.cplusplus.com/reference/queue/queue/ 2 | 3 | FIFO (Topmost / pop element is the first element that got in first) 4 | 5 | // Implement Queue using Array 6 | 3 2 1 8 6 7 | Front Rear 8 | 9 | If we perform a push operation after a pop operation, we can manage it using a circular array ie taking modulo. 10 | 11 | // Given the size of array is n 12 | 13 | push(x){ 14 | if(cnt==n){ // ie the queue is full 15 | return -1; 16 | } 17 | a[rear%n] = x; 18 | rear++; 19 | cnt++; 20 | } 21 | 22 | pop(){ 23 | if(cnt==0) return; // no element in the queue 24 | a[front%n] = -1; // a dummy number assigned 25 | front++; 26 | cnt--; 27 | } 28 | 29 | top(){ 30 | if(cnt==0) return -1; // no element in the queue 31 | return a[front%n]; 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/03) nextGreaterElement(iii).cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/next-greater-element-iii/ 2 | 3 | class Solution { 4 | public: 5 | // Using next permutation ques concept 6 | int nextGreaterElement(int m) { 7 | string s1 = to_string(m); // given 12 -> "12" 8 | int n = s1.size(); 9 | int breakpt = -1; 10 | // finding breakpt 11 | for(int i=n-2; i>=0; --i){ 12 | if(s1[i]breakpt; --i){ 20 | if(s1[i]>s1[breakpt]){ 21 | swap(s1[i], s1[breakpt]); 22 | reverse(s1.begin()+breakpt +1, s1.end()); 23 | break; 24 | } 25 | } 26 | } 27 | long long ele = stoll(s1); // iska dhyan rakhna hoga 28 | if(ele>INT_MAX) return -1; // out of bound na chala jae 29 | return ele; 30 | } 31 | }; 32 | 33 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/04) nearestGreaterToLeft.cpp: -------------------------------------------------------------------------------- 1 | // NGL 2 | 3 | arr[] = {1, 3, 2, 4} 4 | 5 | We will see the left array on each element 6 | Ans[] = {-1, -1, 3, -1} 7 | 8 | // Brute force 9 | 10 | for(int i=0; i=0; --j){} 12 | } 13 | 14 | j is dependent on i (j=i-1) ie itna brute force likh k I got ki stack use hoga 15 | 16 | // Changes from past ques 17 | // 1) Traverse left to right 18 | // 2) No need to reverse 19 | 20 | vector ans; 21 | stack s; 22 | 23 | for(int i=0; i s.top()){ 25 | s.pop(); 26 | } 27 | if(s.empty()){ 28 | ans.push_back(-1); 29 | } 30 | else{ 31 | ans.push_back(s.top()); 32 | } 33 | s.push(arr[i]); 34 | } 35 | 36 | https://www.geeksforgeeks.org/closest-greater-or-same-value-on-left-side-for-every-element-in-array/ 37 | 38 | Other solution 39 | An efficient solution is to use Self-Balancing BST (Implemented as set in C++ and TreeSet in Java). 40 | In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time. 41 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/05) nearestSmallerElement.cpp: -------------------------------------------------------------------------------- 1 | https://www.interviewbit.com/problems/nearest-smaller-element/ 2 | 3 | // Nearest smaller element or Nearest smaller to left 4 | 5 | // Nearest Smaller Element 6 | // Left to right traverse karenge ar dekhenge ki stack m abhi koi bada element toh nahi hai, sabko pop kar do 7 | 8 | vector Solution::prevSmaller(vector &A) { 9 | vector ans; 10 | stack s; 11 | 12 | for(int i=0; i=A[i]){ // this comparison condition changes 14 | s.pop(); 15 | } 16 | if(s.empty()){ 17 | ans.push_back(-1); 18 | } 19 | else{ 20 | ans.push_back(s.top()); 21 | } 22 | s.push(A[i]); 23 | } 24 | return ans; 25 | } 26 | 27 | Nearest Smaller to Right 28 | 29 | // We will traverse from right 30 | // reverse at end coz using push_back 31 | // equality condition changes 32 | 33 | vector Solution::nextSmaller(vector &A) { 34 | vector ans; 35 | stack s; 36 | 37 | for(int i=A.size()-1; i>=0; --i){ 38 | while(!s.empty() && s.top()>=A[i]){ // this comparison condition changes from NGR (Yeh = sign k liye consecutive equal elements in inputs deke dekh lena) 39 | s.pop(); 40 | } 41 | if(s.empty()){ 42 | ans.push_back(-1); 43 | } 44 | else{ 45 | ans.push_back(s.top()); 46 | } 47 | s.push(A[i]); 48 | } 49 | reverse(ans.begin(), ans.end()); 50 | 51 | return ans; 52 | } 53 | 54 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/06) dailyTemperatures.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/daily-temperatures/ 2 | 3 | // Same as NGER 4 | // We have to return days to wait ie difference in indices. 5 | 6 | class Solution { 7 | public: 8 | vector dailyTemperatures(vector& temperatures) { 9 | vector ans; 10 | stack s; 11 | for(int i=temperatures.size()-1; i>=0; i--){ 12 | while(!s.empty() && temperatures[s.top()]<=temperatures[i]){ 13 | s.pop(); 14 | } 15 | if(s.empty()){ 16 | ans.push_back(0); 17 | } 18 | else{ 19 | ans.push_back(s.top()-i); 20 | } 21 | s.push(i); 22 | } 23 | reverse(ans.begin(), ans.end()); 24 | return ans; 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/13) IterativeTowerOfHanoi.cpp: -------------------------------------------------------------------------------- 1 | https://en.wikipedia.org/wiki/Tower_of_Hanoi 2 | 3 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/14) ImplementStackUsingHeap.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shashwat0105/CPP-Data-Structures-and-Algorithms/9d6621248c4c15fa32267527761f1b5a59cfbfb4/05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/14) ImplementStackUsingHeap.cpp -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/Practice Problems/19) removeAllAdjacentDuplicatesInAString.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 2 | 3 | // Using stack 4 | class Solution { 5 | public: 6 | string removeDuplicates(string s) { 7 | int n = s.size(); 8 | stack st; 9 | string ans=""; 10 | 11 | for(auto &c: s){ 12 | if(st.empty() || st.top()!=c) st.push(c); 13 | else st.pop(); 14 | } 15 | 16 | while(!st.empty()){ 17 | ans.push_back(st.top()); 18 | st.pop(); 19 | } 20 | reverse(ans.begin(), ans.end()); 21 | return ans; 22 | } 23 | }; 24 | 25 | 26 | // Without stack by just traversing(more intuitive) // using ans string as a kind of stack 27 | class Solution { 28 | public: 29 | string removeDuplicates(string s) { 30 | int n = s.size(); 31 | string ans=""; 32 | 33 | for(auto &c: s){ 34 | if(ans.size()==0) ans.push_back(c); 35 | else if(ans.back()==c) ans.pop_back(); 36 | else ans.push_back(c); 37 | } 38 | return ans; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/infix-prefix-postfix.cpp: -------------------------------------------------------------------------------- 1 | https://youtu.be/TP_x4aSQ1qU 2 | 3 | // From this pdf u can the examples of conversions 4 | https://github.com/Prince-1501/Hello_world-Competiitve-Programming/blob/master/Leetcode/stack/Infix%2C%20Prefix%20and%20Postfix%20Expressions.pdf 5 | 6 | a+b Infix 7 | ab+ Postfix 8 | +ab Prefix 9 | 10 | Infix to Postfix using stack(Pseudo code is in video or gfg se le skte ho aage ques dekhenge): 11 | TC = O(N) 12 | 13 | https://youtu.be/60iXG0oY_Fg 14 | 15 | Evaluating Postfix value 16 | 17 | 10 2 * 3 + = 23 18 | https://youtu.be/z9eFi0iljS4 19 | 20 | Push operands as it is and when operator comes, pop two operands and evaluate them and push it back to the stack. 21 | 22 | say we have to do: x1 x2 / 23 | the element popped first is x2 and element popped second is x1 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /05 (Stacks and Queue and Heap Or Priority Queue/Stacks/stacks.cpp: -------------------------------------------------------------------------------- 1 | Types of Problems in Stack 2 | (Monotonic Stack Problems: 1,2,3,4,5,6,7) 3 | 1-Type 4 | 1) Nearest Greater to left (Nearest larger element) 5 | 2) Nearest Greater to right (Nearest Smaller element) 6 | 3) Nearest smaller to left 7 | 4) Nearest smaller to right 8 | 9 | 5) Stock Span Problem 10 | 6) Maximum Area Histogram 11 | 12 | 7) Maximum area of Rectangle in Binary Matrix 13 | 14 | 8) Rain water trapping 15 | 9) Implementing a Min Stack (With and without Extra Space) 16 | // To be done in the practice folder: 17 | 10) Implementing a stack using Heap 18 | 11) The celebrity problem 19 | 12) Longest valid parenthesis 20 | 13) Iterative TOH(Tower Of Hanoi) 21 | Implementing TOH using stack is easy, but iteratively is difficult(But was asked in interview) 22 | 23 | 24 | // IDENTIFICATION OF STACK 25 | // 1) Array 26 | // 2) Two for loops in which inner loop's j is dependent on i, then if brute force is O(n^2) then there is an optimized soln using stack. 27 | 28 | 29 | // Implementation of Stack using arrays 30 | int arr[5]; 31 | top = -1; 32 | 33 | push(x){ 34 | arr[++top] = x; 35 | } 36 | 37 | pop(){ 38 | top--; 39 | } 40 | 41 | top(){ 42 | return arr[top]; 43 | } 44 | 45 | size(){ 46 | return top+1; 47 | } 48 | 49 | isEmpty(){ 50 | return top==-1; 51 | } 52 | 53 | 54 | // Implement Stack using Queue 55 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/03) sortAStack.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/sort-a-stack-using-recursion/ 2 | https://practice.geeksforgeeks.org/problems/sort-a-stack/1 3 | 4 | Same as sorting an array 5 | 6 | STL is : stack.sort() 7 | 8 | /*The structure of the class is 9 | class SortedStack{ 10 | public: 11 | stack s; 12 | void sort(); 13 | }; 14 | */ 15 | 16 | // there was not a single class so need to declare insert before. 17 | void insertAtCorrectPosition(stack &s, int temp){ 18 | if(s.size()==0 || s.top()<=temp){ // top of stack has greatest element. Just change < to > then top of stack will have least element. (WOW) 19 | s.push(temp); 20 | return; 21 | } 22 | 23 | int val = s.top(); 24 | s.pop(); 25 | insertAtCorrectPosition(s, temp); 26 | s.push(val); 27 | return; 28 | } 29 | 30 | void SortedStack :: sort() 31 | { 32 | //Your code here 33 | if(s.size()==1) return; 34 | 35 | int temp = s.top(); 36 | s.pop(); 37 | sort(); 38 | insertAtCorrectPosition(s, temp); 39 | return; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/05) reverseAStack.cpp: -------------------------------------------------------------------------------- 1 | // Without using extra stack we have to do 2 | // Using recursion 3 | 4 | 5 | // After poping the top element, I have to insert it at the bottom (ie its correct place) (ie another recursive problem) 6 | 7 | void insertAtBottom(stack &s, int ele){ 8 | // base condition 9 | if(s.size()==0){ // will be inserted when there is no element left ie at the bottom 10 | s.push(ele); 11 | return; 12 | } 13 | 14 | int temp = s.top(); 15 | s.pop(); 16 | insertAtBottom(s, ele); // recursive call for the new s 17 | s.push(temp); 18 | return; 19 | } 20 | 21 | void reverse(stack &s){ 22 | // base condition 23 | if(s.size()==1) return; 24 | 25 | int temp = s.top(); 26 | s.pop(); 27 | reverse(s); 28 | insertAtBottom(s, temp); // inserting the element which we have popped 29 | return; 30 | } 31 | 32 | // Thinking 33 | // High Level Thinking 34 | Expectation 35 | 5 1 36 | 4 2 37 | 3 -> 3 38 | 2 4 39 | 1 5 40 | Given Reversed 41 | 42 | Faith 43 | 4 1 44 | 3 -> 2 45 | 2 3 46 | 1 4 47 | Given Reversed 48 | 49 | Relating faith with expectation. 50 | That we have to insert that 5 at the bottom of the reversed stack provided by reverse(4) 51 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/14) printN-bitBinaryNumbersHavingMore1Than0.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/print-n-bit-binary-numbers-having-more-1s-than-0s0252/1/ 2 | 3 | // Thought process is similar to previous ques 4 | 5 | #1's >= #0's (Legal Prefix) 6 | 7 | Use wired headset to hear 8 | https://youtu.be/U81n0UYtk98 (Aditya Verma) 9 | 10 | Start mein 1 hi rakhna padega 11 | 12 | Also, 13 | Choice for 1 is always available (As seen from the recursive tree) 14 | Choice for 0 is when no of 1 > no of 0 in the current state. (ie #1 used till now = 3, #0 used till now = 2, then both equal is also allowed ie we can still add a 0) 15 | 16 | 17 | class Solution{ 18 | public: 19 | vector ans; 20 | void solve(int n, int ones, int zeroes, string op){ // ones, zeroes are no of 1's 0's used till now to fill n position. 21 | if(n==0){ // all the n bits are filled 22 | ans.push_back(op); 23 | return; 24 | } 25 | 26 | solve(n-1, ones+1, zeroes, op+'1'); // adding 1s is always allowed 27 | 28 | if(ones>zeroes){ 29 | solve(n-1, ones, zeroes+1, op+'0'); 30 | } 31 | // return; 32 | } 33 | 34 | vector NBitBinary(int N){ 35 | string op = ""; 36 | solve(N, 0, 0, op); 37 | return ans; 38 | } 39 | }; 40 | 41 | 42 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/18) subsetSumGFG.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/subset-sums2234/1# 2 | 3 | // To interviewer 4 | // Brute force using bit manipulation to generate power set TC = O(2^N*k) 5 | 6 | void solve(int i, vector &ip, int sum, vector &ans){ 7 | if(i==ip.size()){ 8 | ans.push_back(sum); 9 | return; 10 | } 11 | 12 | // pick 13 | solve(i+1, ip, sum+ip[i], ans); 14 | // not pick 15 | solve(i+1, ip, sum, ans); 16 | } 17 | 18 | vector subsetSums(vector arr, int N){ 19 | // Write Your Code here 20 | vector ans; 21 | 22 | solve(0, arr, 0, ans); 23 | return ans; 24 | } 25 | 26 | // Dusra hai ki wahi op nikalo ar fr op k har element ko add krke sum nikal k ans m push kr do(Jiski jaroorat ni hai) 27 | 28 | // Very Similar ques 29 | https://leetcode.com/problems/sum-of-all-subset-xor-totals/ 30 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/26) combinations.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/combinations/ 2 | 3 | class Solution { 4 | public: 5 | void solve(int idx, int n, int k, vector &op, vector> &ans){ 6 | if(op.size()==k){ 7 | ans.push_back(op); 8 | return; 9 | } 10 | 11 | for(int i=idx; i<=n; ++i){ 12 | op.push_back(i); 13 | solve(i+1, n, k, op, ans); 14 | op.pop_back(); 15 | } 16 | } 17 | 18 | vector> combine(int n, int k) { 19 | vector> ans; 20 | vector op; 21 | 22 | solve(1, n, k, op, ans); 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/28) decodeString.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/decode-string/ 2 | 3 | https://youtu.be/yaCRdWMq4A4 (Knowledge center) 4 | 5 | class Solution { 6 | public: 7 | string recDecodeString(string &s, int &i){ 8 | string ans; 9 | while(i 0){ // append it k times 18 | ans += r; 19 | } 20 | i++; // i is now pointing at ']' so we skip it 21 | } 22 | else{ // its not a digit 23 | ans += s[i++]; // directly append it to the result 24 | } 25 | } 26 | return ans; 27 | } 28 | 29 | string decodeString(string s) { 30 | int i = 0; 31 | return recDecodeString(s, i); 32 | } 33 | }; 34 | 35 | -------------------------------------------------------------------------------- /06 (Recursion and Backtracking)/Practice Problems/29) knightTour.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/the-knights-tour-problem/ 2 | 3 | https://leetcode.com/problems/check-knight-tour-configuration/description/ 4 | 5 | class Solution { 6 | public: 7 | // If I can visit all the cells, also keep checking the cell I visit is a value more 8 | void rec(int i, int j, int n, int m, vector>&grid, vector>&vis, int c){ 9 | if(i<0||i>=n||j<0||j>=m || grid[i][j]!=c || vis[i][j]==1) return; 10 | 11 | vis[i][j]=1; 12 | c++; 13 | 14 | int dr[8]={2, 2,-2, -2,-1, 1, -1, 1}; 15 | int dc[8]={1, -1, 1, -1, 2, -2, -2, 2}; 16 | 17 | for(int l=0; l<8; l++){ 18 | int nr= i+ dr[l]; 19 | int nc= j+ dc[l]; 20 | rec(nr, nc, n, m, grid, vis, c); 21 | } 22 | } 23 | 24 | 25 | bool checkValidGrid(vector>& grid) { 26 | if(grid[0][0]!=0) return false; 27 | int n=grid.size(); 28 | int m=grid[0].size(); 29 | int c=0; 30 | vector>vis(n, vector(m, 0)); 31 | rec(0, 0, n, m, grid, vis, c); 32 | for(int i=0; i>& board, string word, int i, int j, int n, int m, int k){ 6 | if(k >= word.size())return true; 7 | if(i<0 || i>=n || j<0 || j>=m || board[i][j]=='.' || word[k]!=board[i][j]) return false; 8 | if(word.size() == 1 && word[k]==board[i][j]) return true; 9 | board[i][j] = '.'; // when matches I make it a dot 10 | bool temp = false; 11 | int x[4] = {0,0,-1,1}; 12 | int y[4] = {-1,1,0,0}; 13 | for(int index=0;index<4;index++){ 14 | temp = temp || helper(board,word,i+x[index],j+y[index],n,m,k+1); 15 | } 16 | board[i][j] = word[k]; // backtrack to make board return to its old state 17 | return temp; 18 | } 19 | 20 | bool exist(vector>& board, string word) { 21 | // similar to rat and maze problem 22 | // k = current index of the word 23 | int n=board.size(); 24 | if(n==0) return false; 25 | int m=board[0].size(); 26 | if(word.size()==0) return false; 27 | for(int i=0;i freqList; 17 | map keyNode; 18 | 19 | capacity=0; 20 | freq=0; 21 | 22 | // We can use the list of c++ STL. 23 | // But in interviewer they will/can ask you to implement that list as well. 24 | // So, yeh wala part LRU cache mein bhi daalna hoga striver ki video se. 25 | 26 | See LC submission for code 27 | 28 | 29 | -------------------------------------------------------------------------------- /07 (Design)/Practice Problems/04) findMedianFromDataStream.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-median-from-data-stream/ 2 | 3 | https://practice.geeksforgeeks.org/problems/find-median-in-a-stream-1587115620/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article 4 | -------------------------------------------------------------------------------- /07 (Design)/Practice Problems/05) encodeDecodeTinyURL.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/encode-and-decode-tinyurl/ 2 | 3 | Official 4 | https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/ 5 | 6 | 7 | https://leetcode.com/discuss/interview-question/system-design/?currentPage=1&orderBy=hot&query= 8 | 9 | 10 | Simple u can map the later part to integers 11 | 12 | class Solution { 13 | public: 14 | map mp; 15 | int num=0; 16 | // Encodes a URL to a shortened URL. 17 | string encode(string longUrl) { 18 | num++; 19 | string addOn = to_string(num); 20 | string ans = "http://tinyurl.com/"; 21 | ans+= (string)addOn; 22 | mp[ans] = longUrl; 23 | return ans; 24 | } 25 | 26 | // Decodes a shortened URL to its original URL. 27 | string decode(string shortUrl) { 28 | return mp[shortUrl]; 29 | } 30 | }; 31 | 32 | /////////////////////********************************** 33 | 34 | https://youtu.be/4cIDGXBbW34 35 | 36 | else in actual how will u implement a good one 37 | 38 | https://leetcode.com/problems/encode-and-decode-tinyurl/solutions/100268/two-solutions-and-thoughts/ 39 | 40 | https://leetcode.com/problems/encode-and-decode-tinyurl/solutions/1110674/encode-and-decode-tinyurl-short-easy-w-explanation/ 41 | -------------------------------------------------------------------------------- /07 (Design)/Practice Problems/07) insertDeleteGetRandomDuplicatesAllowed.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/ 2 | 3 | -------------------------------------------------------------------------------- /08 (Trees)/08) sameTree.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/same-tree/ 2 | 3 | Method 1: During the traversal comparsion 4 | We can do any traversal we know and solve the ques 5 | 6 | bool isSameTree(TreeNode* p, TreeNode* q) { 7 | // If both trees are empty, they are the same 8 | if (!p && !q) { 9 | return true; 10 | } 11 | 12 | // If one of the trees is empty or they have different values, they are not the same 13 | if (!p || !q || p->val != q->val) { 14 | return false; 15 | } 16 | 17 | // Recursively check if the left and right subtrees are the same 18 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 19 | } 20 | 21 | Method 2: Comparing after complete traversal. 22 | // Point: Agar do tree ka in order traversal same hoga toh tree same hoga - False 23 | // Point: Agar kisi do tree k koi do traversal say In and Pre order same hai toh tree same hoga - True 24 | 25 | // ie it takes two types of traversals to uniquely indentify a tree. (Also the location of NULL in traversal vector is to be given) 26 | // ie while writing code we insert NULL or a large number say 10^5 27 | // New code of inorder: 28 | 29 | void inorder(TreeNode *root, vector& v){ 30 | if(root){ 31 | inorder(root->left, v); 32 | v.push_back(root->val); 33 | inorder(root->right, v); 34 | } 35 | else{ 36 | v.push_back(100000); 37 | } 38 | } 39 | 40 | // So in this ques, dono ka in ar pre order vector nikal k compare kar lo solve ho jaega ques 41 | 42 | // Follow up: 43 | https://leetcode.com/problems/subtree-of-another-tree/ 44 | -------------------------------------------------------------------------------- /08 (Trees)/13) bottomViewOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1/ 2 | 3 | https://youtu.be/0FtVY6I4pB8 4 | 5 | // For overlapping we take the node which is to the right. 6 | 7 | // We can do vertical order traversal and the last node will make the bottom view. 8 | 9 | // Map : (line, node) // line means vertical line 10 | 11 | class Solution { 12 | public: 13 | vector bottomView(Node *root) { 14 | // Your Code Here 15 | vector ans; 16 | if(root==NULL) return ans; 17 | map mp; 18 | queue>q; 19 | q.push({root, 0}); 20 | while(!q.empty()){ 21 | auto it = q.front(); 22 | q.pop(); 23 | Node *node = it.first; 24 | int line = it.second; 25 | mp[line]= node->data; // isme wo check karne ki jaroorat nahi qki agar koi naya ata hai toh wahi le lia jata hai 26 | 27 | if(node->left){ 28 | q.push({node->left, line-1}); 29 | } 30 | if(node->right){ 31 | q.push({node->right, line+1}); 32 | } 33 | } 34 | 35 | for(auto it: mp){ 36 | ans.push_back(it.second); // second mein hi node data stored hai 37 | } 38 | 39 | return ans; 40 | } 41 | }; 42 | 43 | // 44 | Will recursive traversal work? (inorder, pre, post etc) 45 | generally dont do, as it is more complex (height wgyra bhi leni padegi according to striver) 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /08 (Trees)/24) requirementsNeededToConstructUniqueBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | https://youtu.be/9GMECGQgWrQ 2 | 3 | Can u construct a "unique" binary tree using: 4 | 5 | 1) Preorder and Postorder -> NO 6 | 2) Preorder and Inorder -> YES 7 | 3) Postorder and Inorder -> YES 8 | 9 | Inorder is required because it is important to know what is in the left and right of the binary tree. 10 | -------------------------------------------------------------------------------- /08 (Trees)/27) constructBinaryTreeFromPreorderAndPostorder.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 2 | 3 | There will be many ans so return any. 4 | 5 | class Solution { 6 | private: 7 | unordered_map m; 8 | public: 9 | TreeNode* util(vector& pre,vector& post,int preStart,int preEnd,int postStart,int postEnd){ 10 | if(preStart > preEnd) 11 | return NULL; 12 | TreeNode* root = new TreeNode(pre[preStart]); 13 | if(preStart == preEnd) 14 | return root; 15 | 16 | int idx = m[pre[preStart + 1]]; 17 | int offset = idx - postStart; 18 | root->left = util(pre,post,preStart+1,preStart+1+offset,postStart,idx); 19 | root->right = util(pre,post,preStart+1+offset+1,preEnd,idx+1,postEnd); 20 | return root; 21 | } 22 | 23 | TreeNode* constructFromPrePost(vector& pre, vector& post) { 24 | int n = pre.size(); 25 | for(int i = 0;i < n;i++) 26 | m[post[i]] = i; 27 | return util(pre,post,0,n-1,0,n-1); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /08 (Trees)/30) searchInBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/search-in-a-binary-search-tree/ 2 | 3 | class Solution { 4 | public: 5 | TreeNode* searchBST(TreeNode* root, int val) { 6 | if(root==NULL) return NULL; 7 | 8 | if(root->val==val) return root; 9 | if(root->val>val) return searchBST(root->left, val); 10 | else return searchBST(root->right, val); // yaha pe if laga k condition mat check karo, non void wala error aa jata ki kuch return nahi kia, ya ek separate void function bhi bana skte ho 11 | } 12 | }; 13 | 14 | // Single liner without recursion 15 | 16 | class Solution { 17 | public: 18 | TreeNode* searchBST(TreeNode* root, int val) { 19 | while(root!=NULL && root->val!=val){ 20 | root = val < root->val ? root->left : root->right; 21 | } 22 | return root; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /08 (Trees)/31) ceilFromBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/ceil-from-bst_920464 2 | 3 | https://www.geeksforgeeks.org/floor-and-ceil-from-a-bst/ 4 | 5 | // Ceil of an integer is the closest integer greater than or equal to a given number. 6 | 7 | // Method: 8 | // If u find a number greater than key, then it can be a possible ans so update our ceil value. 9 | // Now move towards smaller values. 10 | 11 | int findCeil(BinaryTreeNode *root, int x){ 12 | // Write your code here. 13 | int ceil= -1; 14 | while(root){ 15 | if(root->data == x){ // If key already exist in our BST (best hai yahi return kr do) 16 | ceil = x; 17 | return ceil; 18 | } 19 | if(root->data > x){ 20 | ceil = root->data; 21 | root = root->left; 22 | } 23 | else if(root->data < x){ // yaha ya toh else likho ya else if sirf if nahi 24 | root = root->right; 25 | } 26 | } 27 | return ceil; 28 | } 29 | 30 | // Recursive soln: 31 | 32 | int func(BinaryTreeNode *curr, int key, int &ceil) 33 | { 34 | if(!curr) return ceil; 35 | if(curr->data == key) return ceil = key; 36 | 37 | if(curr->data > key) { 38 | ceil = curr->data; 39 | return func(curr->left, key, ceil); 40 | } 41 | return func(curr->right, key, ceil); 42 | } 43 | int findCeil(BinaryTreeNode *root, int key){ 44 | int ceil = -1; 45 | ceil = func(root,key,ceil); 46 | return ceil; 47 | } 48 | -------------------------------------------------------------------------------- /08 (Trees)/32) floorFromBST.cpp: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/floor-from-bst_920457 2 | 3 | // The greatest integer value which is <= key is the floor. 4 | 5 | // Agar equal mil gaya toh best hai. 6 | // Agar smaller mila then that is our candidate, we move towards bigger values(move right). 7 | // Ar badi aa gyi toh chote k liye jana padega(move left). 8 | 9 | int floorInBST(TreeNode * root, int x) 10 | { 11 | // Write your code here. 12 | int floor=-1; 13 | while(root){ 14 | if(root->val==x){ 15 | floor = x; 16 | return floor; 17 | } 18 | else if(root->val > x){ 19 | root = root->left; 20 | } 21 | else if(root->val < x){ 22 | floor = root->val; 23 | root = root->right; 24 | } 25 | } 26 | return floor; 27 | } 28 | -------------------------------------------------------------------------------- /08 (Trees)/44) cousinsInABinaryTree.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/cousins-in-binary-tree/ 2 | Decent question 3 | 4 | Using BFSn(better coz visits only upto level of cousins) 5 | https://leetcode.com/problems/cousins-in-binary-tree/solutions/1527386/no-wonder-why-this-question-is-in-easy-category-bfs-c/ 6 | 7 | In this approach I also learned to find depth of a particular node using BFS when its value is given. 8 | For loop jitni baar run hota hai utne levels hote hai. 9 | 10 | Using DFS 11 | https://leetcode.com/problems/cousins-in-binary-tree/solutions/618795/java-c-python-dfs-clean-code/ 12 | -------------------------------------------------------------------------------- /08 (Trees)/Segment Trees , Fenwick Trees, Binary Indexed Trees/segmentTree.cpp: -------------------------------------------------------------------------------- 1 | https://cp-algorithms.com/data_structures/segment_tree.html 2 | 3 | // Since there are updates: 4 | 5 | The leaf nodes are the elements of the array. 6 | As we go up the node store the sum of nodes below it. ie it stores the sum of various segment of that array. 7 | 8 | We only need to change logn nodes(height of the tree) to handle the update query!. 9 | 10 | https://www.youtube.com/watch?v=-dUiRtJ8ot0 striver 11 | 12 | https://www.youtube.com/watch?v=NEG-SoyigGE striver 13 | 14 | https://www.youtube.com/playlist?list=PL5DyztRVgtRWt0Kgy7fCN9OSPgr6AI3DO 15 | codencode 16 | 17 | https://www.youtube.com/results?search_query=segment+tree 18 | 19 | https://codeforces.com/blog/entry/18051 20 | 21 | https://leetcode.com/tag/segment-tree/ 22 | 23 | https://leetcode.com/tag/segment-tree/discuss/2406209/My-Segment-Tree-Implementation-w-Classes-and-Recursion 24 | 25 | 26 | // We will use an array to store the node->vals of the tree 27 | // Left child is stored at 2*i+1 positions. 28 | // Right child is stored at 2*i+2 positions. 29 | 30 | 31 | -------------------------------------------------------------------------------- /08 (Trees)/binarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | N 2 | / \ 3 | L R 4 | 5 | For a binary search tree(BST) following condition should strictly follow for node values: 6 | => Left part of tree < N < Right part of tree 7 | => Entire left subtree should itself be a BST 8 | 9 | // Primarily duplicates are not allowed. 10 | // But if we want to integrate duplicates 11 | // Then: we can either integrate another node or we can have (node, frequency) stored 12 | 13 | // Height of a BST is kept : log n (base2) 14 | 15 | // Search in a BT: O(N) using pre, post, in, level order traversals 16 | // Search in a BST: O(logn) 17 | 18 | // Another important property of BST 19 | // Inorder traversal of BST gives the nodes values always in sorted order (WOW) 20 | 21 | -------------------------------------------------------------------------------- /08 (Trees)/tree.cpp: -------------------------------------------------------------------------------- 1 | // See CP handbook for a general tree 2 | // n nodes and n-1 edges. 3 | 4 | // Esa graph jisme cycle na ho use bolte hai tree 5 | 6 | // Binary tree is a special case for a tree 7 | 8 | https://dynalist.io/d/8JunO-H3ZxPg9wDul58ouDMS (Master Tree DS almost Saare topics cover ho jaenge) 9 | 10 | // DFS at any arbitrary node in tree 11 | // Like we do in graphs, instead of visited, we took parent 12 | void dfs(int vertex, int parent=0){ 13 | for(auto child : g[vertex]){ 14 | if(child==parent) continue; 15 | dfs(child, vertex); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/03) floodFill.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/flood-fill/ 2 | 3 | // Go in all four directions and reject all the invalid edges 4 | // A particular node in a dfs call here will be represented using two variable i and j 5 | 6 | // Better in an interview you make a copy of the input(as tampering with input is not preferred). 7 | 8 | class Solution { 9 | public: 10 | void dfs(int i, int j, int iniColor, int newColor, vector>& image, vector> &directions){ 11 | int n = image.size(); 12 | int m = image[0].size(); 13 | 14 | // Rejecting all the invalid edges beforehand 15 | if(i<0 || j<0 || i>=n || j>=m || image[i][j]!=iniColor) return; // out of bound edge // I will call dfs only when do edges ka color same hoga tabhi toh fr uska color change kar paunga, this also acts as visiting array as I won't go back to the already colored node. 16 | 17 | image[i][j] = newColor; 18 | 19 | for(auto &dir: directions){ 20 | int newI = i+dir.first; 21 | int newJ = j+dir.second; 22 | dfs(newI, newJ, iniColor, newColor, image, directions); 23 | } 24 | } 25 | 26 | vector> floodFill(vector>& image, int sr, int sc, int newColor) { 27 | int iniColor = image[sr][sc]; 28 | vector> directions = {{1,0}, {0,-1}, {-1,0}, {0,1}}; 29 | if(iniColor!=newColor) dfs(sr, sc, iniColor, newColor, image, directions); 30 | return image; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/18) minimumMultiplicationToReachEnd.cpp: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/minimum-multiplications-to-reach-end/1 2 | 3 | https://youtu.be/_BvEJ3VIDWw (Striver) 4 | 5 | Kind of ki jo keh raha kar do problem 6 | 7 | We used to go in adjacent nodes, here we multiply to get adjacent nodes. 8 | 9 | CODE: 10 | int minimumMultiplications(vector& arr, int start, int end) { 11 | queue> q; 12 | q.push({start, 0}); 13 | 14 | vector dist(100000, 1e9); 15 | dist[start] = 0; 16 | int mod = 100000; 17 | 18 | while (!q.empty()){ 19 | int node = q.front().first; 20 | int steps = q.front().second; 21 | q.pop(); 22 | if(node==end) return steps; // early return 23 | for (auto &it : arr){ 24 | int num = (it * node) % mod; 25 | 26 | dist[num] = steps + 1; 27 | 28 | // if (num == end) 29 | // return steps + 1; 30 | q.push({num, steps + 1}); 31 | } 32 | } 33 | } 34 | return -1; 35 | } 36 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/27) pacificAtlanticWaterFlow.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/pacific-atlantic-water-flow/ 2 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/34) findTheTownJudge.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-the-town-judge/ 2 | 3 | // It should give 0 votes, and should get N-1 votes 4 | // [[1, 3]] ; since 2 is missing we are short of a vote hence we have to return -1; 5 | 6 | // Method 1: 7 | class Solution { 8 | public: 9 | int findJudge(int n, vector>& trust) { 10 | // 1st value: How many he trusts 11 | // 2nd value: How many trusts him 12 | vector> arr(n+1, {0, 0}); 13 | for(int i=0; i>& trust) { 33 | // Method 2: Using degree logic 34 | vector data(n+1, 0); 35 | for(auto x: trust){ 36 | data[x[0]]--; 37 | data[x[1]]++; 38 | } 39 | for(int i=1; i<=n; ++i){ 40 | int x = data[i]; 41 | if(x==n-1) return i; 42 | } 43 | return -1; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/35) employeeImportance.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/employee-importance/ 2 | 3 | Asked in GOOGLE 4 | 5 | /* 6 | // Definition for Employee. 7 | class Employee { 8 | public: 9 | int id; 10 | int importance; 11 | vector subordinates; 12 | }; 13 | */ 14 | 15 | class Solution { 16 | public: 17 | int getImportance(vector employees, int id) { 18 | unordered_map m; 19 | for(auto x: employees) m[x->id] = x; 20 | int sum = 0; 21 | dfs(m, id, sum); 22 | return sum; 23 | } 24 | void dfs(unordered_map &m, int id, int &sum){ 25 | sum += m[id]->importance; 26 | for(auto child: m[id]->subordinates) dfs(m, child, sum); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/38) keysAndRooms.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/keys-and-rooms/ 2 | 3 | // Graph already bana hua tha mai fr bhi bana raha tha :| 4 | 5 | class Solution { 6 | public: 7 | void dfs(vector>& rooms, int node, vector & vis){ 8 | vis[node] = 1; 9 | for(auto it: rooms[node]){ 10 | if(vis[it]==0){ 11 | dfs(rooms, it, vis); 12 | } 13 | } 14 | } 15 | 16 | bool canVisitAllRooms(vector>& rooms) { 17 | int n = rooms.size(); 18 | vector vis(n+1, 0); 19 | dfs(rooms, 0, vis); 20 | for(int i=0; i>& rooms, int &numbers, int node, vector &visited){ 33 | visited[node] = 1; 34 | numbers++; 35 | for(auto it: rooms[node]){ 36 | if(!visited[it]){ 37 | dfs(rooms, numbers, it, visited); 38 | } 39 | } 40 | } 41 | 42 | bool canVisitAllRooms(vector>& rooms) { 43 | int n = rooms.size(); 44 | vector visited(n+1, 0); 45 | int numbers=0; 46 | dfs(rooms, numbers, 0, visited); 47 | cout< &parent){ 15 | while(parent[node]!=node) node = parent[node]; 16 | return node; 17 | } 18 | 19 | void connectUnion(int i, int j, vector &parent){ 20 | int iRoot = find(i, parent); 21 | int jRoot = find(j, parent); 22 | 23 | if(iRoot!=jRoot){ 24 | parent[jRoot] = iRoot; 25 | } 26 | } 27 | 28 | vector findRedundantConnection(vector>& edges) { 29 | int n = edges.size(); 30 | vector parent(n+1); 31 | // make node 32 | for(int i=1; i<=n; ++i){ 33 | parent[i] = i; 34 | } 35 | 36 | // Loop in all edges 37 | for(auto edge: edges){ 38 | if(find(edge[0], parent)==find(edge[1], parent)) return edge; // dono ka parent same nikla ie loop bana dia 39 | connectUnion(edge[0], edge[1], parent); 40 | } 41 | return {}; 42 | } 43 | }; 44 | 45 | 46 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/45) timeNeededToInformAllEmployees.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/time-needed-to-inform-all-employees/ 2 | 3 | https://youtu.be/qjDoGPZPIjc 4 | 5 | class Solution { 6 | public: 7 | void dfs(int managerNode, vector& informTime, unordered_map> &umap, int &ans, int &mx){ 8 | mx = max(mx, ans); 9 | for(auto employee: umap[managerNode]){ 10 | ans += informTime[managerNode]; 11 | dfs(employee, informTime, umap, ans, mx); 12 | ans -= informTime[managerNode]; // backtrack 13 | } 14 | } 15 | 16 | int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { 17 | int ans = 0; 18 | int mx = 0; 19 | // creating graph 20 | unordered_map> umap; 21 | for(int i=0; i {0,1,3,4,5} 24 | } 25 | } 26 | 27 | dfs(headID, informTime, umap, ans, mx); 28 | return mx; 29 | } 30 | }; 31 | 32 | 33 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/48) satisfiabilityOfEqualityEquations.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/satisfiability-of-equality-equations/ 2 | 3 | // First process all == signs ie by making them in a single set union. 4 | // Then you can check for != whether they belong to same root(parent) or not. 5 | 6 | class Solution { 7 | public: 8 | vector parent; // Wrote globally to remind you of the resize funciton. 9 | int find(int i){ 10 | if(parent[i]== -1) return i; 11 | return parent[i] = find(parent[i]); 12 | } 13 | 14 | void unionNode(int a, int b){ 15 | a = find(a); 16 | b = find(b); 17 | if(a!=b){ 18 | parent[a]=b; 19 | } 20 | } 21 | 22 | bool equationsPossible(vector& equations) { 23 | parent.resize(26, -1); // as there are 0-25 lowercase alphabets 24 | 25 | for(auto e: equations){ 26 | if(e[1]=='=') unionNode(e[0]-'a', e[3]-'a'); 27 | } 28 | for(auto e: equations){ 29 | if(e[1]=='!'){ 30 | if(find(e[0]-'a') == find(e[3]-'a')) return false; 31 | } 32 | } 33 | return true; 34 | } 35 | }; 36 | 37 | 38 | // During revision 39 | // Can refer other gem of solutions 40 | https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/?currentPage=1&orderBy=most_votes&query= 41 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/49) letterCombinationOfAPhoneNumber.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 2 | 3 | // Primarily a ques of recursion 4 | // Digit: 2346 5 | // We will find ans for say 6 and let recursion do the remaining job 6 | 7 | class Solution { 8 | public: 9 | vector recur(string &D, int i, map &m){ // So that copies of the string is not made 10 | if(i==D.size()) return {""}; // base case return empty vector of string 11 | 12 | vector temp = recur(D, i+1, m); // will give me string of remaining part 13 | vector ans; 14 | 15 | for(auto a: m[D[i]-'0']){ // for every element in say m[6] 16 | for(auto x: temp){ // for every string in temp 17 | ans.push_back(a+x); 18 | } 19 | } 20 | return ans; 21 | } 22 | 23 | vector letterCombinations(string digits) { 24 | if(digits.size()==0) return {}; // note here you can't do {""} 25 | map m; 26 | m[2] = "abc"; 27 | m[3] = "def"; 28 | m[4] = "ghi"; 29 | m[5] = "jkl"; 30 | m[6] = "mno"; 31 | m[7] = "pqrs"; 32 | m[8] = "tuv"; 33 | m[9] = "wxyz"; 34 | 35 | return recur(digits, 0, m); 36 | } 37 | }; 38 | 39 | // Other code 40 | // DFS view explanation 41 | https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/1148310/JS-Python-Java-C%2B%2B-or-Easy-Recursive-DFS-Solution-w-Explanation 42 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/53) allPathsFromSourceToTarget.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/all-paths-from-source-to-target/ 2 | 3 | // Run DFS 4 | // Make a path vector, keep inserting until we get our target. 5 | // Then backtrack to find other paths. 6 | 7 | https://youtu.be/X6b02KyeyLU 8 | 9 | // Decent ques 10 | 11 | class Solution { 12 | public: 13 | void dfs(int curr, vector>& graph, vector>& ans, vector &path){ 14 | path.push_back(curr); 15 | 16 | if(curr == graph.size()-1){ // we reached our target node 17 | ans.push_back(path); 18 | } 19 | else{ // else we call dfs on all its child 20 | for(auto child: graph[curr]){ 21 | dfs(child, graph, ans, path); 22 | } 23 | } 24 | path.pop_back(); // backtrack 25 | } 26 | 27 | vector> allPathsSourceTarget(vector>& graph) { 28 | // vector vis(n, 0); // Directed graph mein visited ka use nahi hota 29 | vector> ans; 30 | vector path; 31 | dfs(0, graph, ans, path); 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Leetcode and GFG/57) minimumJumpsToReachHome.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-jumps-to-reach-home/ 2 | 3 | // Tagda Sawal. 4 | 5 | // No YT soln yet 6 | 7 | // Have to do yet from LC discuss 8 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Others/03) InOutTimeOfNodes.cpp: -------------------------------------------------------------------------------- 1 | // https://youtu.be/4VCqVBnUrDY (Codencode) 2 | 3 | int timer = 1; // integer timer count start from 1 4 | bool dfs(int node){ 5 | vis[node] = 1; 6 | In[node] = timer++; // visiting a node and saving it's in time 7 | 8 | for(int child: adj[node]){ 9 | if(vis[child] == 0){ 10 | dfs(child); 11 | } 12 | } 13 | Out[node] = timer++; // after processing all the childrens, we will save it's out time 14 | } 15 | 16 | // This concept helps us to ans: whether one node lies in the subtree of another or not 17 | // In time of root < In time of child 18 | // Out time of root > Out time of child 19 | 20 | // So, If a node x lies in the subtree of y then: i) In time of x > In time of y ii) Out time of x < Out time of y 21 | 22 | // This concept also helps us in finding bridges and articulation point. 23 | 24 | 25 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Practice Problems/Others/06) subtreeSizeUsingDFS.cpp: -------------------------------------------------------------------------------- 1 | // Given a tree. construct an array subSize[], 2 | // where subSize[V] stores size of subtree rooted at node V 3 | 4 | // 1 5 | // | 6 | // 2 7 | // / \ 8 | // 3 4 9 | // / / \ 10 | // 7 5 6 11 | 12 | // subsize[1] = 7 13 | // subsize[2] = 6 14 | // subsize[3] = 2 15 | // subsize[4] = 3 16 | // subsize[5] = 1 17 | // subsize[6] = 1 18 | // subsize[7] = 1 19 | 20 | // subtree size of a node can be calculated from subtree size of its children 21 | // ie subtree size of 2 = subtree size of 3 + subtree size of 4 + current(which is 1) 22 | 23 | #include 24 | using namespace std; 25 | vector ar[100001]; 26 | int vis[100001] , subSize[100001]; 27 | 28 | int dfs(int node) // returns the size of the subtree rooted at node 'node' 29 | { 30 | vis[node] = 1; 31 | int curr = 1; 32 | 33 | for(int child : ar[node]) 34 | if(vis[child] == 0) 35 | { 36 | curr += dfs(child); 37 | } 38 | 39 | return subSize[node] = curr; 40 | } 41 | 42 | int main() { 43 | int n , a , b; // n = number of nodes 44 | 45 | cin>>n; 46 | for(int i=1;i>a>>b , ar[a].push_back(b) , ar[b].push_back(a); 48 | 49 | //call dfs(1) when 1 is root , if another node is root than pass that node, coz it will be the main parent 50 | dfs(1); 51 | 52 | for(int i=1;i<=n;i++) 53 | cout<<"sub tree size of node "< 4 | using namespace std; 5 | 6 | vector adj[2001]; 7 | int vis[2001], col[2001]; 8 | 9 | bool dfs(int node, int c){ 10 | vis[node] = 1; 11 | col[node] = c; 12 | 13 | for(int child: adj[node]){ 14 | if(vis[child]==0){ 15 | bool res = dfs(child, c^1); 16 | if(res == false) 17 | return false; 18 | } 19 | else if(col[node] == col[child]) 20 | return false; 21 | } 22 | return true; 23 | } 24 | 25 | int main(){ 26 | int t,n,m,u,v; 27 | cin>>t; 28 | for(int tc=1; tc<=t; tc++){ // we didn't used while loop coz we have to print scenario no for each test case. 29 | cin>>n>>m; 30 | 31 | for(int i=1; i< n; i++) adj[i].clear(), vis[i]=0; // since we have multiple test cases(graphs) we need to clear the adjacency list & the visited array for next graph as it will contain past info 32 | 33 | for(int i=1; i<=m; i++) 34 | cin>>u>>v, adj[u].push_back(v), adj[v].push_back(u); 35 | 36 | bool flag = true; 37 | 38 | for(int i=1; i<=n; i++){ 39 | if(vis[i]==0){ 40 | flag = dfs(i, 0); 41 | } 42 | } 43 | cout<<"Scenario #"< 7 | using namespace std; 8 | 9 | const int N = 1e5+10; 10 | int size[N]; 11 | int parent[N]; 12 | 13 | void make(int v){ 14 | parent[v] = v; 15 | size[v] = 1; 16 | } 17 | 18 | int find(int v){ 19 | if(v==parent[v]) return v; 20 | return parent[v] = find(parent[v]); 21 | } 22 | 23 | void Union(int a, int b){ 24 | a = find(a); 25 | b = find(b); 26 | 27 | if(a!=b){ 28 | if(size[a] < size[b]) swap(a, b); // If a is smaller I swap to make it bigger tree 29 | parent[b] = a; // I always want to attach b below a 30 | size[a] += size[b]; 31 | } 32 | } 33 | 34 | int main() { 35 | int n, k; 36 | cin>>n>>k; 37 | for(int i=1; i<=n; ++i){ 38 | make(i); 39 | } 40 | 41 | while(k--){ 42 | int u, v; 43 | cin>>u>>v; 44 | Union(u, v); 45 | } 46 | 47 | int ct = 0; 48 | for(int i=1; i<=n; ++i){ 49 | if(find(i)==i) ct++; 50 | } 51 | cout< 6 | using namespace std; 7 | 8 | const int N = 1e5+10; 9 | int size[N]; 10 | int parent[N]; 11 | multiset sizes; 12 | 13 | void make(int v){ 14 | parent[v] = v; 15 | size[v] = 1; 16 | sizes.insert(1); 17 | } 18 | 19 | int find(int v){ 20 | if(v==parent[v]) return v; 21 | return parent[v] = find(parent[v]); 22 | } 23 | 24 | void merge(int a, int b){ 25 | sizes.erase(sizes.find(size[a])); // Basic concept :we should use sizes.erase(sizes.find(size[a])) ie using iterator to delete, since sizes.erase(size[a]) using value to delete will erase all the occurences 26 | sizes.erase(sizes.find(size[b])); 27 | 28 | sizes.insert(size[a] + size[b]); 29 | } 30 | void Union(int a, int b){ 31 | a = find(a); 32 | b = find(b); 33 | 34 | if(a!=b){ 35 | if(size[a] < size[b]) swap(a, b); // If a is smaller I swap to make it bigger tree 36 | parent[b] = a; // I always want to attach b below a 37 | merge(a, b); 38 | size[a] += size[b]; 39 | } 40 | } 41 | 42 | int main() { 43 | int n, q; 44 | cin>>n>>q; 45 | for(int i=1; i<=n; ++i){ 46 | make(i); 47 | } 48 | 49 | while(q--){ 50 | int u, v; 51 | cin>>u>>v; 52 | Union(u, v); 53 | if(sizes.size()==1){ // there is only one element in the multiset 54 | cout<<"0"< adj[]){ // function name is changed obviously 13 | queueq; 14 | vector indegree(N, 0); 15 | // Step 1: Find indegree 16 | for(int i = 0; i < N; i++){ 17 | for(auto it : adj[i]){ 18 | indegree[it]++; 19 | } 20 | } 21 | // Step 2: Fill queue 22 | for(int i = 0; i < N; i++){ 23 | if(indegree[i]==0){ 24 | q.push(i); 25 | } 26 | } 27 | // Step 3: Simple BFS 28 | int cnt = 0; 29 | while(!q.empty()){ 30 | int node = q.front(); 31 | q.pop(); 32 | cnt++; // we are incrementing cnt 33 | for(auto it : adj[node]){ 34 | indegree[it]--; 35 | if(indegree[it]==0){ 36 | q.push(it); 37 | } 38 | } 39 | } 40 | return cnt!=N; // If cnt and N are unequal means topo sort is not generated hence it is cyclic. 41 | } 42 | }; 43 | 44 | 45 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Theory/17) singleSourceShortestPathOnTrees.cpp: -------------------------------------------------------------------------------- 1 | // Single source shortest path (SSSP) 2 | // To find shortest distance from source node to other node. 3 | 4 | // 1 5 | // / 6 | // 2 7 | // / \ 8 | // 3 4 9 | // / \ 10 | // 5 6 11 | 12 | // dfs(1, 0) -> dfs(2, distance of node 1 +1) = dfs(2, 0+1) -> dfs(3, 1+1) -> dfs(4, 1+1) -> dfs(5, 2+1) -> dfs(6, 2+1) 13 | // This works for trees not graph(we use dijasktra's algorithm in graph) 14 | 15 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Theory/21) minimumSpanningTree.cpp: -------------------------------------------------------------------------------- 1 | // MINIMUM SPANNING TREE (MST) 2 | 3 | 2 3 4 | 0--------1---------2 5 | | / | / 6 | |6 / 8 |5 / 7 7 | | / | / 8 | |/ | / 9 | 3 4 10 | 11 | Spanning Tree: 12 | When you can convert a graph to a tree such that it contains exactly N nodes and N-1 edges. 13 | And every node should be reacheable by every other node. 14 | 2 3 15 | O---O---O (5 nodes and 4 edges), Total Cost(Weight) here: 2+3+6+7=18 16 | | / 17 | |6 / 7 18 | | / 19 | O O 20 | 21 | 22 | 2 3 23 | O---O---O (5 nodes and 4 edges), Total Cost(Weight) here: 2+3+8+5 =18 24 | /| 25 | 8/ |5 26 | O O 27 | 28 | O O O (5 nodes and 4 edges), Total Cost(Weight) here: 6+8+5+7 = 26 29 | | / | / 30 | |6 /8 |5 /7 31 | | / | / 32 | O O 33 | 34 | and so on... among all these spanning trees possible from the above graph, the one having minimum weight is the MST 35 | 36 | -------------------------------------------------------------------------------- /09 (Graph Algorithms)/Theory/28) tarjansAlgorithmForSCC.cpp: -------------------------------------------------------------------------------- 1 | // Tarzan's Algorithm for scc 2 | 3 | // Low-Link Value: For each node u, low link value is defined as lowest id of node recheable from node u. 4 | 5 | // Nodes of 1 SCC have same low-link value 6 | // Number of different low-link values = No of connected components. 7 | 8 | // (YET TO UNDERSTAND THIS ALGO) // Done this in bridges ques 9 | 10 | // Code 11 | // https://ideone.com/XuuN1x 12 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/Hashing/1 nonRepeatingElement.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/non-repeating-element3958/1 2 | 3 | // int arr[] = {5, -1, 2, -1, 3, 2} 4 | 5 | // We will use unordered_map 6 | // Key = the element 7 | // Value = its occurence 8 | 9 | int firstNonRepeating(int arr[], int n){ 10 | unordered_map umap; 11 | for(int i=0; i umap; 28 | for(int i=0; i1){ 33 | return i+1; 34 | } 35 | } 36 | return -1; 37 | } 38 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/Hashing/2 unionOfTwoArrays.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/union-of-two-arrays3538/1# 2 | 3 | int doUnion(int a[], int n, int b[], int m) { 4 | //code here 5 | unordered_set s; 6 | for(int i=0; i s; 22 | // for(int i=0; i s; 40 | 41 | for(int i=0; i umap; 10 | for(int i=0; ifirst; 16 | int val = itr->second; 17 | 18 | int pair = s - key; 19 | 20 | if(pair==key){ // say sum = 8, and arr[] = {2,4,6,7}, on getting 4 as a key, pair = 4, but it will only be valid when there are two 4's is val>1 21 | if(val>1) 22 | return true; 23 | } 24 | else{ 25 | if(umap.find(pair)!=umap.end()) // finding the pair in the remaining map. 26 | return true; 27 | } 28 | } 29 | return false; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/Hashing/4 subarrayWithZeroSum.cpp: -------------------------------------------------------------------------------- 1 | // https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1 2 | 3 | // We will use Hashing and Prefix sum 4 | // If we get two prefix sum same, then there is a subarray having sum 0 (jo beech ka subarray hoga uska sum 0 hoga) 5 | 6 | bool subArrayExists(int arr[], int n) 7 | { 8 | //Your code here 9 | unordered_set s; 10 | int pre_sum=0; 11 | for(int i=0; i 4 5 | // Johnny -> 4 6 | // Jamie -> 3 7 | // Jackie -> 2 8 | 9 | vector winner(string arr[],int n) // we want to return a vector of string 10 | { 11 | unordered_map umap; 12 | for(int i=0; ifirst; // first element is a string 20 | int val = itr->second; // second element is an integer 21 | 22 | if(val>max_vote){ 23 | max_vote = val; 24 | name = key; 25 | } 26 | else if(val==max_vote){ 27 | if(keyans; // declaring a vector of string 34 | ans.push_back(name); 35 | string temp = to_string(max_vote); // to_string is a inbuilt string to convert to string coz max_vote is an integer 36 | ans.push_back(temp); 37 | // ans.push_back(to_string(max_vote)); 38 | 39 | return ans; 40 | } 41 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/Hashing/6 relativeSortArray.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/relative-sort-array/ 2 | // https://practice.geeksforgeeks.org/problems/relative-sorting4323/1 3 | 4 | // Example: 5 | // arr1 = {2,1,2,5,7,1,9,3,6,8,8} 6 | // arr2 = {2,1,8,3} 7 | 8 | // Making map of array 1 (will get stored in sorted order) 9 | // 1 -> 2 10 | // 2 -> 2 11 | // 3 -> 1 12 | // 4 -> 1 13 | // 5 -> 1 14 | // 6 -> 1 15 | // 7 -> 1 16 | // 8 -> 2 17 | // 9 -> 1 18 | 19 | vector relativeSortArray(vector& arr1, vector& arr2) { 20 | vector ans; 21 | 22 | map mp; 23 | for(int i=0; i0){ 29 | ans.push_back(arr2[i]); 30 | mp[arr2[i]]--; 31 | } 32 | } 33 | 34 | for(int i=0; i<=1000; i++){ 35 | while(mp[i]>0){ // mp[500] is non zero means there is an element 500 present 36 | ans.push_back(i); 37 | mp[i]--; 38 | } 39 | } 40 | return ans; 41 | } 42 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/Hashing/8 sortArrayByIncreasingFrequency.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sort-array-by-increasing-frequency/ 2 | 3 | // nums = [1,1,2,2,2,3] 4 | // UMAP: 5 | // 1 -> 2 6 | // 2 -> 3 7 | // 3 -> 1 8 | 9 | // Lambda Function in C++ 10 | // https://www.geeksforgeeks.org/lambda-expression-in-c/ 11 | 12 | // [&](int a, intb){return Expression} 13 | // [&](parameters){return Expression} 14 | 15 | // Using lambda function during the sort, it will specify how to sort 16 | // 1) If two numbers have different frequency, smaller goes first. 17 | // 2) If two numbers have same frequency, greater goes first. 18 | 19 | vector frequencySort(vector& nums) { 20 | vector ans; 21 | unordered_map umap; 22 | for(auto x: nums){ 23 | umap[x]++; 24 | } 25 | 26 | sort(nums.begin(), nums.end(), [&](int a, int b){ 27 | return umap[a] != umap[b] ? umap[a]b; // if frequency is different sort fun is defined acc to value, else by key 28 | }); 29 | 30 | return nums; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/Hashing/9 customSortString.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/custom-sort-string/ 2 | 3 | // order= "cba" 4 | // s = "abcd" 5 | // Output = "cbad" 6 | // a->1 7 | // b->1 8 | // c->1 9 | // d->1 10 | 11 | string customSortString(string order, string s) { 12 | map mp; 13 | string ans = ""; 14 | 15 | for(auto x: s){ 16 | mp[x]++; 17 | } 18 | for(auto x: order){ 19 | if(mp.find(x)!=mp.end()){ 20 | auto temp = mp.find(x); 21 | int count = temp->second; // c -> 5 ,, ccccc 22 | 23 | // for(int i=0;i first; 13 | deque dq(10); // deque of 10 elements 14 | deque second(4,100); // 100 100 100 100 15 | deque third(second.begin(), second.end()); // iterating over second 16 | deque fourth(third); // copy of third 17 | 18 | 19 | 20 | #include 21 | using namespace std; 22 | 23 | -------------------------------------------------------------------------------- /0a (STL & Time Complexity)/queue.cpp: -------------------------------------------------------------------------------- 1 | // FIFO 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main(){ 8 | queue q; 9 | 10 | q.push(1); 11 | q.push(2); 12 | q.push(3); 13 | 14 | while(!q.empty()){ 15 | cout< 14 | #include 15 | using namespace std; 16 | 17 | int main(){ 18 | stack books; 19 | 20 | books.push("Learn C++"); 21 | books.push("Learn JAVA"); 22 | books.push("Learn Python"); 23 | 24 | while(!books.empty()){ 25 | cout<0; i-=(i&-i)){ 13 | ans += bit[i]; 14 | } 15 | return ans; 16 | } 17 | 18 | // everytime we are removing a bit, so from a no we can remove max log(i) bits 19 | // Time complexity is O(logn) 20 | 21 | // Sum of l to r => sum(r) - sum(l-1) 22 | 23 | // Adding a value x in ith index not replacing it 24 | // For replacing call update(i, x-a[i]); // ie add the difference ie u want to replace 4 with 6 which is same as adding 2 25 | 26 | void update(int i, int x){ 27 | for( ; i<=N; i+=(i&(-i))){ 28 | bit[i]+=x; 29 | } 30 | } 31 | 32 | // Practice Problems 33 | // https://youtu.be/NOykDuH1_OY 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /0b (Range Queries)/segmentTree.cpp: -------------------------------------------------------------------------------- 1 | // https://www.youtube.com/playlist?list=PL2q4fbVm1Ik6v2-emg_JGcC9v2v2YTbvq 2 | 3 | 4 | -------------------------------------------------------------------------------- /0b (Range Queries)/staticArrayQueries.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/array-data-structure/array-range-queries/ 2 | -------------------------------------------------------------------------------- /0c (Bit Manipulation)/XorQueriesOnSubarray.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/xor-queries-of-a-subarray/ 2 | 3 | // Given an array of integers and Q queries 4 | // To find XOR of elements from index L to R in every query 5 | 6 | // TC = O(1) 7 | 8 | // Approach 9 | // Creating a prefix array 10 | // Sample array : [1, 3, 4, 8] 11 | // prefix[i] = A0^A1^A2^A3...^Ai 12 | // prefix = [1, 2, 6, 14] 13 | 14 | // After this preprocessing 15 | // Ans of each query L, R -> prefix[R] ^ prefix[L-1] ; if L > 0 16 | // prefix[R] ; if L = 0 17 | 18 | // Proof:- prefix[R] ^ prefix[L-1] = (A0^A1^A2...^AL...^AR)^(A0^A1^...AL-1) // the same terms will become 0, using 2 properties 19 | // = AL^AL+1^...^AR = XOR from index L to R 20 | 21 | 22 | -------------------------------------------------------------------------------- /0c (Bit Manipulation)/countingBits.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/counting-bits/ 2 | 3 | // for loop over a set of elements and returning no of set bits in them 4 | 5 | // n&(n-1) removes the last set bit 6 | -------------------------------------------------------------------------------- /0c (Bit Manipulation)/isPowerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/power-of-two/ 2 | 3 | // Method 1 4 | // To check if an integer is power of 2 or not is to count the number of set bits which should be equal to 1 5 | 6 | bool isPowerOfTwo(int n) { 7 | 8 | if(n<=0) return false; // leetcode doesn't provided constraints on n, so we needed to write this else error. 9 | int cnt = 0; 10 | 11 | while(n){ 12 | cnt++; 13 | 14 | n = n&(n-1); 15 | } 16 | return cnt==1 17 | } 18 | 19 | /// OR /// 20 | bool isPowerOfTwo(int n) { 21 | 22 | if(n<=0) return false; // leetcode doesn't provided constraints on n, so we needed to write this else error. 23 | 24 | return (n&(n-1)==0); // coz it removes the last set bit, if there is only 1 set bit then it will be removed and become = 0 25 | } 26 | -------------------------------------------------------------------------------- /0c (Bit Manipulation)/minNoOfFlipsToMakeAorBequalC.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ 2 | 3 | // concept of ith bit is set or not is used 4 | 5 | // I have to traverse the 32 bits and calculate flips for every bit 6 | 7 | 8 | -------------------------------------------------------------------------------- /0c (Bit Manipulation)/noOfOnes.cpp: -------------------------------------------------------------------------------- 1 | // COUNTING NUMBER OF SET BITS 2 | // https://leetcode.com/problems/number-of-1-bits/ 3 | // N = 12(1100) : Output = 2 4 | // N = 13(1101) : Output = 3 5 | // Method 1 6 | // We will perform right shift and & operation with 1 to check for no of set bits 7 | // N&1 -> 00001100 & 00000001 = 0 ie 0th place doesnt has 1, then we right shift by 1 and again do & operation 8 | // TC = O(logn) 9 | 10 | cin>>n; 11 | int cnt = 0; 12 | while(n>0){ 13 | if((n&1)>0) cnt++; 14 | 15 | n = n>>1; 16 | } 17 | cout<>n; 21 | int cnt = 0; 22 | while(n>0){ // runs as many times as there are set bits 23 | cnt++; 24 | 25 | n = n&(n-1); // in this operation we are removing the righmost set bit 26 | } 27 | return cnt; -------------------------------------------------------------------------------- /0c (Bit Manipulation)/sansaAndXOR.cpp: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/sansa-and-xor/problem 2 | 3 | // arr = [3, 4, 5] 4 | // Sansa has an array. She wants to find the value obtained by XOR-ing the contiguous subarrays, 5 | // followed by XOR-ing the values thus obtained. Determine this value. 6 | 7 | // (3)^(4)^(5)^(3^4)^(4^5)^(3^4^5) = 6 ans 8 | 9 | // Always think in terms of ODD & EVEN while working with XOR (very imp) 10 | // Frequency of an element is odd then resultant of their XOR will be that element only 11 | // if even times then 0 12 | // Here, 3 appears 3 times in subarrays (odd) 13 | // Here, 4 appears 4 times in subarrays (even) 14 | // Here, 5 appears 3 times in subarrays (odd) 15 | 16 | // hence, net is 3^5 = 6 ans 17 | 18 | // Formula 19 | // No of subarrays ith element(i = index+1) appears in = (i)*(n-i+1) // derived using permutation and computation 20 | 21 | int main() 22 | { 23 | lli t , n; 24 | cin>>t; 25 | while(t--) 26 | { 27 | cin>>n; 28 | for(int i=0; i>ar[i]; 29 | 30 | lli cnt; 31 | lli res = 0; 32 | for(lli i=1;i<=n;i++) 33 | { 34 | cnt = (i) * (n - i + 1); // 1 based indexing is used here 35 | if(cnt % 2) res ^= ar[i]; // if the count of that no is odd then it will appear in XOR 36 | } 37 | 38 | cout< arr) { 47 | 48 | int k=arr.size(); 49 | if(k%2==0) return 0; 50 | 51 | int res=0; 52 | 53 | for(int i=0;i= negThresh: 24 | // return ~(ans ^ mask) 25 | 26 | // else: 27 | // return ans -------------------------------------------------------------------------------- /10 (Greedy)/02) gasStation.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/gas-station/description/ 2 | 3 | Invalid movement: 4 | Fuel in the tank < Distance or cost required to move. 5 | Gas[i] < Cost[i] then that indexes we cannot start from ie not our ans. 6 | 7 | https://youtu.be/xmJZSYSvgfE 8 | 9 | class Solution { 10 | public: 11 | int canCompleteCircuit(vector& gas, vector& cost) { 12 | int n = gas.size(); 13 | int total_surplus = 0; 14 | int cur_surplus = 0; 15 | int position = 0; 16 | 17 | for(int i=0; i=0 then position else -1 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /10 (Greedy)/Greedy.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/discuss/study-guide/669996/greedy-for-beginners-problems-sample-solutions 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /10 (Greedy)/activitySelectionProblem.cpp: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/activity-selection-problem-greedy-algo-1/ 2 | 3 | // If the rewards are different then it is a DP problem. 4 | 5 | -------------------------------------------------------------------------------- /10 (Greedy)/fractionalKnapsack.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shashwat0105/CPP-Data-Structures-and-Algorithms/9d6621248c4c15fa32267527761f1b5a59cfbfb4/10 (Greedy)/fractionalKnapsack.cpp -------------------------------------------------------------------------------- /11 (Dynamic Programming)/1 unbounded knapsack or DP on subsequence(Classical Pattern)/6) formLargestIntegerWithDigitsThatAddUpToGivenTarget.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/ 2 | 3 | // Soln: 4 | https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/discuss/654490/dp-is-easy-5-step-dp-thinking-process-explained 5 | 6 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/2 longest Common Subsequence or DP on strings/10) minimumNoOfDeletionMakeStringPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome/ 2 | 3 | // Given a string of size ‘n’. The task is to remove or delete minimum number of characters from the string so that the resultant string is palindrome. 4 | // Input : aebcbda 5 | // Output : 2 6 | // Remove characters 'e' and 'd' 7 | // Resultant string will be 'abcba' which is a palindromic string 8 | 9 | // minimum is asked hence DP ques 10 | // Length of palindromic subsequence is inversely proportional to no. of deletion 11 | 12 | // Hence, Longest palindromic subsequence will give min no of deletion 13 | // ie :- "abcba" was nothing but LPS 14 | // Hence :- min no of deletion = Length of string - LPS 15 | // = Length of string - LCS(x, reverse(x)) 16 | 17 | // Ques is nothing but, to calculate min no of deletion to get longest palindromic subsequence. 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/2 longest Common Subsequence or DP on strings/11) minimumNoOfInsertionMakeStringPalindrome.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ 2 | https://www.geeksforgeeks.org/minimum-insertions-to-form-a-palindrome-dp-28/ 3 | 4 | // Idea is to keep the "longest" palindrome portion of the string intact. 5 | 6 | // Similar to min no of deletion ques (give 2 min to think if u have any similar ques before) 7 | 8 | // I/P : x = "aebcbda" 9 | 10 | // In aebcbda , "ed" is disturbing! 11 | // So, to make a palindrome we can either delete e, d or insert e, d and make it's pair 12 | 13 | Hence, No of insertions = No. of deletions.(LOL) = Length of string - LPS 14 | 15 | **** 16 | 17 | class Solution { 18 | public: 19 | int LCS(string x, string y){ 20 | int m = x.size(); 21 | int n = y.size(); 22 | int t[1001][1001]; 23 | 24 | for(int i=0; i<=m; ++i) t[i][0] = 0; 25 | for(int j=0; j<=n; ++j) t[0][j] = 0; 26 | 27 | for(int i=1; i<=m; ++i){ 28 | for(int j=1; j<=n; ++j){ 29 | if(x[i-1] == y[j-1]){ 30 | t[i][j] = 1+ t[i-1][j-1]; 31 | } 32 | else{ 33 | t[i][j] = max(t[i-1][j], t[i][j-1]); 34 | } 35 | } 36 | } 37 | return t[m][n]; 38 | } 39 | 40 | int minInsertions(string str) { 41 | int n = str.size(); 42 | string x = str; 43 | reverse(str.begin(), str.end()); 44 | return n - LCS(x, str); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/2 longest Common Subsequence or DP on strings/9) longestPalindromSubstring.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-palindromic-substring/ 2 | 3 | // Longest common substring 4 | // VERIFY the below sentences 5 | // Like Longest Common Subsequence is to Longest Palindromic Subsequence, It is Longest Common Substring to Longest Palindromic Substring 6 | // Sorry, above approach will fail for "abcdba" 7 | // Longest palindromic substring is something you cant solve by the stuff I taught you. (aditya verma) 8 | // I think the 27th video was "Longest Palindromic Substring". It looks like an LCS variation. But there is one case where LCS fails in that problem and gives wrong answer. 9 | // We could see that the lcs method fails when there exists a reversed copy of a non-palindromic substring in some other part of String 10 | 11 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/3 MCM(Matrix Chain Multiplication), Partition DP (Classical Pattern)/5) eggDroppingProblem.cpp: -------------------------------------------------------------------------------- 1 | // Abhi karna hai yeh... 2 | 3 | // Aditya verma ki 3 videos hai 4 | // Other YT 5 | 6 | // Leetcode 7 | 8 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/3 MCM(Matrix Chain Multiplication), Partition DP (Classical Pattern)/minimumDifficultyOfJobSchedule.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/ 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/3 MCM(Matrix Chain Multiplication), Partition DP (Classical Pattern)/minimumScoreTriangulationOfPolygon.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/minimum-score-triangulation-of-polygon/ 2 | 3 | Medium-Hard 4 | 5 | https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/1515627/Problem-Pattern-or-Matrix-Chain-Multiplication 6 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/3 MCM(Matrix Chain Multiplication), Partition DP (Classical Pattern)/superEggDrop.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/super-egg-drop/ 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/4 Fibonacci Sequence/00) fibonacci.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/fibonacci-number/ 2 | 3 | Tabulation , TC and SC = O(N) 4 | 5 | class Solution { 6 | public: 7 | int fib(int n) { 8 | 9 | int f[n+2]; 10 | f[0] = 0; 11 | f[1] = 1; 12 | 13 | for(int i=2; i<=n; i++){ 14 | f[i] = f[i-1] + f[i-2]; 15 | } 16 | return f[n]; 17 | } 18 | }; 19 | 20 | Space optimised using two variables 21 | TC = O(N), SC = O(1) 22 | 23 | class Solution { 24 | public: 25 | int fib(int n) { 26 | 27 | if(n<=1) return n; 28 | 29 | int prev2 = 0; 30 | int prev = 1; 31 | 32 | for(int i=2; i<=n; i++){ 33 | int curi = prev + prev2; 34 | prev2 = prev; 35 | prev = curi; 36 | } 37 | return prev; 38 | } 39 | }; 40 | 41 | // Matrix Exponentiation 42 | TC = O(logn) 43 | 44 | Used to find large fibonacci numbers. 45 | 46 | https://www.youtube.com/results?search_query=matrix+exponentiation+fibonacci 47 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/4 Fibonacci Sequence/04) frogJumpLeetcode.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/frog-jump/ 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/4 Fibonacci Sequence/06) houseRobberII.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/house-robber-ii/ 2 | 3 | First n last are also adjacent 4 | 5 | Remove the last element and solve as previous ques 6 | Remove the first element and solve as previous ques 7 | Take the max, as both cannot come in our ans together. 8 | 9 | // CODE 10 | 11 | class Solution { 12 | public: 13 | int solve(vector &nums){ 14 | int n = nums.size(); 15 | int prev = nums[0]; // because If u are standing at i=0 then better u pick it as all values are +ve 16 | int prev2 = 0; // index < 0 17 | for(int i=1; i1) pick += prev2; 20 | int notPick = 0 + prev; 21 | int curi = max(pick, notPick); 22 | prev2 = prev; 23 | prev = curi; 24 | } 25 | return prev; 26 | } 27 | 28 | int rob(vector& nums) { 29 | if(nums.size()==1) return nums[0]; // edge case 30 | vector temp1, temp2; 31 | int n = nums.size(); 32 | for(int i=0; i& nums) { 7 | int n = nums.size(); 8 | int farthest = 0; 9 | 10 | for(int i=0; i=n-1; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/6 DP on trees/5) diameterOfN-AryTree.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/diameter-n-ary-tree/ 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/7 Digit DP/01) boringNumbers.cpp: -------------------------------------------------------------------------------- 1 | https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ff49/000000000043b0c6#problem 2 | 3 | https://youtu.be/2yAEj-0A8bk 4 | 5 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/7 Digit DP/02) digitSumSPOJ.cpp: -------------------------------------------------------------------------------- 1 | https://www.spoj.com/problems/PR003004/ 2 | 3 | https://youtu.be/H6OCV7qcZoQ 4 | 5 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/7 Digit DP/03) encoding.cpp: -------------------------------------------------------------------------------- 1 | https://youtu.be/B7ZWUBfaIq0 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/7 Digit DP/04) countingNumbers.cpp: -------------------------------------------------------------------------------- 1 | https://youtu.be/lD_irvBkeOk 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/7 Digit DP/digitDpTheory.cpp: -------------------------------------------------------------------------------- 1 | https://youtu.be/heUFId6Qd1A 2 | 3 | Basically used to find count of numbers in a range [L, R] whose sum of digits is some X. 4 | 5 | https://www.youtube.com/results?search_query=digit+dynamic+programming 6 | 7 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/8 BitMask DP/03) findTheShortestSuperstring.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/find-the-shortest-superstring 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/8 BitMask DP/bitmasking.cpp: -------------------------------------------------------------------------------- 1 | Example: 2 | s = {1, 5} 3 | This s can be represented as just 17 coz: [0 0 0 ... 0 1 0 0 0 1] in binary. 4 | 5 | 6 | // Example: 7 | Given a set represented as a bitmask. 8 | Implement: 9 | 1) adding element to set 10 | 2) removing element from set 11 | 3) display elements of the set. 12 | 13 | // 14 | void add(int &subset, int x){ 15 | subset = (subset ^ (1<< (x-1))); 16 | } 17 | 18 | void remove(int &subset, int x){ // I want to turn that bit to zero. 19 | // assuming x is not in the subset 20 | subset = (subset ^ (1<< (x-1))); // becoz i is represented by i-1th bit. XOR does the work. Rest bits stay the same 21 | } 22 | 23 | void display(int subset){ 24 | for(int bit_no = 0; bit_no <= 9; bit_no++){ // assuming the range is between 0 and 9 25 | if(subset & (1 << bit_no)){ // And with 2^i to check if that partcular bit is set or not 26 | cout<nums){ 17 | // code 18 | int n = nums.size(); 19 | 20 | vector dp1(n, 1); 21 | for(int i=0; i dp1[i]){ 24 | dp1[i] = 1 + dp1[prev]; 25 | } 26 | } 27 | } 28 | 29 | vector dp2(n, 1); 30 | for(int i=n-1; i>=0; --i){ 31 | for(int prev = n-1; prev>i; --prev){ 32 | if(nums[prev] dp2[i]){ 33 | dp2[i] = 1 + dp2[prev]; 34 | } 35 | } 36 | } 37 | 38 | int maxi=0; 39 | for(int i=0; i& nums) { 11 | int n = nums.size(); 12 | vector dp(n, 1), cnt(n, 1); 13 | int maxi=1; 14 | for(int i=0; idp[i]){ 17 | dp[i] = 1 + dp[prev]; 18 | cnt[i] = cnt[prev]; // inherit the same 19 | } 20 | else if(nums[prev] >& matrix) { 14 | int n = matrix.size(); 15 | int m = matrix[0].size(); 16 | vector> dp(n+1, vector (m+1, 0)); // create a dp table 17 | for(int i=0; i& prices) { 13 | int minPrice = INT_MAX; // = prices[0] as there is 1 element for sure // this variable is acting as a memo 14 | int profit = 0; 15 | int n = prices.size(); 16 | for(int i=0; i= 1; machine_no--){ 26 | go[machine_no][1] = t[machine_no][1] + min(go[machine_no + 1][1], shift[i][2] + go[machine_no + 1][2]); 27 | go[machine_no][2] = t[machine_no][2] + min(go[machine_no + 1][2], shift[i][1] + go[machine_no + 1][1]); 28 | } 29 | return min(e1 + go[1][1], e2 + go[1][2]); 30 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/longestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/longest-increasing-subsequence/ 2 | 3 | // Classical Problem!! (LIS) 4 | 5 | // Till date the best discuss I guess 6 | https://leetcode.com/problems/longest-increasing-subsequence/discuss/1326552/Optimization-From-Brute-Force-to-Dynamic-Programming-Explained! 7 | 8 | 9 | // Kartik Arora (Other than binary search solution is there too) 10 | https://youtu.be/wqLwv7E1GF0 11 | 12 | // Striver has also taught this. 13 | 14 | 15 | // Recursive 16 | // Take, Not take // traversing from back 17 | class Solution { 18 | public: 19 | int util( vector nums, int index, int cv){ // cv is current min value 20 | // end condition 21 | if( index == 0 ){ // if( index < 0 ) return 0; // Alternate base condition 22 | if( nums[index] < cv ) return 1; 23 | else return 0; 24 | } 25 | 26 | // logic 27 | int q1 = 0, q2 = 0; 28 | if( nums[index] < cv ){ 29 | q1 = 1 + util(nums, index-1, nums[index]); 30 | } 31 | q2 = util( nums, index-1, cv); 32 | return max(q1, q2); 33 | } 34 | int lengthOfLIS(vector& nums) { 35 | return util(nums,nums.size()-1, INT_MAX); 36 | } 37 | }; 38 | 39 | // DP 40 | 41 | dp[i] denotes the LIS ending at index i 42 | 43 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/perfectSquares.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/perfect-squares/ 2 | 3 | dp[i] = minimum number of numbers to subtract from i to reach 0. 4 | 5 | dp[n] // our final answer 6 | dp[0] = 0; 7 | 8 | // code 9 | 10 | class Solution { 11 | public: 12 | int numSquares(int n) { 13 | vector dp(n+1); 14 | 15 | dp[0] = 0; 16 | 17 | for(int i=1; i<=n; ++i){ 18 | int ans = (1<<30); // infinity 19 | for(int j = 1; j*j <= i; ++j){ 20 | ans = min(ans, 1+dp[i - j*j]); 21 | } 22 | dp[i] = ans; 23 | } 24 | return dp[n]; 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/removeBoxes.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-boxes/ 2 | 3 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/strangePrinter.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/strange-printer/ 2 | 3 | Strange Printers problem is same as remove boxes. We need to remove consecutive subsequences 4 | 5 | 6 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/twoKeysKeyboard.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/2-keys-keyboard/ 2 | 3 | (i, j) means i is on screen and j is on the clipboard. 4 | (i, j) press copy => (i, i) 5 | (i, j) press paste => (i+j, j) 6 | 7 | // At any state we will have two options that are: 8 | Paste copy value with current value => 1 step 9 | Copy current value and then paste it with itself => 2 step // Note copy alone cannot be performed coz infinite loop will be there/ 10 | 11 | dp(i, j) : minimum number of steps to reach exactly N A's on screen. 12 | Given that i A's on screen and j A's on clipboard. 13 | 14 | ******************************************************** 15 | 16 | #define INF (1<<30) 17 | class Solution { 18 | public: 19 | int count(int i, int j, int n, vector> &dp){ 20 | if(i>n) return INF; 21 | if(i==n) return 0; 22 | 23 | if(dp[i][j]) return dp[i][j]; 24 | 25 | int op1 = 2 + count(i+i, i, n, dp); // copy and paste 26 | int op2 = 1 + count(i+j, j, n, dp); // paste 27 | 28 | return dp[i][j] = min({op1, op2}); 29 | } 30 | 31 | int minSteps(int n) { 32 | vector> dp(n+1, vector(n+1, 0)); // dp[n+1][n+1] 33 | return n > 1 ? 1 + count(1, 1, n, dp) : 0; 34 | } 35 | }; 36 | 37 | // Method 2 38 | 39 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/twoPersonTraversalOfSequenceOfCities.cpp: -------------------------------------------------------------------------------- 1 | You are given an ordered sequence of n cities, and the distances between every pair of cities. 2 | You must partition the cities into two subsequences (not necessarily contiguous) such that person A visits all cities in the first subsequence (in order), 3 | person B visits all cities in the second subsequence (in order), and such that the sum of the total distances travelled by A and B is minimized. 4 | Assume that person A and person B start initially at the first city in their respective subsequences. 5 | 6 | https://leetcode.com/discuss/interview-question/1979807/Most-Frequently-Asked-Dynamic-Programming-Questions-or-Practice-Well 7 | 8 | http://courses.csail.mit.edu/6.006/fall10/handouts/dpproblems-sol.pdf 9 | 10 | -------------------------------------------------------------------------------- /11 (Dynamic Programming)/Practice Problems/wordBreak.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/word-break/ 2 | 3 | YET TO UNDERSTAND DHANG SE 4 | https://www.youtube.com/results?sp=mAEB&search_query=word+break 5 | 6 | class Solution { 7 | public: 8 | bool wordBreak(string s, vector& wordDict) { 9 | int n = s.length(); 10 | int dp[n+1]; 11 | memset(dp, 0, sizeof dp); 12 | dp[n] = 1; 13 | 14 | unordered_set dict; 15 | for(string &word: wordDict){ 16 | dict.insert(word); 17 | } 18 | 19 | // dp[i] 20 | for(int i=n; i>=0; --i){ 21 | string word; 22 | for(int j=i; j 6 | using namespace std; 7 | 8 | int numOfCuts(int w, int h) { 9 | int dp[w+1][h+1]; 10 | for(int i=0; i>w>>h; 34 | cout< 10 | using namespace std; 11 | 12 | int main() { 13 | int mod = 1e9+7; 14 | int n, Sum; 15 | cin >> n>> Sum; 16 | vector coin(n); 17 | for(int i=0; i>coin[i]; 19 | } 20 | 21 | vector> t(n+1,vector(Sum+1,0)); 22 | 23 | for(int i=0; i<=n; i++) t[i][0]=1; 24 | 25 | for(int j=1; j<=Sum; j++) t[0][j]=0; 26 | 27 | for(int i = 1; i <= n; i++){ 28 | for(int j = 1; j <= Sum; j++){ 29 | if (coin[i - 1] <= j) 30 | t[i][j] = (t[i][j - coin[i - 1]] + t[i - 1][j])%mod; 31 | else 32 | t[i][j] = t[i - 1][j]; 33 | } 34 | } 35 | 36 | cout << t[n][Sum] << endl; 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /12 (CSES Solutions)/Dynamic Programming/4) removingDigits.cpp: -------------------------------------------------------------------------------- 1 | https://cses.fi/problemset/task/1637 2 | 3 | // Jo number subtract hoke banega fr uski digits use karni hogi. 4 | 5 | // dp(i) will store min number of steps to go from i to 0 (DP State) 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | int mod = 1e9+7; 12 | int n; 13 | cin >> n; 14 | 15 | vector dp(n+1); 16 | dp[0] = 0; 17 | for(int i=1; i<=n; ++i){ 18 | int temp = i; 19 | int minSteps = 1e6+2; 20 | while(temp!=0){ 21 | int di = temp%10; 22 | temp /= 10; 23 | if(di==0) continue; 24 | minSteps = min(minSteps, 1+ dp[i-di]); 25 | } 26 | dp[i] = minSteps; 27 | } 28 | 29 | cout< 34 | using namespace std; 35 | 36 | int main() { 37 | int n; 38 | cin >> n; 39 | vector dp(n+1,1e9); 40 | dp[0] = 0; 41 | for (int i = 0; i <= n; i++) { 42 | for (char c : to_string(i)) { 43 | dp[i] = min(dp[i], dp[i-(c-'0')]+1); 44 | } 45 | } 46 | cout << dp[n] << endl; 47 | } 48 | 49 | 50 | 51 | // Another soln 52 | // Note that the greedy solution of always subtracting the maximum digit is also correct, but we are practicing DP :) 53 | 54 | int minSteps(int n){ 55 | int res = 0; 56 | while (n != 0){ 57 | res++; 58 | int t = n, m = 0; 59 | while(t != 0){ 60 | m = Math.max(m, t%10); 61 | t/=10; 62 | } 63 | n -= m; 64 | } 65 | return res; 66 | } 67 | -------------------------------------------------------------------------------- /12 (CSES Solutions)/Dynamic Programming/5) bookShop.cpp: -------------------------------------------------------------------------------- 1 | https://cses.fi/problemset/task/1158 2 | 3 | // Tight Constraints. 4 | 5 | // This is a case of the classical problem called 0-1 knapsack. 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | //int mod = 1e9+7; 12 | int n, x; 13 | cin >> n >> x; 14 | vector price(n+1), pages(n+1); 15 | 16 | for(int i=0; i> price[i]; 17 | for(int i=0; i> pages[i]; 18 | 19 | int dp[n+1][x+1]; 20 | 21 | for(int i=0; i<=n; ++i) dp[i][0]=0; 22 | for(int money=0; money<=x; ++money) dp[0][money]=0; 23 | 24 | for(int i=1; i<=n; ++i){ 25 | for(int money=0; money<=x; ++money){ // Using i numbers and "money" in hand solving the subproblems. 26 | if(price[i-1]<=money){ 27 | dp[i][money] = max(pages[i-1]+ dp[i-1][money-price[i-1]], dp[i-1][money]); 28 | } 29 | else{ 30 | dp[i][money] = dp[i-1][money]; 31 | } 32 | } 33 | } 34 | 35 | cout< 7 | using namespace std; 8 | 9 | int main() { 10 | int mod = 1e9+7; 11 | int n, target; 12 | cin >> n>> target; 13 | vector coin(n); 14 | for(int i=0; i>coin[i]; 16 | } 17 | vector dp(target+1,0); 18 | dp[0] = 1; 19 | for (int i = 1; i <= target; i++){ 20 | for(auto x: coin){ // In dice there was 1 to 6, here it is in form of an array. 21 | if(i-x>=0) dp[i] = (dp[i]+dp[i-x])%mod; 22 | } 23 | } 24 | cout << dp[target] << endl; 25 | } 26 | 27 | // 28 | SC = O(X) 29 | TC = O(NX) 30 | -------------------------------------------------------------------------------- /12 (CSES Solutions)/Dynamic Programming/9) longestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | https://cses.fi/problemset/task/1145 2 | 3 | // Classical Problem!! (LIS) 4 | 5 | // In ques that ask to find required subsequence or subarrays. 6 | 7 | // Standard way of thinking: What is best possible subarray that ends at ith element of the array. 8 | 9 | 10 | // Kartik Arora (Other than binary search solution is there too) 11 | https://youtu.be/wqLwv7E1GF0 12 | 13 | // O(N^2) solution 14 | 15 | DP State: 16 | 17 | dp(i) = length of the longest increasing subsequence ending at ith element of the array. 18 | Ans = max dp(i) , for every i = 1 to N 19 | 20 | // How will we evaluate length of the longest increasing subsequence ending at ith element 21 | 22 | dp(i) = 1 + max(dp[j]) 23 | j should be valid means: 1) j 29 | using namespace std; 30 | 31 | int lengthOfLIS(vector& A) { 32 | int len = 0; 33 | for(auto cur : A) 34 | if(len == 0 || A[len-1] < cur) A[len++] = cur; // extend 35 | else *lower_bound(begin(A), begin(A) + len, cur) = cur; // replace 36 | return len; 37 | } 38 | 39 | int main() { 40 | // your code goes here 41 | int n; 42 | cin>>n; 43 | vector A(n); 44 | for(int i=0; i>A[i]; 46 | } 47 | cout<