├── .vscode ├── c_cpp_properties.json └── settings.json ├── 001 Array and Math ├── A1 Rain water trapped.ipynb ├── A2 Maximum Absolute Difference.ipynb ├── A3 Maximum Consecutive Gap.ipynb ├── A3 maxConsecutiveGap.cpp ├── A4 Carotenemia.ipynb ├── HW1 Set Matrix Zeroes.ipynb ├── HW2 Spiral Order Matrix.ipynb ├── HW3 next Permutation.ipynb ├── HW4 Reading Newspaper.ipynb └── README.md ├── 002 Array 2 ├── A1 Rearrange the array.ipynb ├── A2 Sub-matrix Sum Queries.ipynb ├── A3 Sum of All Submatrices.ipynb ├── A4 Search in a Sorted matrix.ipynb ├── HW1 Merge Intervals .ipynb ├── HW2 Wave Array.ipynb ├── HW3 FizzBuzz.ipynb ├── HW4 Max Chunks to Make Sorted II.ipynb ├── HW5 Min operations to make all elements of a matrix equal.ipynb ├── HW6_mergeOverlappingIntervals.py └── README.md ├── 003 Math 1 GCD ├── A1 GCD.ipynb ├── A2 Divisor Game.ipynb ├── A3 Delete Elements.ipynb ├── A4 Delete One.ipynb ├── A5 Pubg.ipynb ├── HW1 Repeated Subtraction.ipynb ├── HW2 Enumerating GCD.ipynb ├── HW3 Finding Position.ipynb ├── HW4 Overlap Rectangles.ipynb ├── HW5 Solve sub-sequences and return OR.ipynb ├── Notes.ipynb ├── Practice notes.ipynb └── README.md ├── 004 Math 2 Prime ├── A1 Lucky Numbers.ipynb ├── A1_lucky.cpp ├── A2 Prime Factors.ipynb ├── A3 Open doors.ipynb ├── A4 Count of divisors for multiple queries.ipynb ├── HW1 Trailing Zeroes.ipynb ├── HW2 Prime Sum.ipynb ├── HW3 Largest Coprime Divisor.ipynb ├── HW4 Coprime Again.ipynb ├── HW5 Find nth magic number 5, 25, 30.ipynb ├── Notes.ipynb └── README.md ├── 005 Math 3 Mod ├── A1 Excel Column Tile.py ├── A2 Grid Unique paths.py ├── A3 Cut the chocolate.py ├── A4 To and Fro.py ├── A5 victory.cpp ├── HW! Excel Column Number.py ├── HW2 Reverse Integer.py ├── HW3 ncr % p.cpp ├── HW3 ncr%p.cpp ├── HW4 All GCD Pair.py ├── HW5 ncr % m.cpp ├── HW5 ncr % m1.cpp ├── HW6 rectangle Area.cpp ├── README.md ├── binomialCoefficient.cpp └── img │ ├── IMG_20200618_003533__01.jpg │ └── README.md ├── 006 Bit Manipulation ├── A1 Reverse Bits.ipynb ├── A2 Single Number.ipynb ├── A3 Single Number II.ipynb ├── A4 Min XOR.ipynb ├── HW1 Divide integer.ipynb ├── HW2 Different Bits Sum Pairwise.ipynb ├── HW2 diffBitsSumPairwise.cpp ├── HW3 XOR Queries.ipynb ├── HW4 Interesting Array.ipynb └── README.md ├── 007 Searching 1 ├── A1 RotatedSortedArraySearch.py ├── A2 MatrixMedian.py ├── A3 AllTwiceExceptOnce.py ├── A4 PeakElement.py ├── HW1 MatrixSearch.py ├── HW2 MaxStairCaseHeight.py ├── HW3 SpecialInteger.py └── README.md ├── 008 Searching 2 ├── A1 AllocateBooks.py ├── A2 MatrixMedian.cpp ├── A3 AggressiveCows.cpp ├── A4 SmallestGoodBase.py ├── HW1 MatrixSearch.py ├── HW2 SquareRoot.py ├── HW3 PaintersPartition.py └── README.md ├── 009 Recursion ├── A1 UniquePermutations.cpp ├── A2 permutations.py ├── A3 Subset.cpp ├── HW1 CombinationSum2.cpp ├── HW1 [opt2] CombinationSum2.cpp ├── HW1 [opt3] CombinationSum.cpp ├── HW1 [opt]CombinationSum2.cpp └── README.md ├── 010 Backtracking 1 ├── A1_nQueens.cpp ├── A4_grayCode.cpp └── README.md ├── 011 Backtracking 2 └── README.md ├── 012 Sorting 1 ├── A1 Merging Intervals.cpp ├── A2 Largest Number.cpp ├── A3 waveArray.cpp ├── A4_maxUnsortedSubarray1.cpp ├── A4_maximumUnsortedSubarray.cpp ├── A5_inversionCount.cpp ├── HW1 Merge two sorted LL.py ├── HW2 Triplets with Sum between given range.cpp ├── HW3 Sum the difference.cpp ├── HW4 Flight Range Bookings.cpp ├── README.md ├── Sorting Algorithms │ ├── bubble3Sort.cpp │ ├── bubbleSort.cpp │ ├── countSort.cpp │ ├── insertionSort.cpp │ └── selectionSort.cpp └── img │ ├── Horners method.JPG │ ├── README.md │ ├── Sum the difference 1.jpg │ ├── Sum the difference 2.jpg │ └── Sum the difference.jpg ├── 013 Sorting 2 ├── A1 SumtheDifference.py ├── A2 GameOfBottles.py ├── A4 MaximumAndMinimum.py ├── HW1 LargestNumber.py ├── HW3 Alternate+ve&-ve.cpp ├── HW4 MaxChunksToSorted.cpp ├── HW5 minSwaps2.cpp └── README.md ├── 014 Two Pointers ├── A1 3 Sum.cpp ├── A2 Container with Most Water.cpp ├── A3 CountPairsWithGivenSum.py ├── A5 anotherCountingProblem.cpp ├── A5 subArraywithgivenSum.cpp ├── HW1 array3Ptrs.cpp ├── Notes.cpp └── README.md ├── 015 Hashing 1 ├── A1 LongestConsecutiveSequence.py ├── A2 ShaggyAndDistances.py ├── A3 SubarrayWithZeroSum.py ├── A4 SortArrayAccToAnotherArray.py ├── HW1 WindowString.cpp ├── HW2 longestSubstrwoutRepeating.cpp ├── HW3 ColorfulNumber.cpp ├── HW4 Permutations.cpp ├── Notes.py ├── README.md ├── countTriangles.py ├── img │ ├── IMG_20200312_155622.jpg │ └── README.md └── lengthConsecutiveElements.py ├── 016 Hashing 2 ├── A1 Replicating Substring.py ├── A2 pointsOnSameLine.py ├── A3 Count Triangles.py ├── HW1 Anagrams.cpp ├── HW2 Equal.cpp ├── HW3 Compare Sorted Subarrays.py ├── HW3 CompareSortedSubarrays.cpp ├── PalindromicPairs.py └── README.md ├── 017 String Algorithm ├── A1 longestCommonPrefix.cpp ├── A2 reverseTheString.cpp ├── A3 reverseString.py ├── A4_boringSubstring.cpp ├── Atoi.cpp ├── HW1 makeStringPalindrome.cpp ├── HW2_smallestPrefixString.cpp ├── HW3 closestPalindrome.cpp ├── Notes.cpp ├── README.md ├── anagrams.cpp ├── isomorphic.cpp ├── reverseWordsInSentence.cpp └── rotateStringTwice.py ├── 018 Pattern Matching └── README.md ├── 019 Stack 1 ├── A1 Min Stack.cpp ├── A2 Sort Stack using another stack.cpp ├── A3 Order them.cpp ├── A4 Max Freq Stack.cpp ├── A4 maxFreqStack.cpp ├── HW! SimplifyDirectoryPath.py ├── HW2 PalindromeList.cpp ├── README.md ├── getMin.cpp ├── insertAtBootom.cpp ├── stackImplementation.cpp └── stackUsingSTL.cpp ├── 020 Stack 2 ├── A1 LargestAreainHistogram.cpp ├── A2 MaximumRectangle.cpp ├── A4 StackReverseUsingRecursion.cpp ├── HW1 EvaluateExpr.cpp ├── HW2 RedundantBraces.cpp ├── HW3 nearestSmallerEle.cpp ├── HW3 prevSmallerEle.cpp ├── HW4_kth_char_double_decrypted_string.cpp ├── README.md └── img │ ├── README.md │ ├── histogram.png │ └── histogram0.png ├── 021 Queue ├── A1GasStation.cpp ├── A2 reverse1stBnumQ.cpp ├── A3 N123.cpp ├── A4 Max&MinDiffWindow.cpp ├── CircularQueue.cpp ├── HW1 firstNonRepeatingChar.cpp ├── HW2 FirstNegativeInteger.cpp ├── QueueImplementation.cpp ├── README.md └── slidingWindowMaximum.cpp ├── 022 Linked List 1 ├── A1 ReorderList.cpp ├── A2 removeNthNodefromLast.cpp ├── A3 KreverseLL.cpp ├── A4 ImplementLL.cpp ├── A5 CloneLL.cpp ├── DoubleLL.cpp ├── HW1 ReverseInPairs.cpp ├── HW2 removeDuplicatesSorted1.cpp ├── HW3 middleNode.cpp ├── HW4 reverseLLRange.cpp ├── README.md ├── SingleLL.cpp ├── addLL.cpp ├── circularLL.cpp ├── reverseKGroups.cpp ├── reverseKgroups.cpp └── reverseLL.cpp ├── 023 Linked List 2 ├── A1 MergeTwoSortedLL.cpp ├── A2 IntersectionOfLL.cpp ├── A3 CloneLL.cpp ├── A4 FlattenLL.cpp ├── HW1 Remove Duplicates from Sorted List II.cpp ├── HW2 removeDuplicatesSorted1.cpp ├── HW3 longestPalindromicList.cpp ├── README.md ├── detectAndRemoveLoop.cpp └── firstRepeatedChar.cpp ├── 024 Trees 1 ├── A1 LevelOrder.cpp ├── A2 InorderTraversal.cpp ├── A3 InPost.cpp ├── A4 checkInPostPre.cpp ├── A5 verticalOrderTraversal.cpp ├── BT2DLL.cpp ├── ChildrenSumProperty.cpp ├── HW1 InPre.cpp ├── HW2 PreOrderTraversal.cpp ├── HW3 PostOrderTraversal.cpp ├── HW4 ZigZagLevelOrder.cpp ├── HW4 ZigZagLeverOrder1.cpp ├── HW4 ZigZagLeverOrder2.cpp ├── README.md ├── TreeImplementation.cpp ├── getHeight.cpp ├── getMax.cpp ├── getSize.cpp ├── inOrder.cpp ├── isBalanced.cpp ├── isBalancedOptimized.cpp ├── leftView.cpp ├── maxWidth.cpp ├── mirrorTraversal.cpp ├── nodesAtKDist.cpp ├── postOrder.cpp ├── preOrder.cpp ├── rightView.cpp ├── sumOfLeaves.cpp └── treeDiameter.cpp ├── 025 Trees 2 ├── A1 isBalancedBST.cpp ├── A1 isBalancedBT.cpp ├── A3 rightView.cpp ├── A4 TopView.cpp ├── A4 nextPointerBT.cpp ├── A5 diameter.cpp ├── HW1 isSymmetric.cpp ├── HW2 areIdentical.cpp ├── HW3 leftView.cpp ├── HW4 Odd&EvenLevelSumDifference.cpp └── README.md ├── 026 BST 1 └── HW4 BSTNodesinRange.cpp ├── 026 BST ├── A1 recoverBST.cpp ├── A2 validBST.cpp ├── A3 kthSmallest.cpp ├── A4 2-SumBinaryTree.cpp ├── A5 largestBSTsubtree.cpp ├── HW1 sortedArr2BST.cpp ├── HW2 checkBSToneChild.cpp ├── HW3 commonNodesin2BSTs.cpp ├── HW4 BSTnodesinRange.cpp └── README.md ├── 027 Problem On Trees ├── A2 BinaryTree2DLL.cpp ├── A3 invertTree.cpp ├── A4 EqualTreePartition.cpp ├── HW1 pathSum.cpp ├── HW2 flatterBT2LL.cpp ├── HW2 flatterBT2LL1.cpp ├── HW2 flatterBT2LL2.cpp ├── HW3 sumBT.cpp ├── README.md └── img │ ├── BT2DLL (1).jpg │ └── BT2DLL (2).jpg ├── 028 Tries ├── 01 TRIE_best.cpp ├── BinaryTree2dArray.cpp ├── R4_validPhoneDirectory.cpp ├── README.md ├── Remedial_15July │ └── contactFinder.cpp ├── Trie.cpp ├── Trie_implementation.cpp ├── TrieusingMAP.cpp └── img │ ├── IMG_20200512_224826.jpg │ └── README.md ├── 029 Segment Trees ├── README.md └── SegTreeImplementation.cpp ├── 030 Heaps 1 ├── A1 Magician&Chocolates.cpp ├── A2 ProductOf3.cpp ├── A3 ConnectRopes.cpp ├── A4 maxArrSumAfterBNegative.cpp ├── HW1 BthSmallestPrimeFraction.cpp ├── HW2 BptsClosertoOrogin.cpp ├── HW2 BptsClosest2Origin.cpp ├── HW2 BptsClosestOrigin.py ├── HW3 kSmallestEleinSortedMatrix.cpp ├── HW4 MishaAndCandies.cpp ├── PQArrayMax.cpp ├── PQArrayMin.cpp ├── README.md ├── heapImplementation.cpp ├── img │ ├── IMG_20200525_224809.jpg │ └── README.md ├── inbuiltmaxHeap.cpp └── inbuiltminHeap.cpp ├── 031 Heap 2 ├── A1 mergeKsortedLL.cpp ├── A2 ways2formMaxHeap.cpp ├── A3 AthLargestNo.cpp ├── A4 RunningMedian.cpp ├── HW1 NmaxPairCombination.cpp ├── HW4 minLargestEle.cpp ├── HW4 minLargestElement.cpp ├── README.md └── customHeap.cpp ├── 032 Greedy 1 ├── A1 DistributeCandies.cpp ├── A1 DistributeCandy.cpp ├── A2 Seats.cpp ├── A3 AssignMicetoHoles.cpp ├── A4 Bulbs.cpp ├── A5 CandiesInABox.cpp ├── HW1 StackingCubes.cpp ├── HW1 stackingCubes.cpp ├── HW2 ThsShipCompany.cpp ├── HW3 BinaryString.cpp ├── Hw4 AnotherCoinProblem.cpp └── README.md ├── 033 Greedy 2 ├── A1 Gas Station.cpp ├── A2 Delete Min and Max.cpp ├── A3 minJumpsArray.cpp └── README.md ├── 034 Dynamic Programming (1D DP) ├── A1 Stairs.cpp ├── A2 MaxwoutAdjEle.cpp ├── A3 minNumSquares.cpp ├── A4 LetsParty.cpp ├── A5 FibonacciNumber.cpp ├── A5 FibonacciNumber1.cpp ├── HW1 MaxProductSubArray.cpp ├── HW2_ways2Decode.cpp ├── HW3 LongestBalancedSubstring.cpp ├── HW4 MaximumSum.cpp ├── HW4 maximumSum1.cpp └── README.md ├── 035 Dynamic Programming 2 ├── A1 UniquePathGrid.cpp ├── A1 UniquePathGrid1.cpp ├── A1 UniquePathsGrid.cpp ├── A2 RegExpMatch.cpp ├── A2 RegularExpMatch.cpp ├── A3 minSumPath.cpp ├── A4 EditDistance.cpp ├── A5 LongestCommonSubsequence.cpp ├── A6 longestPalindromicSubsequence.cpp ├── HW1 DistinctSubsequences.cpp ├── HW2 ways3Decode.cpp ├── HW3 regularExpression2.cpp ├── HW4 letsParty.cpp ├── HW5 maxSum.cpp ├── HW6 oddPalindrome.cpp └── README.md ├── 036 Dynamic Programming 3 ├── A1 palindromePartitioning2.cpp ├── A2 coinSumInfinite.cpp ├── A2 palindrome partitioning 2.cpp ├── A3 subMatrixSumQueries.cpp ├── HW1 dungeonPrincess.cpp ├── HW2 repeatingSubsequence.cpp ├── HW3 lengthLongestFibonacciSubsequence.cpp └── README.md ├── 037 Dynamic Programming 4 ├── A2_minSumPathTriangle.cpp └── README.md ├── 038 Dynamic Programming 5 ├── A1 fipArray.cpp ├── A2 0-1 Knapsack.cpp └── README.md ├── 039 Dynamic Programming 6 ├── A1 maxSumPathBinaryTree.cpp ├── HW1 burstBalloons.cpp ├── HW2 arithmeticSubsequences.cpp └── README.md ├── 040 Dynamic Programming 7 ├── A1 scrambleString.cpp ├── A3 treeColoringwith3colors.cpp ├── A4 obsessiveString.cpp ├── HW2 LittlePonny&SubsetMedian.py └── README.md ├── 041 Dynamic Programming 8 ├── A2 treeColoringwith3colors.cpp ├── HW3 Repeating SubSequence.cpp └── README.md ├── 042 Dynamic Programming 9 ├── HW2 longestFibonacciSubsequence.cpp └── README.md ├── 043 Dynamic Programming Problems └── README.md ├── 044 Graphs 1 ├── A1 firstDFS.cpp ├── A2 noOfIslands.cpp ├── A3_anotherBFS.cpp ├── A4 pathInDirectedGraph.cpp ├── HW1_cloneGraph.cpp ├── HW2_BlackShapes.cpp ├── HW3_makeCircle.cpp ├── HW4_diameterofTree.cpp └── README.md ├── 045 Graphs 2 ├── A2_rottenOranges.cpp ├── A4 ColoringCyclicGraph.cpp └── README.md ├── 046 Graphs 3 ├── HW1 largestDistanceBWnodesTree.cpp └── README.md ├── 047 Graphs 4 ├── 1 commutableIslands.cpp ├── 4 edgeInMST.cpp ├── A1_commutableGraphs.cpp ├── A2_batches.cpp ├── HW2 Batches.cpp ├── README.md └── UNION_FIND.cpp ├── 048 Graphs 5 ├── A1 preReqCourses.cpp ├── A3 detectCycle.cpp ├── A3_LexTopologicalSort.cpp ├── HW1_goodGraph.cpp ├── HW3_tree_coloring_with_three_colors.cpp ├── README.md ├── detectCycle.cpp └── topologicalSort.cpp ├── 049 Problems on Graphs ├── Assignme.cpp └── README.md ├── 050 Practice ├── 01 MISC │ ├── 1 meetingRooms.cpp │ ├── 2_removeExtraEdge.cpp │ ├── 3 pickFromBothSides.cpp │ ├── 4_oddShuffling.cpp │ └── README.md ├── 02 MISC │ ├── 2 littlePonyAndPartitionSort.cpp │ ├── 4 canUWin.cpp │ └── README.md ├── 03 MISC │ ├── 1 countTotalSetBits.cpp │ ├── 1_cntTotSetBits1.cpp │ └── README.md ├── 04 DP Remedial │ ├── 1_maxCoinsInALine.cpp │ ├── 2_maxFruits.cpp │ ├── 3_cutRod.cpp │ └── 4_minFallingPathSum2.cpp ├── 05 DP 2 (Remedial) │ ├── 01 uniqueBST.cpp │ ├── 01 uniqueBST1.cpp │ ├── 01 uniqueBST2.cpp │ ├── 02_universalString.cpp │ ├── 03_maxCoinTree.cpp │ └── README.md ├── 07 Graphs Remedial │ ├── [Optimized]steppingNumbers.cpp │ └── steppingStones.cpp ├── MI │ ├── 1_15Aug.cpp │ └── 2_23Aug.cpp └── README.md ├── 051 DP with Bitmasking 1 ├── A1_elementSelection.cpp ├── A2_AllthePermutations.cpp ├── A3_favouriteTeacher.cpp └── README.MD ├── 052 DP with Bitmasking 2 ├── 1_Travelling_Salesman_Problem.cpp └── README.MD ├── 053 Digit DP ├── A1_[Optimized]_nonZeroDigits.cpp ├── A1_nonZeroDigits.cpp ├── A2_DoubleSum.cpp ├── A2_[Optimized]_DoubleSum.cpp └── README.MD ├── Contests ├── 01 Contest │ ├── 01 PairSumDivisibleB.cpp │ ├── 01 PairSumDivisiblebyB.cpp │ ├── 02 powersOf3.cpp │ ├── 03 KSmallestTriplet.cpp │ ├── 03 KSmallestTripletSum.cpp │ ├── 04 XORPrime.cpp │ └── README.md ├── 02 Contest │ ├── 04 A-B.cpp │ ├── 1 Swap elements.cpp │ ├── 2 Hide Boxes.cpp │ ├── 3 Sort permutation.cpp │ └── README.md ├── 03 Contest │ └── README.md ├── 04 Contest │ ├── AdjPosNeg.cpp │ ├── BallMagician.cpp │ ├── README.md │ ├── SwapElements.cpp │ └── maximumXOR.cpp ├── 05 Contest │ ├── 1_EqualStrings.cpp │ ├── 2_RemoveElements.cpp │ ├── 3_AnotherGCD.cpp │ └── 4_OpenMinimumShop.py ├── 06 Contest │ ├── 1 powerArrays.cpp │ ├── 2 similarityBWcities.cpp │ ├── 3 sweetDish.cpp │ ├── 4 crosstheWall.cpp │ └── README.md ├── 07 Contest │ ├── 1 powerArray.cpp │ ├── 2 similarityBWcities.cpp │ ├── 3 sweetDish.cpp │ └── README.md ├── 08 Contest │ ├── 1 GCD_PAIR.cpp │ └── 2 squareWindow.cpp ├── 10 Contest │ └── fractionalDistillation.cpp ├── 11 Contest │ └── stringQueries.cpp ├── 12 Contest │ ├── InATrouble.cpp │ └── substringSums.cpp ├── 13 Contest │ ├── greatestItems.cpp │ ├── oneLove.cpp │ └── shaggyLikeMedians.cpp ├── 14 Contest │ └── README.md ├── 15 Contest │ └── README.md ├── 16 Contest │ ├── 2 bagsAndXOR.cpp │ └── README.md ├── 17 Contest │ ├── NameTransformation.cpp │ ├── NoMoreZeroes.cpp │ └── README.md ├── 18 Contest │ ├── chessmodulo.cpp │ ├── gcdQueries.cpp │ ├── permutation game.jpg │ ├── permutationGame.cpp │ └── top 2 in scaler contest.jpg ├── 19 Contest │ ├── 1 reconstructLinks.cpp │ ├── 2 waysOfColoring.cpp │ ├── 3 minSingletons.cpp │ └── 4 maxSumMatrix.cpp └── README.md ├── Core Subjects ├── Database │ └── README.MD └── Operating Systems │ ├── Operating Systems 1 │ └── README.md │ ├── Operating Systems 2 │ └── README.md │ ├── Operating Systems 3 │ └── README.md │ ├── Operating Systems 4 │ └── README.md │ ├── Operating Systems 5 │ ├── README.md │ └── TaskScheduling.cpp │ ├── Operating Systems 6 │ └── README.md │ ├── Operating Systems 7 │ └── README.md │ └── Operating Systems 8 │ └── README.md ├── MI ├── 11October.cpp ├── 12 December2020.cpp └── recursion.cpp ├── README.md ├── basics ├── README.md ├── passByRef.cpp ├── tree.cpp ├── vector.cpp └── vectorImplementation.cpp └── template.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++20", 17 | "intelliSenseMode": "msvc-x64" 18 | } 19 | ], 20 | "version": 4 21 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "vector": "cpp", 4 | "ostream": "cpp", 5 | "algorithm": "cpp", 6 | "chrono": "cpp", 7 | "limits": "cpp", 8 | "random": "cpp", 9 | "initializer_list": "cpp", 10 | "list": "cpp", 11 | "type_traits": "cpp", 12 | "xhash": "cpp", 13 | "xstring": "cpp", 14 | "xutility": "cpp", 15 | "deque": "cpp" 16 | }, 17 | "python.analysis.autoImportCompletions": false 18 | } -------------------------------------------------------------------------------- /001 Array and Math/A3 maxConsecutiveGap.cpp: -------------------------------------------------------------------------------- 1 | int Solution::maximumGap(const vector &A) { 2 | 3 | int n = A.size(); 4 | 5 | if (n < 2) 6 | return 0; 7 | 8 | int maxEle = INT_MIN; 9 | int minEle = INT_MAX; 10 | 11 | for (int x: A) { 12 | maxEle = max(maxEle, x); 13 | minEle = min(minEle, x); 14 | } 15 | 16 | int gap = (maxEle - minEle - 1)/(n-1) + 1; 17 | 18 | vector minB(n-1, INT_MAX); 19 | vector maxB(n-1, INT_MIN); 20 | 21 | for (int i = 0; i < n; ++i) { 22 | if ( (A[i] != maxEle) && (A[i] != minEle) ) { 23 | int index = (A[i]-minEle)/gap; 24 | minB[index] = min(minB[index], A[i]); 25 | maxB[index] = max(maxB[index], A[i]); 26 | } 27 | } 28 | 29 | int ans = INT_MIN; 30 | int prev = minEle; 31 | for (int i = 0; i < n-1; ++i) { 32 | if ( (minB[i] == INT_MAX) && (maxB[i] == INT_MIN) ) { 33 | continue; 34 | } 35 | ans = max(ans, minB[i]-prev); 36 | prev = maxB[i]; 37 | } 38 | ans = max(ans, maxEle - prev); 39 | 40 | return ans; 41 | } 42 | -------------------------------------------------------------------------------- /001 Array and Math/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems and assignments of day 1 2 | -------------------------------------------------------------------------------- /002 Array 2/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignments and problems of this chapter 2 | -------------------------------------------------------------------------------- /003 Math 1 GCD/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all assignments and homeworks solutions 2 | -------------------------------------------------------------------------------- /004 Math 2 Prime/A1_lucky.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int A = 8; 7 | 8 | vector isprime(A + 1, true); 9 | isprime[0] = isprime[1] = 0; 10 | 11 | for (int i = 2; i <= A; ++i) 12 | { 13 | for (int j = 2 * i; j <= A; j += i) 14 | { 15 | isprime[j] = false; 16 | } 17 | } 18 | 19 | for (bool x : isprime) 20 | cout << x << " "; 21 | cout << endl; 22 | vector prime(A + 1, 0); 23 | 24 | for (int i = 2; i <= A; ++i) 25 | { 26 | if (isprime[i]) 27 | { 28 | for (int j = 2 * i; j <= A; j += i) 29 | { 30 | prime[j]++; 31 | } 32 | } 33 | } 34 | 35 | int lucky = 0; 36 | for (int i = 0; i <= A; ++i) 37 | { 38 | if (prime[i] == 2) 39 | { 40 | lucky++; 41 | } 42 | } 43 | 44 | for (int i = 0; i <= 12; ++i) 45 | cout << i << " "; 46 | cout << endl; 47 | for (int x : prime) 48 | cout << x << ", "; 49 | 50 | cout << endl; 51 | cout << lucky; 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /004 Math 2 Prime/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all assignments and homeworks of the topic __prime factorization and Sieve theorem__ 2 | -------------------------------------------------------------------------------- /005 Math 3 Mod/A1 Excel Column Tile.py: -------------------------------------------------------------------------------- 1 | Excel Column Title 2 | Problem Description 3 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 4 | 1 -> A 5 | 2 -> B 6 | 3 -> C 7 | ... 8 | 26 -> Z 9 | 27 -> AA 10 | 28 -> AB 11 | 12 | 13 | 14 | Problem Constraints 15 | 1 <= A <= INTMAX 16 | 17 | 18 | Input Format 19 | First and only argument of input contains single integer A 20 | 21 | 22 | Output Format 23 | Return a string denoting the corresponding title. 24 | 25 | 26 | Example Input 27 | A = 27 28 | 29 | 30 | Example Output 31 | "AA" 32 | 33 | 34 | Example Explanation 35 | 1 -> A, 36 | 2 -> B, 37 | 3 -> C, 38 | ... 39 | 26 -> Z, 40 | 27 -> AA, 41 | 28 -> AB 42 | 43 | 44 | 45 | 46 | class Solution: 47 | # @param A : integer 48 | # @return a strings 49 | def convertToTitle(self, A): 50 | 51 | res = [] 52 | 53 | while A > 0: 54 | if A % 26 == 0: 55 | res.append('Z') 56 | A//= 26 57 | A = A-1 58 | 59 | else: 60 | res.append(chr( (A%26) + 64)) 61 | A //= 26 62 | 63 | s = "" 64 | s = s.join(res[::-1]) 65 | 66 | return s 67 | 68 | -------------------------------------------------------------------------------- /005 Math 3 Mod/A2 Grid Unique paths.py: -------------------------------------------------------------------------------- 1 | Grid Unique Paths 2 | Problem Description 3 | A robot is located at the top-left corner of an A x B grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? 4 | 5 | 6 | Problem Constraints 7 | A and B will be such that the resulting answer fits in a 32 bit signed integer. 8 | 9 | 10 | Input Format 11 | First argument of input will be single integer A. 12 | Second argument of input will be single integer B. 13 | 14 | 15 | Output Format 16 | Return a single integer denoting the number of unique paths. 17 | 18 | 19 | Example Input 20 | A = 2, B = 2 21 | 22 | 23 | Example Output 24 | 2 25 | 26 | 27 | Example Explanation 28 | 2 possible routes : (0, 0) -> (0, 1) -> (1, 1) 29 | OR : (0, 0) -> (1, 0) -> (1, 1) 30 | 31 | 32 | 33 | class Solution: 34 | 35 | def uniquePaths(self, A, B): 36 | 37 | if A == 1 or B == 1: 38 | return 1 39 | 40 | if A 3 -> 2 28 | 29 | 30 | class Solution: 31 | # @param A : integer 32 | # @return an integer 33 | def solve(self, A): 34 | 35 | return A//2 - (A%2==0) 36 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW! Excel Column Number.py: -------------------------------------------------------------------------------- 1 | Excel Column Number 2 | Problem Description 3 | Given a column title as appears in an Excel sheet, return its corresponding column number. 4 | 5 | 6 | Problem Constraints 7 | 1 <= length of the column title <= 1000 8 | 9 | 10 | Input Format 11 | Input a string which represents the column title in excel sheet. 12 | 13 | 14 | Output Format 15 | Return a single integer which represents the corresponding column number. 16 | 17 | 18 | Example Input 19 | Input 1: 20 | AB 21 | Input 2: 22 | ABCD 23 | 24 | 25 | 26 | Example Output 27 | Output 1: 28 | 28 29 | Output 2: 30 | 18289 31 | 32 | 33 | 34 | Example Explanation 35 | Explanation 1: 36 | A -> 1 37 | B -> 2 38 | C -> 3 39 | ... 40 | Z -> 26 41 | AA -> 27 42 | AB -> 28 43 | 44 | 45 | 46 | 47 | class Solution: 48 | # @param A : string 49 | # @return an integer 50 | def titleToNumber(self, A): 51 | 52 | res = 0 53 | for i in A: 54 | res = res*26 + (ord(i)-ord('A')) +1 55 | 56 | return res 57 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW2 Reverse Integer.py: -------------------------------------------------------------------------------- 1 | Reverse integer 2 | Problem Description 3 | You are given an integer N and the task is to reverse the digits of the given integer. Return 0 if the result overflows and does not fit in a 32 bit signed integer 4 | 5 | Look at the example for clarification. 6 | 7 | 8 | Problem Constraints 9 | N belongs to the Integer limits. 10 | 11 | 12 | Input Format 13 | Input an Integer. 14 | 15 | 16 | Output Format 17 | Return a single integer denoting the reverse of the given integer. 18 | 19 | 20 | Example Input 21 | Input 1: 22 | x = 123 23 | 24 | Input 2: 25 | x = -123 26 | 27 | 28 | 29 | Example Output 30 | Output 1: 31 | 321 32 | 33 | Ouput 2: 34 | -321 35 | 36 | 37 | 38 | Example Explanation 39 | If the given integer is negative like -123 the output is also negative -321 40 | 41 | 42 | 43 | class Solution: 44 | def reverse(self, A): 45 | negative = False 46 | 47 | if A < 0: 48 | negative = True 49 | A = -1*A 50 | 51 | rev = 0 52 | while A > 0: 53 | r = A % 10 54 | rev = rev*10 + r 55 | A //= 10 56 | 57 | if rev < -2147483648 or rev > 2147483647: 58 | return 0 59 | 60 | if negative: 61 | return -1*rev 62 | return rev 63 | 64 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW3 ncr % p.cpp: -------------------------------------------------------------------------------- 1 | int countFact(int n, int p) 2 | { 3 | int k=0; 4 | while (n>0) 5 | { 6 | k+=n/p; 7 | n/=p; 8 | } 9 | return k; 10 | } 11 | 12 | /* This function calculates (a^b)%MOD */ 13 | long long pow(int a, int b, int MOD) 14 | { 15 | long long x=1,y=a; 16 | while(b > 0) 17 | { 18 | if(b%2 == 1) 19 | { 20 | x=(x*y); 21 | if(x>MOD) x%=MOD; 22 | } 23 | y = (y*y); 24 | if(y>MOD) y%=MOD; 25 | b /= 2; 26 | } 27 | return x; 28 | } 29 | 30 | long long C(int n, int r, int MOD) 31 | { 32 | long long res = 1; 33 | vector isPrime(n+1,1); 34 | for (int i=2; i<=n; i++) 35 | if (isPrime[i]) 36 | { 37 | for (int j=2*i; j<=n; j+=i) 38 | isPrime[j]=0; 39 | int k = countFact(n,i) - countFact(r,i) - countFact(n-r,i); 40 | res = (res * pow(i, k, MOD)) % MOD; 41 | } 42 | return res; 43 | } 44 | 45 | int Solution::solve(int A, int B, int Mod) 46 | { 47 | 48 | return Mod == 1 ? 0 : C(A,B,Mod); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW3 ncr%p.cpp: -------------------------------------------------------------------------------- 1 | long long binpow(long long a, long long b, long long m) { 2 | a %= m; 3 | long long res = 1; 4 | while (b > 0) { 5 | if (b & 1) 6 | res = res * a % m; 7 | a = a * a % m; 8 | b >>= 1; 9 | } 10 | return res; 11 | } 12 | long long fact[1000005]; 13 | int Solution::solve(int A, int B, int C) { 14 | 15 | fact[0]=1; 16 | for(long long i=1;i<=A;++i){ 17 | fact[i]=(fact[i-1]*i)%C; 18 | } 19 | 20 | long long ans = fact[A]; 21 | ans = ( ans * binpow(fact[B],C-2,C))%C; 22 | ans = ( ans * binpow(fact[A-B],C-2,C))%C; 23 | 24 | return ans; 25 | } 26 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW5 ncr % m.cpp: -------------------------------------------------------------------------------- 1 | 2 | int ncrdp(int n, int r, int mod){ 3 | 4 | int C[n+1][r+1]; 5 | memset(C, 0, sizeof(C)); 6 | 7 | for (int i = 0; i <= n; ++i){ 8 | for (int j = 0; j <= min(i,r); ++j){ 9 | if (j == 0 || j == i) 10 | C[i][j] = 1; 11 | else 12 | { 13 | C[i][j] = C[i-1][j-1] + C[i-1][j]; 14 | } 15 | } 16 | } 17 | 18 | return C[n][r] % mod; 19 | } 20 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW5 ncr % m1.cpp: -------------------------------------------------------------------------------- 1 | long long int combination(int n,int r,int mod){ 2 | int C[r+1]; 3 | memset(C, 0, sizeof(C)); 4 | 5 | C[0] = 1; 6 | for (int i = 1; i <= n; i++) 7 | { 8 | for (int j = min(i, r); j > 0; j--) 9 | C[j] = (C[j] + C[j-1])%mod; 10 | } 11 | return C[r]; 12 | } 13 | -------------------------------------------------------------------------------- /005 Math 3 Mod/HW6 rectangle Area.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Rectangle Area 4 | Problem Description 5 | 6 | Given eight integers A, B, C, D, E, F, G and H which represent two rectangles in a 2D plane. 7 | 8 | For the first rectangle it's bottom left corner is (A, B) and top right corner is (C, D) and for the second rectangle it's bottom left corner is (E, F) and top right corner is (G, H). 9 | 10 | Find and return the overlapping area of the two rectangles. 11 | 12 | 13 | 14 | Problem Constraints 15 | -104 <= A <= C <= 104 16 | -104 <= B <= D <= 104 17 | -104 <= E <= G <= 104 18 | -104 <= F <= H <= 104 19 | 20 | 21 | Input Format 22 | The eight arguments given are the integers A, B, C, D, E, F, G and H. 23 | 24 | 25 | 26 | Output Format 27 | Return the overlapping area of the two rectangles. 28 | 29 | 30 | 31 | Example Input 32 | Input 1: 33 | 34 | A = 0 B = 0 35 | C = 4 D = 4 36 | E = 2 F = 2 37 | G = 6 H = 6 38 | Input 2: 39 | 40 | A = 0 B = 0 41 | C = 4 D = 4 42 | E = 2 F = 2 43 | G = 3 H = 3 44 | 45 | 46 | Example Output 47 | Output 1: 48 | 49 | 4 50 | Output 2: 51 | 52 | 1 53 | 54 | */ 55 | 56 | 57 | int Solution::solve(int A, int B, int C, int D, int E, int F, int G, int H) { 58 | 59 | int x_dist = min(C,G) - max(A,E); 60 | int y_dist = min(D, H) - max(B,F); 61 | 62 | int ans = 0; 63 | if (x_dist && y_dist) 64 | ans = x_dist * y_dist; 65 | 66 | return ans; 67 | } 68 | -------------------------------------------------------------------------------- /005 Math 3 Mod/binomialCoefficient.cpp: -------------------------------------------------------------------------------- 1 | ll binomialCoeff(int n, int k){ 2 | 3 | ll res = 1; 4 | // Since C(n, k) = C(n, n-k) 5 | if (k > n-k) 6 | k = n-k; 7 | 8 | for (int i = 0; i < k; ++i){ 9 | res *= (n-i); 10 | res /= (i+1); 11 | } 12 | 13 | return res; 14 | } 15 | -------------------------------------------------------------------------------- /005 Math 3 Mod/img/IMG_20200618_003533__01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/005 Math 3 Mod/img/IMG_20200618_003533__01.jpg -------------------------------------------------------------------------------- /005 Math 3 Mod/img/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the images used in this class 2 | -------------------------------------------------------------------------------- /006 Bit Manipulation/HW2 diffBitsSumPairwise.cpp: -------------------------------------------------------------------------------- 1 | long long MOD = 1000000007; 2 | 3 | int Solution::cntBits(vector &A) { 4 | 5 | long long cnt = 0, ans = 0; 6 | for (int i = 0; i < 32; ++i) { 7 | cnt = 0; 8 | for (int j = 0; j < A.size(); ++j) { 9 | if (A[j] & (1< > &A) { 30 | int l = 0, r = INT_MAX; 31 | int mid, req = A.size()*A[0].size(); 32 | 33 | while (r-l>1){ 34 | mid = l+(r-l)/2; 35 | int cnt = 0; 36 | 37 | for (auto &i:A){ 38 | int p = upper_bound(i.begin(), i.end(), mid) - i.begin(); 39 | cnt += p; 40 | } 41 | 42 | if (cnt >= (req/2 + 1)) 43 | r = mid; 44 | else 45 | l = mid; 46 | } 47 | return r; 48 | } 49 | -------------------------------------------------------------------------------- /008 Searching 2/A4 SmallestGoodBase.py: -------------------------------------------------------------------------------- 1 | Smallest Good Base 2 | Given an integer A, we call k >= 2 a good base of A, if all digits of A base k are 1. Now given a string representing A, you should return the smallest good base of A in string format. 3 | Input Format 4 | The only argument given is the string representing A. 5 | Output Format 6 | Return the smallest good base of A in string format. 7 | Constraints 8 | 3 <= A <= 10^18 9 | For Example 10 | Input 1: 11 | A = "13" 12 | Output 1: 13 | "3" (13 in base 3 is 111) 14 | 15 | Input 2: 16 | A = "4681" 17 | Output 2: 18 | "8" (4681 in base 8 is 11111) 19 | 20 | 21 | 22 | 23 | class Solution: 24 | 25 | 26 | def solve(self, A): 27 | 28 | N = int(A) 29 | 30 | for i in range(63,0,-1): 31 | low = 2 32 | high = N-1 33 | 34 | while low<=high: 35 | 36 | mid = low + (high-low)//2 37 | sum = (mid**i-1)//(mid-1) 38 | 39 | if sum == N: 40 | return str(mid) 41 | 42 | elif sum > N: 43 | high = mid-1 44 | 45 | else: 46 | low = mid+1 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /008 Searching 2/HW2 SquareRoot.py: -------------------------------------------------------------------------------- 1 | Square Root of Integer 2 | Problem Description 3 | Given an integer A. Compute and return the square root of A. If A is not a perfect square, return floor(sqrt(A)). DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY. 4 | 5 | 6 | Problem Constraints 7 | 1 <= A <= 109 8 | 9 | 10 | Input Format 11 | The first and only argument given is the integer A. 12 | 13 | 14 | Output Format 15 | Return floor(sqrt(A)) 16 | 17 | 18 | Example Input 19 | Input 1: 20 | 11 21 | Input 2: 22 | 9 23 | 24 | 25 | 26 | Example Output 27 | Output 1: 28 | 3 29 | Output 2: 30 | 3 31 | 32 | 33 | 34 | Example Explanation 35 | Explanation: 36 | When A = 11 , square root of A = 3.316. It is not a perfect square so we return the floor which is 3. 37 | When A = 9 which is a perfect square of 3, so we return 3 38 | 39 | 40 | 41 | class Solution: 42 | # @param A : integer 43 | # @return an integer 44 | def sqrt(self, A): 45 | 46 | if A==1: 47 | return 1 48 | 49 | l = 0 50 | h = A 51 | while h-l > 1: 52 | mid = l+(h-l)//2 53 | x = mid*mid 54 | 55 | if x==A: 56 | return mid 57 | 58 | elif x>A: 59 | h = mid 60 | 61 | else: 62 | l = mid 63 | 64 | return l 65 | 66 | 67 | -------------------------------------------------------------------------------- /008 Searching 2/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homeworks given in the class 2 | 3 | Before starting the Binary Search I recommend to read this powerful article: [Variances of Binary Search](https://www.topcoder.com/community/competitive-programming/tutorials/binary-search/?target=_blank) 4 | 5 | 1. Binary Search on sorted structures 6 | 2. Binary Search in answer space 7 | 3. Binary Search on patterns 8 | 9 | 10 | -------------------------------------------------------------------------------- /009 Recursion/A1 UniquePermutations.cpp: -------------------------------------------------------------------------------- 1 | void swap (int &a, int &b){ 2 | int temp = a; 3 | a = b; 4 | b = temp; 5 | } 6 | 7 | vector> ans; 8 | void generatePermutations(vector &A, int l, int r){ 9 | if (l == r){ 10 | ans.push_back(A); 11 | return; 12 | } 13 | unordered_set vis; 14 | for (int i = l; i <= r; ++i){ 15 | if (vis.find(A[i]) == vis.end()){ 16 | swap(A[i], A[l]); 17 | generatePermutations(A, l+1, r); 18 | swap(A[i], A[l]); 19 | vis.insert(A[i]); 20 | } 21 | } 22 | } 23 | 24 | vector > Solution::permute(vector &A) { 25 | 26 | ans.clear(); 27 | generatePermutations(A, 0, A.size()-1); 28 | 29 | return ans; 30 | } 31 | -------------------------------------------------------------------------------- /009 Recursion/A2 permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return a list of list of integers 4 | def permute(self, A): 5 | 6 | if len(A)==1: 7 | return [A] 8 | 9 | ans = [] 10 | for i in range(len(A)): 11 | remString = A[:i]+A[i+1:] 12 | p = self.permute(remString) 13 | 14 | for j in range(len(p)): 15 | ans.append([A[i]]+p[j]) 16 | 17 | return ans 18 | 19 | -------------------------------------------------------------------------------- /009 Recursion/HW1 [opt2] CombinationSum2.cpp: -------------------------------------------------------------------------------- 1 | vector > ans; 2 | 3 | void recurse(vector &A, int B, vector &curr, int sum, int index){ 4 | 5 | if (sum == B){ 6 | ans.push_back(curr); 7 | return; 8 | } 9 | if (sum > B) 10 | return; 11 | 12 | int freq[10000] {0}; 13 | for (int i = index; i < A.size(); i++){ 14 | if (freq[A[i]] == 0){ 15 | freq[A[i]] = 1; 16 | curr.push_back(A[i]); 17 | recurse(A,B,curr,sum+A[i],i+1); 18 | curr.pop_back(); 19 | } 20 | } 21 | 22 | return; 23 | } 24 | 25 | vector > Solution::combinationSum(vector &A, int B) { 26 | 27 | ans.clear(); 28 | sort(A.begin(), A.end()); 29 | vector curr; 30 | recurse(A, B, curr, 0, 0); 31 | 32 | return ans; 33 | } 34 | -------------------------------------------------------------------------------- /009 Recursion/HW1 [opt3] CombinationSum.cpp: -------------------------------------------------------------------------------- 1 | vector > ans; 2 | 3 | void recurse(vector &A, int B, vector &curr, int sum, int index){ 4 | 5 | if (sum == B){ 6 | ans.push_back(curr); 7 | return; 8 | } 9 | if (sum > B) 10 | return; 11 | 12 | unordered_map freq; 13 | for (int i = index; i < A.size(); i++){ 14 | if (freq[A[i]] == 0){ 15 | freq[A[i]] = 1; 16 | curr.push_back(A[i]); 17 | recurse(A,B,curr,sum+A[i],i+1); 18 | curr.pop_back(); 19 | } 20 | } 21 | 22 | return; 23 | } 24 | 25 | vector > Solution::combinationSum(vector &A, int B) { 26 | 27 | ans.clear(); 28 | sort(A.begin(), A.end()); 29 | vector curr; 30 | recurse(A, B, curr, 0, 0); 31 | 32 | return ans; 33 | } 34 | -------------------------------------------------------------------------------- /009 Recursion/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the recursion assignment and homework problems 2 | 3 | -------------------------------------------------------------------------------- /010 Backtracking 1/A1_nQueens.cpp: -------------------------------------------------------------------------------- 1 | vector> res; 2 | 3 | bool check(vector &temp, int row, int col, int A) 4 | { 5 | for (int i = 0; i < row; i++) 6 | if (temp[i][col] == 'Q') 7 | return false; 8 | 9 | for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) 10 | if (temp[i][j] == 'Q') 11 | return false; 12 | 13 | for (int i = row, j = col; i >= 0 && j < A; i--, j++) 14 | if (temp[i][j] == 'Q') 15 | return false; 16 | 17 | return true; 18 | } 19 | 20 | void getNQueen(int A, int row, vector &temp) 21 | { 22 | if (row == A) 23 | { 24 | res.push_back(temp); 25 | return; 26 | } 27 | 28 | for (int col = 0; col < A; col++) 29 | { 30 | if (check(temp, row, col, A)) 31 | { 32 | temp[row][col] = 'Q'; 33 | getNQueen(A, row + 1, temp); 34 | temp[row][col] = '.'; 35 | } 36 | } 37 | } 38 | 39 | vector> Solution::solveNQueens(int A) 40 | { 41 | res.clear(); 42 | 43 | if (A == 2 || A == 3) 44 | return res; 45 | 46 | string s(A, '.'); 47 | 48 | vector temp(A, s); 49 | 50 | getNQueen(A, 0, temp); 51 | 52 | return res; 53 | } -------------------------------------------------------------------------------- /010 Backtracking 1/A4_grayCode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Gray Code 4 | Problem Description 5 | 6 | The gray code is a binary numeral system where two successive values differ in only one bit. 7 | 8 | Given a non-negative integer A representing the total number of bits in the code, print the sequence of gray code. 9 | 10 | A gray code sequence must begin with 0. 11 | 12 | 13 | 14 | Problem Constraints 15 | 1 <= A <= 16 16 | 17 | 18 | 19 | Input Format 20 | First argument is an integer A. 21 | 22 | 23 | 24 | Output Format 25 | Return an array of integers representing the gray code sequence. 26 | 27 | 28 | 29 | Example Input 30 | Input 1: 31 | 32 | A = 2 33 | Input 1: 34 | 35 | A = 1 36 | 37 | 38 | Example Output 39 | output 1: 40 | 41 | [0, 1, 3, 2] 42 | output 2: 43 | 44 | [0, 1] 45 | 46 | 47 | Example Explanation 48 | Explanation 1: 49 | 50 | for A = 2 the gray code sequence is: 51 | 00 - 0 52 | 01 - 1 53 | 11 - 3 54 | 10 - 2 55 | So, return [0,1,3,2]. 56 | Explanation 1: 57 | 58 | for A = 1 the gray code sequence is: 59 | 00 - 0 60 | 01 - 1 61 | So, return [0, 1]. 62 | 63 | */ 64 | 65 | vector Solution::grayCode(int A) { 66 | 67 | vector ans; 68 | for (int i = 0; i < (1<>1)); 70 | } 71 | 72 | return ans; 73 | } 74 | -------------------------------------------------------------------------------- /010 Backtracking 1/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework problems 2 | -------------------------------------------------------------------------------- /011 Backtracking 2/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework problems 2 | -------------------------------------------------------------------------------- /012 Sorting 1/A2 Largest Number.cpp: -------------------------------------------------------------------------------- 1 | Largest Number 2 | Given a list of non negative integers, arrange them such that they form the largest number. For example: Given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. 3 | 4 | 5 | 6 | int cmp(string x, string y){ 7 | string a = x+y; 8 | string b = y+x; 9 | return a.compare(b) > 0 ? 1 : 0; 10 | } 11 | 12 | string Solution::largestNumber(const vector &A) { 13 | vector as; 14 | 15 | for (auto i:A) 16 | as.push_back(to_string(i)); 17 | 18 | sort(as.begin(), as.end(), cmp); 19 | 20 | string ans = ""; 21 | 22 | for (auto i : as) 23 | ans += i; 24 | 25 | if (ans[0] == '0') 26 | return "0"; 27 | 28 | return ans; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /012 Sorting 1/A3 waveArray.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::wave(vector &A) { 2 | 3 | sort (A.begin(), A.end()); 4 | 5 | for (int i = 1; i < A.size(); i=i+2) 6 | swap(A[i], A[i-1]); 7 | 8 | return A; 9 | } 10 | -------------------------------------------------------------------------------- /012 Sorting 1/A4_maxUnsortedSubarray1.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::subUnsort(vector &A) 2 | { 3 | int leftMax = A[0]; 4 | int rightMin = A[A.size() - 1]; 5 | int r = -1, l = -1; 6 | 7 | for (int i = 0; i < A.size(); ++i) 8 | { 9 | if (A[i] < leftMax) 10 | r = i; 11 | else 12 | leftMax = A[i]; 13 | } 14 | 15 | for (int j = A.size() - 2; j >= 0; --j) 16 | { 17 | if (A[j] > rightMin) 18 | l = j; 19 | else 20 | rightMin = A[j]; 21 | } 22 | 23 | if (l == -1 || r == -1) 24 | return {-1}; 25 | return {l, r}; 26 | } -------------------------------------------------------------------------------- /012 Sorting 1/A4_maximumUnsortedSubarray.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::subUnsort(vector &arr) { 2 | int n = arr.size(); 3 | int s = 0, e = n-1, i, max, min; 4 | vector result; 5 | for (s = 0; s < n-1; s++) 6 | { 7 | if (arr[s] > arr[s+1]) 8 | break; 9 | } 10 | if (s == n-1) 11 | { 12 | result.push_back(-1); 13 | return result; 14 | } 15 | 16 | for(e = n - 1; e > 0; e--) 17 | { 18 | if(arr[e] < arr[e-1]) 19 | break; 20 | } 21 | 22 | max = arr[s]; min = arr[s]; 23 | for(i = s + 1; i <= e; i++) 24 | { 25 | if(arr[i] > max) 26 | max = arr[i]; 27 | if(arr[i] < min) 28 | min = arr[i]; 29 | } 30 | 31 | for( i = 0; i < s; i++) 32 | { 33 | if(arr[i] > min) 34 | { 35 | s = i; 36 | break; 37 | } 38 | } 39 | 40 | for( i = n -1; i >= e+1; i--) 41 | { 42 | if(arr[i] < max) 43 | { 44 | e = i; 45 | break; 46 | } 47 | } 48 | 49 | result.push_back(s); 50 | result.push_back(e); 51 | 52 | return result; 53 | } 54 | -------------------------------------------------------------------------------- /012 Sorting 1/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Intuition behind Sum the Difference problem: 4 | 5 | ### How the Time Complexity changes from O(2^N) --> O(n^2) --> O(n*log n) 6 | 7 | Read about [Horner's formula](https://en.wikipedia.org/wiki/Horner%27s_method) before proceeding further 8 | 9 | ![Sum the Difference 1](img/Sum%20the%20difference.jpg) 10 | 11 | 1) Here you can observe in the 1st approach we're generating all subsets in O(2^n) time and calculating max-min in O91) time so overall time is O(2^n) 12 | 13 | 2) First sort the array in O(nlogn) time and then for every value I mean for every i and j calculate (A[j] - A[i]) * 2^(j-i-1). 14 | (A[j] - A[i]) for max - min and 2^(j-i-1) for the number of subsets has the max and min as A[j] & A[i] respectively 15 | 16 | 3) Here draw some more observation by counting how many times 1,2,3 and 4 appears in the max and min of all subsets of {1,2,3,4}? 17 | We found that the count appears as 2^0, 2^1, 2^2, 2^3........ So we simply use Horner's method to calculate the max and min. 18 | 19 | ![Horner's method](img/Horners%20method.JPG) 20 | 21 | ![Sum the Difference 1](img/Sum%20the%20difference%201.jpg) 22 | 23 | ![Sum the Difference 1](img/Sum%20the%20difference%202.jpg) 24 | 25 | 26 | 27 | 28 | 29 | 30 | This folder contains all the assignment and homework problems 31 | -------------------------------------------------------------------------------- /012 Sorting 1/Sorting Algorithms/bubble3Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Sorting elements alternatively 5 | // Odd indexed and even indexed elements are sorted seperately 6 | 7 | void bubble3Sort (vector A) { 8 | 9 | int n = A.size(); 10 | for (int i = 0; i < n-1; ++i){ 11 | for (int j = 0; j < n-i-2; ++j){ 12 | if (A[j] > A[j+2]) 13 | swap(A[j], A[j+2]); 14 | } 15 | } 16 | 17 | for (int x : A) 18 | cout< A {4,3,5,6,7,2}; 23 | bubble3Sort(A); 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /012 Sorting 1/Sorting Algorithms/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubbleSort (vector A) { 5 | 6 | int n = A.size(); 7 | for (int i = 0; i < n-1; ++i){ 8 | for (int j = 0; j < n-i-1; ++j){ 9 | if (A[j] > A[j+1]) 10 | swap(A[j], A[j+1]); 11 | } 12 | } 13 | 14 | for (int x : A) 15 | cout< A {4,3,1,5,2,7,4}; 20 | bubbleSort(A); 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /012 Sorting 1/Sorting Algorithms/countSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void countSort (vector A) { 5 | 6 | int n = A.size(); 7 | 8 | int maxEle = INT_MIN; 9 | for (int x : A){ 10 | maxEle = max(maxEle, x); 11 | } 12 | 13 | vector freq(maxEle + 1, 0); 14 | vector prefixSum(maxEle + 1, 0); 15 | for (int x : A){ 16 | freq[x]++; 17 | } 18 | 19 | prefixSum[0] = freq[0]; 20 | for (int i = 1; i < freq.size(); ++i) 21 | prefixSum[i] = prefixSum[i-1] + A[i]; 22 | 23 | vector res(n, 0); 24 | for (int i = n-1; i >= 0; --i){ 25 | int idx = --prefixSum[A[i]]; 26 | res[idx] = A[i]; 27 | cout< A {4,2,2,0,1,2,4,3,2,1}; 39 | countSort(A); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /012 Sorting 1/Sorting Algorithms/insertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void insertionSort (vector A) { 5 | 6 | int n = A.size(), j, key; 7 | for (int i = 1; i < n; ++i){ 8 | key = A[i]; 9 | j = i-1; 10 | while (j >= 0 && A[j] > key){ 11 | A[j+1] = A[j]; 12 | j--; 13 | } 14 | A[j+1] = key; 15 | } 16 | 17 | for (int x : A) 18 | cout< A {4,3,1,5,2,7,4}; 23 | insertionSort(A); 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /012 Sorting 1/Sorting Algorithms/selectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void selectionSort (vector A) { 5 | 6 | int n = A.size(), min; 7 | for (int i = 0; i < n; ++i){ 8 | min = i; 9 | for (int j = i; j < n; ++j){ 10 | if (A[j] < A[min]) 11 | min = j; 12 | } 13 | swap(A[i], A[min]); 14 | } 15 | 16 | for (int x : A) 17 | cout< A {4,3,1,5,2,7,4}; 22 | selectionSort(A); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /012 Sorting 1/img/Horners method.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/012 Sorting 1/img/Horners method.JPG -------------------------------------------------------------------------------- /012 Sorting 1/img/README.md: -------------------------------------------------------------------------------- 1 | This folder contains the image files which are used to draw the intuition behind the Sum the difference solution from O(2^n) --> O(n^2) --> O(nlogn) 2 | -------------------------------------------------------------------------------- /012 Sorting 1/img/Sum the difference 1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/012 Sorting 1/img/Sum the difference 1.jpg -------------------------------------------------------------------------------- /012 Sorting 1/img/Sum the difference 2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/012 Sorting 1/img/Sum the difference 2.jpg -------------------------------------------------------------------------------- /012 Sorting 1/img/Sum the difference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/012 Sorting 1/img/Sum the difference.jpg -------------------------------------------------------------------------------- /013 Sorting 2/HW1 LargestNumber.py: -------------------------------------------------------------------------------- 1 | Largest Number 2 | Problem Description 3 | Given a list A of non negative integers, arrange them such that they form the largest number. Note: The result may be very large, so you need to return a string instead of an integer. 4 | 5 | 6 | Problem Constraints 7 | 1 <= len(A) <= 100000 8 | 0 <= A[i] <= 2*109 9 | 10 | 11 | Input Format 12 | First argument is an array of integers. 13 | 14 | 15 | Output Format 16 | Return a string representing the largest number. 17 | 18 | 19 | Example Input 20 | Input 1: 21 | A = [3, 30, 34, 5, 9] 22 | 23 | 24 | Example Output 25 | Output 1: 26 | 9534330 27 | 28 | 29 | Example Explanation 30 | Explanation 1: 31 | A = [3, 30, 34, 5, 9] 32 | Reorder the numbers to [9, 5, 34, 3, 30] to form the largest number. 33 | 34 | 35 | 36 | 37 | int cmp(string x, string y){ 38 | string a = x+y; 39 | string b = y+x; 40 | return a.compare(b)>0 ? 1:0; 41 | } 42 | 43 | string Solution::largestNumber(const vector &A) { 44 | 45 | vector temp; 46 | 47 | for (auto &i: A) 48 | temp.push_back(to_string(i)); 49 | 50 | sort(temp.begin(), temp.end(), cmp); 51 | 52 | string ans = ""; 53 | 54 | for (auto &i: temp) 55 | ans += i; 56 | 57 | if (ans[0] == '0') 58 | return "0"; 59 | 60 | return ans; 61 | 62 | } 63 | -------------------------------------------------------------------------------- /013 Sorting 2/HW4 MaxChunksToSorted.cpp: -------------------------------------------------------------------------------- 1 | Max Chunks To Make Sorted 2 | Problem Description 3 | Given an array of integers A of size N that is a permutation of [0, 1, 2, ..., (N-1)], if we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array. What is the most number of chunks we could have made? 4 | 5 | 6 | Problem Constraints 7 | 1 <= N <= 100000 8 | 0 <= A[i] < N 9 | 10 | 11 | Input Format 12 | The only argument given is the integer array A. 13 | 14 | 15 | Output Format 16 | Return the maximum number of chunks that we could have made. 17 | 18 | 19 | Example Input 20 | Input 1: 21 | A = [1, 2, 3, 4, 0] 22 | Input 2: 23 | A = [2, 0, 1, 3] 24 | 25 | 26 | Example Output 27 | Output 1: 28 | 1 29 | Output 2: 30 | 2 31 | 32 | 33 | Example Explanation 34 | Explanation 1: 35 | A = [1, 2, 3, 4, 0] 36 | To get the 0 in the first index, we have to take all elements in a single chunk. 37 | Explanation 2: 38 | A = [2, 0, 1, 3] 39 | We can divide the array into 2 chunks. 40 | First chunk is [2, 0, 1] and second chunk is [3]. 41 | 42 | 43 | 44 | 45 | 46 | int Solution::solve(vector &A) { 47 | 48 | int max1 = INT_MIN, n = A.size(); 49 | int cnt = 0; 50 | 51 | for (int i=0; i (2, 3) -> (4, 0) -> (3, 0). You will get a sorted array. 50 | You cannot sort it with lesser swaps. 51 | Explanation 2: 52 | 53 | You cannot sort it with lesser than 2 swaps. 54 | */ 55 | 56 | int Solution::solve(vector &A) 57 | { 58 | 59 | int ans = 0; 60 | for (int i = 0; i < A.size(); ++i) 61 | { 62 | while (A[i] != i) 63 | { 64 | ans++; 65 | swap(A[i], A[A[i]]); 66 | } 67 | } 68 | 69 | return ans; 70 | } -------------------------------------------------------------------------------- /014 Two Pointers/A1 3 Sum.cpp: -------------------------------------------------------------------------------- 1 | 3 Sum 2 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. 3 | Return the sum of the three integers. Assume that there will only be one solution 4 | 5 | Example: given array S = {-1 2 1 -4}, and target = 1. 6 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2) 7 | 8 | 9 | int Solution::threeSumClosest(vector &A, int B) { 10 | 11 | sort(A.begin(), A.end()); 12 | 13 | int closestSum = INT_MAX - *max_element(A.begin(), A.end()) - 1; 14 | 15 | for (int k = 0; k < A.size(); k++){ 16 | 17 | int i = k+1, j = A.size()-1; 18 | 19 | while ( i < j ){ 20 | int sum = A[i] + A[j] + A[k]; 21 | 22 | if (abs(B - sum) < abs(B - closestSum)) 23 | closestSum = sum; 24 | 25 | if (sum > B) 26 | j--; 27 | else 28 | i++; 29 | } 30 | } 31 | 32 | return closestSum; 33 | } 34 | -------------------------------------------------------------------------------- /014 Two Pointers/A2 Container with Most Water.cpp: -------------------------------------------------------------------------------- 1 | Container With Most Water 2 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 3 | 'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 4 | Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | Your program should return an integer which corresponds to the maximum area of water that can be contained 6 | ( Yes, we know maximum area instead of maximum volume sounds weird. But this is 2D plane we are working with for simplicity ). 7 | 8 | Note: You may not slant the container. 9 | 10 | Example : 11 | Input : [1, 5, 4, 3] 12 | Output : 6 13 | 14 | Explanation : 5 and 3 are distance 2 apart. So size of the base = 2. Height of container = min(5, 3) = 3. 15 | So total area = 3 * 2 = 6 16 | 17 | 18 | 19 | int Solution::maxArea(vector &A) { 20 | 21 | int n = A.size(); 22 | int i = 0, j = n-1, _max = 0; 23 | 24 | while (i &A, int B) { 27 | 28 | int ans = 0; 29 | int n = A.size(); 30 | 31 | int i = 0, j = n-1; 32 | 33 | while (i < j){ 34 | int sum = A[i]+A[j]; 35 | if (sum == B){ 36 | j--; 37 | i++; 38 | ans++; 39 | } 40 | 41 | else if(sum > B) 42 | j--; 43 | else 44 | i++; 45 | } 46 | 47 | 48 | return ans; 49 | } 50 | -------------------------------------------------------------------------------- /014 Two Pointers/A5 anotherCountingProblem.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | 3 | long mod = 1000000007, ans = 0; 4 | 5 | int l = 0, r = A.size() - 1; 6 | 7 | while (l < A.size() && r >= 0) 8 | { 9 | if (1l * A[l] * A[r] >= B) 10 | { 11 | r--; 12 | } 13 | else 14 | { 15 | ans = (ans % mod + (r + 1) % mod) % mod; 16 | l++; 17 | } 18 | } 19 | 20 | return int(ans % mod); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /014 Two Pointers/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework problems of this topic 2 | -------------------------------------------------------------------------------- /015 Hashing 1/A1 LongestConsecutiveSequence.py: -------------------------------------------------------------------------------- 1 | Longest Consecutive Sequence 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | Example: Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. 5 | Return its length: 4. Your algorithm should run in O(n) complexity. 6 | 7 | 8 | class Solution: 9 | # @param A : tuple of integers 10 | # @return an integer 11 | def longestConsecutive(self, arr): 12 | x = set() 13 | n = len(arr) 14 | 15 | for i in range(n): 16 | x.add(arr[i]) 17 | 18 | maxCnt = -1 19 | 20 | for i in range(n): 21 | t = arr[i] 22 | if t-1 not in x: 23 | cnt = 0 24 | k = 0 25 | 26 | while True: 27 | if t+k in x: 28 | cnt += 1 29 | else: 30 | maxCnt = max(maxCnt, cnt) 31 | break 32 | k += 1 33 | 34 | return maxCnt 35 | -------------------------------------------------------------------------------- /015 Hashing 1/A3 SubarrayWithZeroSum.py: -------------------------------------------------------------------------------- 1 | Find if there is a sub-array with 0 sum 2 | Given an array of integers A, find and return whether the given array contains a subarray with a sum equal to 0. 3 | If the given array contains a sub-array with sum zero return 1 else return 0. Note: Length of sub array should be at least one. 4 | Input Format 5 | The only argument given is the integer array A. 6 | Output Format 7 | Return whether the given array contains a subarray with a sum equal to **0**. 8 | Constraints 9 | 1 <= length of the array <= 100000 10 | -10^9 <= A[i] <= 10^9 11 | For Example 12 | Input 1: 13 | A = [1, 2, 3, 4, 5] 14 | Output 1: 15 | 0 16 | 17 | Input 2: 18 | A = [5, 17, -22, 11] 19 | Output 2: 20 | 1 21 | 22 | 23 | 24 | class Solution: 25 | # @param A : list of integers 26 | # @return an integer 27 | def solve(self, arr): 28 | n = len(arr) 29 | x = set() 30 | pre = arr[0] 31 | currSum = 0 32 | x.add(pre) 33 | 34 | for i in range(1,n): 35 | currSum = pre + arr[i] 36 | if currSum == 0: 37 | return 1 38 | if currSum in x: 39 | return 1 40 | else: 41 | x.add(currSum) 42 | pre = currSum 43 | 44 | return 0 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /015 Hashing 1/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework problems of this topic 2 | 3 | # Count Triangle problem: 4 | 5 | ![Count Triangle](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/015%20Hashing%201/img/IMG_20200312_155622.jpg) 6 | -------------------------------------------------------------------------------- /015 Hashing 1/img/IMG_20200312_155622.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/015 Hashing 1/img/IMG_20200312_155622.jpg -------------------------------------------------------------------------------- /015 Hashing 1/img/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the images used in this topic for better explanation 2 | 3 | 4 | ![count Triangle](IMG_20200312_155622.jpg) 5 | -------------------------------------------------------------------------------- /016 Hashing 2/A1 Replicating Substring.py: -------------------------------------------------------------------------------- 1 | Replicating Substring 2 | Given a string S, find if it is possible to re-order the characters of the string S so that it can be represented as a 3 | concatenation of K similar strings. Eg if S=aabb and K=2, then it is possible to re-arrange the string as "abab" which is a 4 | concatenation of 2 similar strings "ab". If it is possible, return 1, else return -1. 5 | 6 | Constraints: 7 | 1. 1 <= Length of S <= 1000 8 | 2. All the alphabets of S are lower case (a - z) 9 | 3. 1 <= K <= 1000 10 | 11 | Input: Integer K and string S Output: Your function should return 1 if it is possible to re-arrange the characters of the string S so that it can be represented as a concatenation of K similar strings. If it is not, return -1. Example: Input: 12 | K:2 13 | S:bbaabb 14 | 15 | Output: 16 | 1 17 | 18 | class Solution: 19 | def solve(self, k, s): 20 | 21 | freq = [0]*26 22 | 23 | for i in s: 24 | freq[ ord(i) - 97 ] += 1 25 | 26 | ans = 1 27 | for i in range(26): 28 | if freq[i] != 0: 29 | x = freq[i] 30 | if x%k != 0: 31 | ans = -1 32 | break 33 | 34 | return ans 35 | -------------------------------------------------------------------------------- /016 Hashing 2/HW1 Anagrams.cpp: -------------------------------------------------------------------------------- 1 | Anagrams 2 | Given an array of strings, return all groups of strings that are anagrams. 3 | Represent a group by a list of integers representing the index in the original list. Look at the sample case for clarification. 4 | 5 | Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', 6 | formed from 'rasp' Note: All inputs will be in lower-case. 7 | 8 | Example : 9 | Input : cat dog god tca 10 | Output : [[1, 4], [2, 3]] 11 | 12 | cat and tca are anagrams which correspond to index 1 and 4. dog and god are another set of anagrams 13 | which correspond to index 2 and 3. The indices are 1 based ( the first element has index 1 instead of index 0). 14 | 15 | Ordering of the result : You should not change the relative ordering of the words / phrases within the group. 16 | Within a group containing A[i] and A[j], A[i] comes before A[j] if i < j. 17 | 18 | 19 | 20 | vector > Solution::anagrams(const vector &A) { 21 | 22 | vector> ans; 23 | unordered_map> Map; 24 | string s; 25 | for(int i = 0; i < A.size(); i++){ 26 | s = A[i]; 27 | sort(s.begin(), s.end()); 28 | Map[s].push_back(i+1); 29 | } 30 | 31 | for(auto i : Map) 32 | ans.push_back(i.second); 33 | 34 | return ans; 35 | } 36 | -------------------------------------------------------------------------------- /016 Hashing 2/HW3 CompareSortedSubarrays.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A, vector > &B) { 2 | 3 | vector res; 4 | int n = A.size(); 5 | // Prefix Sum 6 | vector pre(n,0); 7 | pre[0] = A[0]; 8 | for (int i = 1 ; i < A.size(); i++) 9 | pre[i] = pre[i-1] + A[i]; 10 | 11 | 12 | 13 | for (int i = 0; i < B.size(); i++){ 14 | int ans = false; 15 | int l1 = B[i][0]; 16 | int r1 = B[i][1]; 17 | int l2 = B[i][2]; 18 | int r2 = B[i][3]; 19 | 20 | int sum1 = pre[r1]; 21 | if (l1 > 0) 22 | sum1 -= pre[l1-1]; 23 | 24 | int sum2 = pre[r2]; 25 | if (l2 > 0) 26 | sum2 -= pre[l2-1]; 27 | 28 | if (sum1 == sum2){ 29 | ans = true; 30 | unordered_map umap; 31 | for (int j = l1; j <= r1; j++) 32 | umap[ A[j] ]++; 33 | for (int j = l2; j <= r2; j++) 34 | umap[ A[j] ]--; 35 | 36 | for (auto itr = umap.begin(); itr != umap.end(); itr++) 37 | if (itr->second != 0) 38 | ans = false; 39 | } 40 | 41 | res.push_back(ans); 42 | } 43 | 44 | return res; 45 | } 46 | -------------------------------------------------------------------------------- /016 Hashing 2/README.md: -------------------------------------------------------------------------------- 1 | This folder includes all the assignment and homework of this topic 2 | -------------------------------------------------------------------------------- /017 String Algorithm/A2 reverseTheString.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Reverse the String 4 | Problem Description 5 | 6 | Given a string A of size N. 7 | 8 | Return the string A after reversing the string word by word. 9 | 10 | NOTE: 11 | 12 | A sequence of non-space characters constitutes a word. 13 | Your reversed string should not contain leading or trailing spaces, even if it is present in the input string. 14 | If there are multiple spaces between words, reduce them to a single space in the reversed string. 15 | 16 | 17 | Problem Constraints 18 | 1 <= N <= 3 * 105 19 | 20 | 21 | 22 | Input Format 23 | The only argument given is string A. 24 | 25 | 26 | 27 | Output Format 28 | Return the string A after reversing the string word by word. 29 | 30 | 31 | 32 | Example Input 33 | Input 1: 34 | A = "the sky is blue" 35 | Input 2: 36 | A = "this is ib" 37 | 38 | 39 | Example Output 40 | Output 1: 41 | "blue is sky the" 42 | Output 2: 43 | "ib is this" 44 | 45 | 46 | Example Explanation 47 | Explanation 1: 48 | We reverse the string word by word so the string becomes "the sky is blue". 49 | Explanation 2: 50 | We reverse the string word by word so the string becomes "this is ib" 51 | 52 | */ 53 | 54 | class Solution: 55 | # @param A : string 56 | # @return a strings 57 | def solve(self, A): 58 | 59 | A = A.split(' ') 60 | A = A[::-1] 61 | 62 | return ' '.join(A) 63 | -------------------------------------------------------------------------------- /017 String Algorithm/A3 reverseString.py: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse the String 3 | Problem Description 4 | Given a string A of size N. Return the string A after reversing the string word by word. NOTE: 5 | A sequence of non-space characters constitutes a word. 6 | Your reversed string should not contain leading or trailing spaces, even if it is present in the input string. 7 | If there are multiple spaces between words, reduce them to a single space in the reversed string. 8 | 9 | 10 | 11 | Problem Constraints 12 | 1 <= N <= 105 13 | 14 | 15 | Input Format 16 | The only argument given is string A. 17 | 18 | 19 | Output Format 20 | Return the string A after reversing the string word by word. 21 | 22 | 23 | Example Input 24 | Input 1: 25 | A = "the sky is blue" 26 | Input 2: 27 | A = "this is ib" 28 | 29 | 30 | Example Output 31 | Output 1: 32 | "blue is sky the" 33 | Output 2: 34 | "ib is this" 35 | 36 | 37 | Example Explanation 38 | Explanation 1: 39 | We reverse the string word by word so the string becomes "the sky is blue". 40 | 41 | 42 | */ 43 | 44 | class Solution: 45 | # @param A : string 46 | # @return a strings 47 | def solve(self, A): 48 | 49 | 50 | A = A.split() 51 | A = A[::-1] 52 | return ' '.join(A) 53 | 54 | -------------------------------------------------------------------------------- /017 String Algorithm/A4_boringSubstring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool checkBoring(string s){ 5 | bool flag = true; 6 | for (int i = 1; i < s.size(); ++i){ 7 | flag &= (abs(s[i] - s[i-1]) != 1); 8 | } 9 | return flag; 10 | } 11 | 12 | int solve(string A) { 13 | 14 | string odd = "", even =""; 15 | for (int i = 0; i < A.size(); ++i){ 16 | if (A[i]%2 == 0) 17 | even += A[i]; 18 | else 19 | odd += A[i]; 20 | } 21 | 22 | sort(even.begin(), even.end()); 23 | sort(odd.begin(), odd.end()); 24 | 25 | if (checkBoring(even + odd) || checkBoring(odd + even)) 26 | return 1; 27 | return 0; 28 | } 29 | 30 | int main(){ 31 | cout< 2 | using namespace std; 3 | 4 | int atoi(string str){ 5 | 6 | int sign = 1, base = 0, i = 0; 7 | while (str[i] == ' ') { i++; } 8 | 9 | if (str[i] == '-' || str[i] == '+') { 10 | sign = (str[i++] == '-') ? -1 : 1; 11 | } 12 | 13 | while (str[i] >= '0' && str[i] <= '9') { 14 | cout< INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { 16 | if (sign == 1) return INT_MAX; 17 | else return INT_MIN; 18 | } 19 | base = 10 * base + (str[i++] - '0'); 20 | } 21 | return base * sign; 22 | } 23 | 24 | int main(){ 25 | 26 | string s = "2147483646"; 27 | cout< 2 | using namespace std; 3 | 4 | string compute(string A, string B) 5 | { 6 | 7 | int n = A.size(), m = B.size(); 8 | int i = 1, j = 0; 9 | string temp; 10 | temp.push_back(A[0]); 11 | 12 | if (i < n && A[i] < B[j]) 13 | { 14 | temp.push_back(A[i++]); 15 | while (A[i] < B[j]) 16 | { 17 | temp.push_back(A[i++]); 18 | } 19 | temp.push_back(B[j]); 20 | } 21 | else 22 | { 23 | temp.push_back(B[j++]); 24 | while (j < m && B[j] < A[i]) 25 | { 26 | temp.push_back(B[j++]); 27 | } 28 | temp.push_back(A[i]); 29 | } 30 | 31 | return temp; 32 | } 33 | 34 | string smallestPrefix(string A, string B) 35 | { 36 | 37 | int n = A.size(), m = B.size(); 38 | int i = 0, j = 0; 39 | 40 | string ans1 = compute(A, B); 41 | string ans2 = compute(B, A); 42 | cout << "\n" 43 | << ans1 << " " << ans2; 44 | if (ans1.size() < ans2.size()) 45 | return ans1; 46 | return ans2; 47 | } 48 | 49 | int main() 50 | { 51 | 52 | string A = "ababa", B = "ahahahah"; 53 | cout << smallestPrefix(A, B); 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /017 String Algorithm/Notes.cpp: -------------------------------------------------------------------------------- 1 | // Given a string, find first non-repeating character 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Finding first non-repeating char 7 | 8 | char non(string str){ 9 | map m; 10 | 11 | for (int i = 0; i < str.size(); i++) 12 | m[ str[i] ]++; 13 | 14 | for (int i = 0; i < str.size(); i++) 15 | if ( m[str[i]] == 1) 16 | return str[i]; 17 | 18 | } 19 | 20 | int main(){ 21 | 22 | string s = "interviewbit"; 23 | 24 | cout<<"\n"<<"Result is "< 7 | using namespace std; 8 | 9 | bool anagram(string s1, string s2){ 10 | 11 | map m1; 12 | map m2; 13 | 14 | int n = s1.size(), m = s2.size(); 15 | 16 | if (n != m) 17 | return false; 18 | 19 | for (int i = 0; i < n; i++){ 20 | m1[ s1[i] ]++; 21 | m2[ s2[i] ]++; 22 | } 23 | 24 | if (m1 == m2) 25 | return true; 26 | else 27 | return false; 28 | } 29 | 30 | int main(){ 31 | string s1 = "abgcde"; 32 | string s2 = "gabdce"; 33 | 34 | cout< 2 | using namespace std; 3 | 4 | string reverse(string s){ 5 | int n = s.size(); 6 | 7 | for (int i = 0; i < n/2; i++) 8 | swap(s[i], s[n-i-1]); 9 | 10 | return s; 11 | } 12 | 13 | int main(){ 14 | 15 | string x = "the sky is blue"; 16 | stringstream s(x); 17 | string word; 18 | string res; 19 | 20 | while (s >> word){ 21 | res.append(reverse(word)+" "); 22 | } 23 | 24 | 25 | cout< st; 2 | int minEle; 3 | 4 | MinStack::MinStack() { 5 | while (!st.empty()) 6 | st.pop(); 7 | minEle = -1; 8 | } 9 | 10 | void MinStack::push(int x) { 11 | 12 | if (st.empty()){ 13 | st.push(x); 14 | minEle = x; 15 | } 16 | else if (x <= minEle){ 17 | st.push(2*x - minEle); 18 | minEle = x; 19 | } 20 | else 21 | st.push(x); 22 | } 23 | 24 | void MinStack::pop() { 25 | 26 | if (st.empty()) 27 | return; 28 | 29 | int x = st.top(); 30 | st.pop(); 31 | if (x < minEle) 32 | minEle = 2*minEle - x; 33 | 34 | } 35 | 36 | int MinStack::top() { 37 | if (st.empty()) 38 | return -1; 39 | 40 | int x = st.top(); 41 | if (x < minEle) 42 | return minEle; 43 | return x; 44 | } 45 | 46 | int MinStack::getMin() { 47 | if (st.empty()) 48 | return -1; 49 | return minEle; 50 | } 51 | 52 | 53 | /** 54 | * Your MinStack object will be instantiated and called as such: 55 | * MinStack* obj = new MinStack(); 56 | * obj->push(x); 57 | * obj->pop(); 58 | * int param_3 = obj->top(); 59 | * int param_4 = obj->getMin(); 60 | */ 61 | -------------------------------------------------------------------------------- /019 Stack 1/A2 Sort Stack using another stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort stack using another stack 3 | Given a stack of integers A, sort it using another stack. Return the array of integers after sorting the stack using another stack. 4 | Input Format 5 | The only argument given is the integer array A. 6 | Output Format 7 | Return the array of integers after sorting the stack using another stack. 8 | Constraints 9 | 1 <= length of the array <= 5000 10 | 0 <= A[i] <= 10^9 11 | For Example 12 | Input 1: 13 | A = [5, 4, 3, 2, 1] 14 | Output 1: 15 | [1, 2, 3, 4, 5] 16 | 17 | Input 2: 18 | A = [5, 17, 100, 11] 19 | Output 2: 20 | [5, 11, 17, 100] 21 | 22 | */ 23 | 24 | vector Solution::solve(vector &A) { 25 | 26 | vector temp; 27 | 28 | while (!A.empty()){ 29 | int x = A.back(); 30 | A.pop_back(); 31 | while (!temp.empty() && temp.back() > x){ 32 | A.push_back(temp.back()); 33 | temp.pop_back(); 34 | } 35 | temp.push_back(x); 36 | } 37 | 38 | return temp; 39 | } 40 | -------------------------------------------------------------------------------- /019 Stack 1/A4 maxFreqStack.cpp: -------------------------------------------------------------------------------- 1 | unordered_map freq; 2 | unordered_map> s; 3 | int maxFreq = 0; 4 | 5 | void push(int ele, vector &ans){ 6 | 7 | freq[ele]++; 8 | if (maxFreq < freq[ele]) 9 | maxFreq = freq[ele]; 10 | 11 | if (s.find(freq[ele]) != s.end() ){ // if stack exists 12 | s[freq[ele]].push(ele); 13 | } 14 | else{ 15 | stack st; 16 | st.push(ele); 17 | s[freq[ele]] = st; // key-> freq; val = stack 18 | } 19 | 20 | ans.push_back(-1); 21 | } 22 | 23 | void pop(vector &ans){ 24 | 25 | int maxFreqEle = s[maxFreq].top(); 26 | ans.push_back(maxFreqEle); 27 | s[maxFreq].pop(); 28 | 29 | if (s[maxFreq].empty()) 30 | maxFreq--; 31 | 32 | freq[maxFreqEle]--; 33 | 34 | } 35 | 36 | vector Solution::solve(vector > &A) { 37 | 38 | maxFreq = 0; 39 | freq.clear(); 40 | s.clear(); 41 | int n = A.size(); 42 | vector ans; 43 | 44 | for (int i = 0; i < n; i++){ 45 | if (A[i][0] == 1) 46 | push(A[i][1], ans); 47 | else 48 | pop(ans); 49 | } 50 | 51 | return ans; 52 | } 53 | -------------------------------------------------------------------------------- /019 Stack 1/HW! SimplifyDirectoryPath.py: -------------------------------------------------------------------------------- 1 | Simplify Directory Path 2 | 3 | Given a string A representing an absolute path for a file (Unix-style). 4 | Return the string A after simplifying the absolute path. Note: 5 | Absolute path always begin with '/' ( root directory ). 6 | Path will not have whitespace characters. 7 | 8 | Input Format 9 | The only argument given is string A. 10 | 11 | Output Format 12 | Return a string denoting the simplified absolue path for a file (Unix-style). 13 | 14 | For Example 15 | Input 1: 16 | A = "/home/" 17 | Output 1: 18 | "/home" 19 | 20 | Input 2: 21 | A = "/a/./b/../../c/" 22 | Output 2: 23 | "/c" 24 | 25 | 26 | 27 | class Solution: 28 | # @param A : string 29 | # @return a strings 30 | def simplifyPath(self, A): 31 | 32 | A = A.split('/') 33 | stack = [] 34 | 35 | for i in A: 36 | if i == '' or i == '.': 37 | continue 38 | 39 | elif i == '..': 40 | if (len(stack) != 0): 41 | stack.pop() 42 | 43 | else: 44 | stack.append(i) 45 | 46 | return '/'+'/'.join(stack) 47 | 48 | 49 | -------------------------------------------------------------------------------- /019 Stack 1/README.md: -------------------------------------------------------------------------------- 1 | This folder includes all the assignment and homework of this topic 2 | -------------------------------------------------------------------------------- /019 Stack 1/getMin.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | /** initialize your data structure here. */ 4 | vector st; 5 | vector minStack; 6 | 7 | MinStack() { 8 | st.clear(); 9 | minStack.clear(); 10 | } 11 | 12 | void push(int x) { 13 | st.push_back(x); 14 | if ( (minStack.size() == 0) || (minStack.back() >= x) ) 15 | minStack.push_back(x); 16 | } 17 | 18 | void pop() { 19 | if (st.size() == 0) 20 | return; 21 | int x = st.back(); 22 | st.pop_back(); 23 | if (minStack.back() == x) 24 | minStack.pop_back(); 25 | } 26 | 27 | int top() { 28 | if (st.size() == 0) 29 | return -1; 30 | return st.back(); 31 | } 32 | 33 | int getMin() { 34 | if (minStack.size() > 0) 35 | return minStack.back(); 36 | return -1; 37 | } 38 | }; 39 | 40 | /** 41 | * Your MinStack object will be instantiated and called as such: 42 | * MinStack* obj = new MinStack(); 43 | * obj->push(x); 44 | * obj->pop(); 45 | * int param_3 = obj->top(); 46 | * int param_4 = obj->getMin(); 47 | */ 48 | -------------------------------------------------------------------------------- /019 Stack 1/stackUsingSTL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void showstack(stack s){ 5 | cout<<"The stack is "; 6 | while (!s.empty()){ 7 | cout< s; 16 | 17 | s.push(10); 18 | s.push(100); 19 | s.push(1000); 20 | s.push(10000); 21 | 22 | showstack(s); 23 | cout<<"Size is "< Solution::solve(vector &A) { 33 | 34 | if(A.size()==0||A.size()==1) 35 | return A; 36 | 37 | int temp=A[0]; 38 | 39 | A.erase(A.begin()); 40 | 41 | solve(A); 42 | 43 | A.push_back(temp); 44 | 45 | 46 | return A; 47 | } 48 | -------------------------------------------------------------------------------- /020 Stack 2/HW2 RedundantBraces.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Redundant Braces 3 | 4 | Given a string A denoting an expression. It contains the following operators '+', '-', '*', '/'. 5 | Chech whether A has redundant braces or not. Return 1 if A has redundant braces, else return 0. 6 | 7 | Note: A will be always a valid expression. 8 | 9 | Input Format 10 | The only argument given is string A. 11 | Output Format 12 | Return 1 if string has redundant braces, else return 0. 13 | For Example 14 | Input 1: 15 | A = "((a + b))" 16 | Output 1: 17 | 1 18 | Explanation 1: 19 | ((a + b)) has redundant braces so answer will be 1. 20 | 21 | Input 2: 22 | A = "(a + (a + b))" 23 | Output 2: 24 | 0 25 | Explanation 2: 26 | (a + (a + b)) doesn't have have any redundant braces so answer will be 0. 27 | */ 28 | 29 | 30 | int Solution::braces(string A) { 31 | 32 | } 33 | int Solution::braces(string A) { 34 | 35 | stack st; 36 | 37 | for (auto i : A){ 38 | 39 | if (isalpha(i)) 40 | continue; 41 | 42 | if (i == '}' || i == ']' || i == ')'){ 43 | char ch = st.top(); 44 | if (ch == '(' || ch == '{' || ch == '[') 45 | return 1; 46 | else{ 47 | st.pop(); 48 | st.pop(); 49 | } 50 | 51 | } 52 | else 53 | st.push(i); 54 | } 55 | return 0; 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /020 Stack 2/HW3 prevSmallerEle.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::prevSmaller(vector &A) { 2 | 3 | int n = A.size(); 4 | if (n == 0) 5 | return {}; 6 | if (n == 1) 7 | return {-1}; 8 | 9 | stack s; 10 | s.push(0); 11 | int i = 1; 12 | vector ans; 13 | ans.push_back(-1); 14 | 15 | while (i < n) { 16 | while (!s.empty() && A[s.top()] >= A[i]) { 17 | s.pop(); 18 | } 19 | 20 | if (s.empty()) 21 | ans.push_back(-1); 22 | else 23 | ans.push_back(A[s.top()]); 24 | s.push(i); 25 | ++i; 26 | } 27 | 28 | return ans; 29 | } 30 | -------------------------------------------------------------------------------- /020 Stack 2/README.md: -------------------------------------------------------------------------------- 1 | This folder includes all the assignment and homework of this topic 2 | 3 | ## The below image is of the A1 Maximum Area under a Histogram: 4 | ### Input: 5 | ![image](img/histogram0.png)
6 | ### Output: Return the maximum area under the histogram:\ 7 | Here in this case it is 5*2 = 10 8 | ![image](img/histogram.png) 9 | 10 | -------------------------------------------------------------------------------- /020 Stack 2/img/README.md: -------------------------------------------------------------------------------- 1 | contains images 2 | -------------------------------------------------------------------------------- /020 Stack 2/img/histogram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/020 Stack 2/img/histogram.png -------------------------------------------------------------------------------- /020 Stack 2/img/histogram0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/020 Stack 2/img/histogram0.png -------------------------------------------------------------------------------- /021 Queue/A2 reverse1stBnumQ.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reversing the first B elements of queue 3 | 4 | Given an array of integers A and an integer B. we need to reverse the order of the first B elements of the array, 5 | leaving the other elements in the same relative order. Note: You are required to first insert elements into 6 | an auxiliary queue then perform Reversal of first B elements. 7 | 8 | Input Format 9 | The argument given is the integer array A and an integer B 10 | Output Format 11 | Return an array of integer after reversing the first k elements of A using queue 12 | 13 | Constraints 14 | 1 <= B <= length of the array <= 200000 15 | 1 <= A[i] <= 100000 16 | For Example 17 | Input 1: 18 | A = [1, 2, 3, 4, 5] 19 | B = 3 20 | Output 1: 21 | [3, 2, 1, 4, 5] 22 | 23 | Input 2: 24 | A = [5, 17, 100, 11] 25 | B = 2 26 | Output 2: 27 | [17, 5, 100, 11] 28 | 29 | */ 30 | 31 | vector Solution::solve(vector &A, int B) { 32 | 33 | queue q; 34 | int i = 0; 35 | for (i ; i < B; i++) 36 | q.push(A[i]); 37 | 38 | i--; 39 | 40 | while (i >= 0){ 41 | A[i] = q.front(); 42 | q.pop(); 43 | i--; 44 | } 45 | 46 | return A; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /021 Queue/A3 N123.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | N integers containing only 1,2 and 3 3 | 4 | Given an integer A. Find and Return first positive A integers in ascending order containing only digits 1,2 and 3. 5 | 6 | NOTE: all the A integers will fit in 32 bit integer. 7 | 8 | Input Format 9 | The only argument given is integer A. 10 | Output Format 11 | Find and Return first positive A integers in ascending order containing only digits 1,2 and 3. 12 | Constraints 13 | 1 <= A <= 29500 14 | For Example 15 | Input 1: 16 | A = 3 17 | Output 1: 18 | [1, 2, 3] 19 | 20 | Input 2: 21 | A = 7 22 | Output 2: 23 | [1, 2, 3, 11, 12, 13, 21] 24 | 25 | */ 26 | 27 | 28 | vector Solution::solve(int A) { 29 | 30 | queue q; 31 | 32 | vector ans; 33 | 34 | q.push(1); 35 | q.push(2); 36 | q.push(3); 37 | 38 | for (int i=0; i < A; i++){ 39 | 40 | int x = q.front(); 41 | ans.push_back(x); 42 | q.pop(); 43 | q.push(x*10+1); 44 | q.push(x*10+2); 45 | q.push(x*10+3); 46 | } 47 | 48 | return ans; 49 | } 50 | -------------------------------------------------------------------------------- /021 Queue/README.md: -------------------------------------------------------------------------------- 1 | This folder contain all assignments/homeworks of Queue topic 2 | -------------------------------------------------------------------------------- /021 Queue/slidingWindowMaximum.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sliding-window-maximum/ 2 | // Asked in Google for SDE-2 3 | // Can do it using DP but the charter of this problem is to use dequeue [DEQ] 4 | 5 | #include 6 | using namespace std; 7 | 8 | #include 9 | 10 | vector solve(vector &A, int k) 11 | { 12 | int _max = INT_MIN; 13 | vector ans; 14 | for (int i = 0; i < k; ++i) 15 | { 16 | _max = max(_max, A[i]); 17 | } 18 | ans.push_back(_max); 19 | deque dq; 20 | dq.push_back(_max); 21 | 22 | for (int i = k; i < A.size(); ++i) 23 | { 24 | if (dq.empty()) 25 | { 26 | dq.push_back(i); 27 | _max = A[i]; 28 | } 29 | else 30 | { 31 | while (!dq.empty() && A[dq.front()] < A[i]) 32 | { 33 | dq.pop_front(); 34 | } 35 | if (dq.empty()) 36 | { 37 | _max = A[i]; 38 | } 39 | else 40 | { 41 | _max = max(_max, A[i]); 42 | } 43 | dq.push_front(A[i]); 44 | ans.push_back(_max); 45 | } 46 | } 47 | 48 | return ans; 49 | } 50 | 51 | int main() 52 | { 53 | vector A{1, 3, -1, -3, 5, 3, 6, 7}; 54 | 55 | vector ans = solve(A, 3); 56 | 57 | for (int x : ans) 58 | cout << x << " "; 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /022 Linked List 1/DoubleLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *next; 7 | Node *prev; 8 | Node (int x){ 9 | data = x; 10 | next = NULL; 11 | prev = NULL; 12 | } 13 | }; 14 | 15 | 16 | void printDLL(Node *head){ 17 | 18 | while (head!= NULL){ 19 | cout<data<<" "; 20 | head = head->next; 21 | } 22 | cout<next = head; 29 | head->prev = temp; 30 | 31 | cout<<"Inesrtion\n"; 32 | printDLL(temp); 33 | 34 | 35 | return temp; 36 | } 37 | 38 | 39 | int main(){ 40 | 41 | Node *head = NULL; 42 | head = insertBegin(head, 20); 43 | head = insertBegin(head, 30); 44 | head = insertBegin(head, 40); 45 | printDLL(head); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /022 Linked List 1/HW2 removeDuplicatesSorted1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicates from Sorted List 3 | 4 | Problem Description 5 | Given a sorted linked list, delete all duplicates such that each element appear only once. 6 | 7 | 8 | Problem Constraints 9 | 0 <= length of linked list <= 1000000 10 | 11 | 12 | Input Format 13 | First argument is the head pointer of the linked list. 14 | 15 | 16 | Output Format 17 | Return the head pointer of the linked list after removing all duplicates. 18 | 19 | 20 | Example Input 21 | Input 1: 22 | 1->1->2 23 | Input 2: 24 | 1->1->2->3->3 25 | 26 | 27 | 28 | Example Output 29 | Output 1: 30 | 1->2 31 | Output 2: 32 | 1->2->3 33 | 34 | 35 | 36 | Example Explanation 37 | Explanation 1: 38 | each element appear only once in 1->2 39 | */ 40 | 41 | 42 | /** 43 | * Definition for singly-linked list. 44 | * struct ListNode { 45 | * int val; 46 | * ListNode *next; 47 | * ListNode(int x) : val(x), next(NULL) {} 48 | * }; 49 | */ 50 | ListNode* Solution::deleteDuplicates(ListNode* A) { 51 | 52 | ListNode *temp = A; 53 | 54 | while (temp!=NULL){ 55 | while (temp->next != NULL && temp->val == temp->next->val){ 56 | temp->next = temp->next->next; 57 | } 58 | temp = temp->next; 59 | } 60 | return A; 61 | } 62 | -------------------------------------------------------------------------------- /022 Linked List 1/HW3 middleNode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Middle element of linked list 3 | 4 | Given a linked list of integers. Find and return the middle element of the linked list. 5 | 6 | Note: If there are N nodes in the linked list and N is even then return the (N/2+1)th element. 7 | 8 | Input Format 9 | The only argument given head pointer of linked list. 10 | Output Format 11 | Return the middle element of the linked list. 12 | 13 | Constraints 14 | 1 <= length of the linked list <= 100000 15 | 1 <= Node value <= 10^9 16 | 17 | For Example 18 | Input 1: 19 | 1->2->3->4->5 20 | Output 1: 21 | 3 22 | 23 | Input 2: 24 | A = 1->5->6->2->3->4 25 | Output 2: 26 | 2 27 | */ 28 | 29 | 30 | 31 | /** 32 | * Definition for singly-linked list. 33 | * struct ListNode { 34 | * int val; 35 | * ListNode *next; 36 | * ListNode(int x) : val(x), next(NULL) {} 37 | * }; 38 | */ 39 | int Solution::solve(ListNode* A) { 40 | 41 | ListNode *slow = A, *fast = A; 42 | 43 | while (fast && fast->next){ 44 | slow = slow->next; 45 | fast = fast->next->next; 46 | } 47 | 48 | return slow->val; 49 | } 50 | -------------------------------------------------------------------------------- /022 Linked List 1/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved assignment & homework problems of this class 2 | -------------------------------------------------------------------------------- /022 Linked List 1/circularLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // We can traverse the whole list from any node 5 | // Insert at begin or end in O(1) by just maintaining one pointer 6 | // Can implement a queue 7 | // Implementing Scheduling algorithms like Round Robin 8 | 9 | 10 | struct Node{ 11 | int data; 12 | Node *next; 13 | Node (int x){ 14 | data = x; 15 | next = NULL; 16 | } 17 | }; 18 | 19 | 20 | // While inserting make sure that the last element points to the head 21 | 22 | int main(){ 23 | 24 | 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /022 Linked List 1/reverseKGroups.cpp: -------------------------------------------------------------------------------- 1 | 2 | Node *reverseLL(Node *head, Node *prev = NULL){ 3 | 4 | if (head == NULL) 5 | return prev; 6 | Node *next = head -> next; 7 | head -> next = prev; 8 | 9 | return reverseLL(next, head); 10 | } 11 | 12 | 13 | Node *reverseGroupsRecursive(Node *head, int k){ 14 | // If k <= no. of nodes in LL then kth node will be the head of the LL 15 | // If k > length of LL then after the first pass whatever 16 | // is the last node of LL you processed will be the head 17 | 18 | Node *ptr = head, *prev = head; 19 | int count = 0; 20 | 21 | while (count < k && ptr != NULL){ 22 | prev = ptr; 23 | ptr = ptr->next; 24 | count++; 25 | } 26 | 27 | if (count == k){ 28 | prev -> next = NULL; 29 | Node *newHead = reverseLL (head, NULL); 30 | head -> next = reverseGroupsRecursive(ptr, k); 31 | return newHead; 32 | } 33 | else 34 | { 35 | return head; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /022 Linked List 1/reverseKgroups.cpp: -------------------------------------------------------------------------------- 1 | 2 | Node *reverseLL(Node *head, Node *prev = NULL){ 3 | 4 | if (head == NULL) 5 | return prev; 6 | Node *next = head -> next; 7 | head -> next = prev; 8 | 9 | return reverseLL(next, head); 10 | } 11 | 12 | 13 | Node *reverseGroupsRecursive(Node *head, int k){ 14 | // If k <= no. of nodes in LL then kth node will be the head of the LL 15 | // If k > length of LL then after the first pass whatever 16 | // is the last node of LL you processed will be the head 17 | 18 | Node *ptr = head, *prev = head; 19 | int count = 0; 20 | 21 | while (count < k && ptr != NULL){ 22 | prev = ptr; 23 | ptr = ptr->next; 24 | count++; 25 | } 26 | 27 | if (count == k){ 28 | prev -> next = NULL; 29 | Node *newHead = reverseLL (head, NULL); 30 | head -> next = reverseGroupsRecursive(ptr, k); 31 | return newHead; 32 | } 33 | else 34 | { 35 | return head; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /023 Linked List 2/HW1 Remove Duplicates from Sorted List II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicates from Sorted List II 3 | 4 | Given a sorted linked list, delete all nodes that have duplicate numbers, 5 | leaving only distinct numbers from the original list. 6 | 7 | For example, 8 | Given 1->2->3->3->4->4->5, return 1->2->5. 9 | Given 1->1->1->2->3, return 2->3. 10 | */ 11 | 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * struct ListNode { 16 | * int val; 17 | * ListNode *next; 18 | * ListNode(int x) : val(x), next(NULL) {} 19 | * }; 20 | */ 21 | ListNode* Solution::deleteDuplicates(ListNode* A) { 22 | 23 | ListNode *dummyHead = new ListNode(0); 24 | dummyHead->next = A; 25 | ListNode *temp = A, *prev = dummyHead; 26 | 27 | while (temp != NULL){ 28 | 29 | bool flag = false; 30 | 31 | while (temp->next != NULL && temp->val == temp->next->val){ 32 | flag = true; 33 | temp->next = temp->next->next; 34 | } 35 | 36 | if (flag){ 37 | prev->next = temp->next; 38 | } 39 | else{ 40 | prev->next = temp; 41 | prev = temp; 42 | } 43 | 44 | temp = temp->next; 45 | } 46 | 47 | return dummyHead->next; 48 | } 49 | -------------------------------------------------------------------------------- /023 Linked List 2/HW2 removeDuplicatesSorted1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicates from Sorted List 3 | 4 | Problem Description 5 | Given a sorted linked list, delete all duplicates such that each element appear only once. 6 | 7 | 8 | Problem Constraints 9 | 0 <= length of linked list <= 1000000 10 | 11 | 12 | Input Format 13 | First argument is the head pointer of the linked list. 14 | 15 | 16 | Output Format 17 | Return the head pointer of the linked list after removing all duplicates. 18 | 19 | 20 | Example Input 21 | Input 1: 22 | 1->1->2 23 | Input 2: 24 | 1->1->2->3->3 25 | 26 | 27 | 28 | Example Output 29 | Output 1: 30 | 1->2 31 | Output 2: 32 | 1->2->3 33 | 34 | 35 | 36 | Example Explanation 37 | Explanation 1: 38 | each element appear only once in 1->2. 39 | */ 40 | 41 | 42 | 43 | /** 44 | * Definition for singly-linked list. 45 | * struct ListNode { 46 | * int val; 47 | * ListNode *next; 48 | * ListNode(int x) : val(x), next(NULL) {} 49 | * }; 50 | */ 51 | ListNode* Solution::deleteDuplicates(ListNode* A) { 52 | 53 | ListNode *temp = A; 54 | while (temp != NULL && temp->next != NULL){ 55 | 56 | if (temp->val == temp->next->val){ 57 | ListNode *x = temp->next; 58 | temp->next = x->next; 59 | free(x); 60 | } 61 | else 62 | temp = temp->next; 63 | 64 | } 65 | 66 | return A; 67 | } 68 | -------------------------------------------------------------------------------- /023 Linked List 2/README.md: -------------------------------------------------------------------------------- 1 | This folder includes all the assignment and homeworks for this topic 2 | -------------------------------------------------------------------------------- /023 Linked List 2/detectAndRemoveLoop.cpp: -------------------------------------------------------------------------------- 1 | void detectRemoveLoop (Node *head){ 2 | Node *slow = head, *fast = head; 3 | 4 | while (!fast && !fast->next){ 5 | slow =slow->next; 6 | fast = fast->next->next; 7 | if (slow == fast) 8 | break; 9 | } 10 | if (slow != fast) 11 | return; 12 | slow = head; 13 | while (slow->next != fast->next){ // Because we need to remove the loop 14 | slow = slow->next; 15 | fast = fast->next; 16 | } 17 | fast->next = NULL; // Removing loop by changing the next of last node (*fast ptr) to NULL 18 | 19 | } 20 | -------------------------------------------------------------------------------- /024 Trees 1/A3 InPost.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree From Inorder And Postorder 3 | 4 | Given inorder and postorder traversal of a tree, construct the binary tree. 5 | Note: You may assume that duplicates do not exist in the tree. 6 | Example : 7 | Input : 8 | Inorder : [2, 1, 3] 9 | Postorder : [2, 3, 1] 10 | 11 | Return : 12 | 1 13 | / \ 14 | 2 3 15 | */ 16 | 17 | 18 | /** 19 | * Definition for binary tree 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | 28 | 29 | unordered_map Imap; 30 | TreeNode* InPost(vector &inOrder, vector &postOrder, int is, int ie, int ps, int pe){ 31 | 32 | if (ie < is) 33 | return NULL; 34 | 35 | TreeNode *root = new TreeNode(postOrder[pe]); 36 | int index = Imap[root -> val]; 37 | 38 | root -> left = InPost(inOrder, postOrder, is, index-1, ps, ps+(index - is)-1); 39 | root -> right = InPost(postOrder, postOrder, index+1, ie, ps+(index-is), pe-1); 40 | 41 | return root; 42 | } 43 | 44 | TreeNode* Solution::buildTree(vector &A, vector &B) { 45 | 46 | // if (A.size() == 1){ 47 | // TreeNode *x = new TreeNode(A[0]); 48 | // return x; 49 | // } 50 | 51 | for (int i = 0; i < A.size(); i++) 52 | Imap[ A[i] ] = i; 53 | 54 | return InPost(A, B, 0, A.size()-1, 0, B.size()-1); 55 | } 56 | -------------------------------------------------------------------------------- /024 Trees 1/HW1 InPre.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given preorder and inorder traversal of a tree, construct the binary tree. 3 | Note: You may assume that duplicates do not exist in the tree. 4 | Example : 5 | Input : 6 | Preorder : [1, 2, 3] 7 | Inorder : [2, 1, 3] 8 | 9 | Return : 10 | 1 11 | / \ 12 | 2 3 13 | */ 14 | 15 | 16 | /** 17 | * Definition for binary tree 18 | * struct TreeNode { 19 | * int val; 20 | * TreeNode *left; 21 | * TreeNode *right; 22 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 23 | * }; 24 | */ 25 | unordered_map Imap; 26 | TreeNode* InPreTree(vector &inorder, vector &preorder, int is, int ie, int ps, int pe){ 27 | if (ie < is) 28 | return NULL; 29 | 30 | TreeNode *root = new TreeNode(preorder[ps]); 31 | int index = Imap[root -> val]; 32 | 33 | root -> left = InPreTree(inorder, preorder, is, index - 1, ps + 1, ps+(index-is)); 34 | root -> right = InPreTree(inorder, preorder, index+1, ie, ps + (index - is) + 1, pe); 35 | 36 | return root; 37 | } 38 | 39 | TreeNode* Solution::buildTree(vector &A, vector &B) { 40 | 41 | 42 | for (int i = 0; i < B.size(); i++) 43 | Imap[ B[i] ] = i; 44 | 45 | return InPreTree(B, A, 0, B.size()-1, 0, A.size()-1); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /024 Trees 1/HW4 ZigZagLeverOrder1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | vector > Solution::zigzagLevelOrder(TreeNode* A) { 11 | vector > ans; 12 | queue q; 13 | q.push(A); 14 | stack s; 15 | int reverse = 0; 16 | 17 | while (!q.empty()){ 18 | 19 | int size = q.size(); 20 | vector temp; 21 | for (int i = 0; i < size; i++){ 22 | TreeNode *curr = q.front(); 23 | q.pop(); 24 | if (reverse) 25 | s.push(curr); 26 | else 27 | temp.push_back(curr->val); 28 | if (curr->left) 29 | q.push(curr->left); 30 | if (curr->right) 31 | q.push(curr->right); 32 | } 33 | 34 | if (reverse){ 35 | while (!s.empty()){ 36 | TreeNode *curr = s.top(); 37 | temp.push_back(curr->val); 38 | s.pop(); 39 | } 40 | } 41 | ans.push_back(temp); 42 | reverse ^= 1; 43 | } 44 | 45 | return ans; 46 | } 47 | -------------------------------------------------------------------------------- /024 Trees 1/HW4 ZigZagLeverOrder2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | vector > Solution::zigzagLevelOrder(TreeNode* A) { 11 | 12 | vector> ans; 13 | stack s1, s2; 14 | s1.push(A); 15 | int toggle = 1; 16 | 17 | while (!s1.empty() || !s2.empty()){ 18 | 19 | vector temp; 20 | 21 | if (toggle){ 22 | while (!s1.empty()){ 23 | TreeNode *curr = s1.top(); 24 | s1.pop(); 25 | temp.push_back(curr->val); 26 | 27 | if (curr->left) 28 | s2.push(curr->left); 29 | if (curr->right) 30 | s2.push(curr->right); 31 | } 32 | } 33 | 34 | else{ 35 | while(!s2.empty()){ 36 | TreeNode *curr = s2.top(); 37 | s2.pop(); 38 | temp.push_back(curr->val); 39 | 40 | if (curr->right) 41 | s1.push(curr->right); 42 | if (curr->left) 43 | s1.push(curr->left); 44 | } 45 | } 46 | toggle ^= 1; 47 | ans.push_back(temp); 48 | } 49 | 50 | return ans; 51 | } 52 | -------------------------------------------------------------------------------- /024 Trees 1/README.md: -------------------------------------------------------------------------------- 1 | This folder contain all the solved homework and assignment problems for this topic 2 | -------------------------------------------------------------------------------- /024 Trees 1/TreeImplementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | }; 14 | 15 | int getMax(Node *root){ 16 | if (root == NULL) 17 | return INT_MIN; 18 | else 19 | return max(root->data, max(getMax(root->left), getMax(root->right))); 20 | 21 | } 22 | 23 | 24 | int main(){ 25 | 26 | Node *a = new Node(10); 27 | 28 | a->left = new Node(20); 29 | a->right = new Node(30); 30 | 31 | a->left->left = new Node(40); 32 | a->left->right = new Node(50); 33 | 34 | a->right->left = new Node(60); 35 | a->right->right = new Node(70); 36 | 37 | cout<<" \nMax is "< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | }; 14 | 15 | int height(Node *root){ 16 | 17 | if (!root) 18 | return -1; 19 | else 20 | return 1 + max( height( root->left ), height( root->right ) ); 21 | } 22 | 23 | int main(){ 24 | 25 | Node *a = new Node(10); 26 | 27 | a->left = new Node(20); 28 | a->right = new Node(30); 29 | 30 | a->left->left = new Node(40); 31 | a->left->right = new Node(50); 32 | 33 | a->right->left = new Node(60); 34 | a->right->right = new Node(70); 35 | 36 | cout<<" \nHeight of Binary Tree is "<< height(a); 37 | 38 | 39 | return 0; 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /024 Trees 1/getMax.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getMax(Node *root){ 5 | if (root == NULL) 6 | return INT_MIN; 7 | else 8 | return max(root->data, max(getMax(root->left), getMax(root->right))); 9 | 10 | } 11 | 12 | int main(){ 13 | 14 | Node *a = new Node(10); 15 | 16 | a->left = new Node(20); 17 | a->right = new Node(30); 18 | 19 | a->left->left = new Node(40); 20 | a->left->right = new Node(50); 21 | 22 | a->right->left = new Node(60); 23 | a->right->right = new Node(70); 24 | 25 | cout<<" \nMax is "< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | }; 14 | 15 | int getSize(Node *root){ 16 | 17 | if (!root) 18 | return 0; 19 | return 1 + getSize(root->left) + getSize(root->right); 20 | } 21 | 22 | int main(){ 23 | 24 | Node *a = new Node(10); 25 | 26 | a->left = new Node(20); 27 | a->right = new Node(30); 28 | 29 | a->left->left = new Node(40); 30 | a->left->right = new Node(50); 31 | 32 | a->right->left = new Node(60); 33 | a->right->right = new Node(70); 34 | 35 | cout<<" \nSize is "< s; 10 | 11 | while (!s.empty() || curr != NULL){ 12 | if (curr != NULL){ 13 | s.push (curr); 14 | curr = curr->right; 15 | } 16 | else{ 17 | curr = s.top(); 18 | s.pop(); 19 | cout << curr->data<< " "; 20 | curr = curr->left; 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /024 Trees 1/nodesAtKDist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | }; 14 | 15 | void printKDist(Node *root, int k){ 16 | 17 | if ( !root ) 18 | return; 19 | 20 | if ( k == 0 ) 21 | cout<data<<" "; 22 | 23 | else{ 24 | printKDist(root->left, k-1); 25 | printKDist(root->right, k-1); 26 | } 27 | } 28 | 29 | int main(){ 30 | 31 | Node *a = new Node(10); 32 | 33 | a->left = new Node(20); 34 | a->right = new Node(30); 35 | 36 | a->left->left = new Node(40); 37 | a->left->right = new Node(50); 38 | 39 | a->right->left = new Node(60); 40 | a->right->right = new Node(70); 41 | 42 | cout<<" \nNodes at 0 distance are "; 43 | printKDist(a, 0); // Root Node 44 | 45 | cout<<" \nNodes at 1 distance are "; 46 | printKDist(a, 1); // Level 1 47 | 48 | cout<<" \nNodes at 2 distance are "; 49 | printKDist(a, 2); // Level 2 50 | 51 | 52 | return 0; 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /024 Trees 1/preOrder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | }; 14 | 15 | 16 | void preOrder(Node *root) 17 | { 18 | stack s; 19 | Node *curr = root; 20 | s.push(curr); 21 | 22 | while ( s.empty() == false ) 23 | { 24 | Node *x = s.top(); 25 | s.pop(); 26 | 27 | if (x->right != NULL) 28 | s.push(x->right); 29 | 30 | if (x->left != NULL) 31 | s.push(x->left); 32 | 33 | cout<< x->data <<" "; 34 | 35 | } 36 | cout<data<<" "; 45 | preOrderRecursive(root->left); 46 | preOrderRecursive(root->right); 47 | } 48 | 49 | 50 | int main(){ 51 | 52 | Node *a = new Node(10); 53 | 54 | a->left = new Node(20); 55 | a->right = new Node(30); 56 | 57 | a->left->left = new Node(40); 58 | a->left->right = new Node(50); 59 | 60 | a->right->left = new Node(60); 61 | a->right->right = new Node(70); 62 | 63 | preOrder(a); // Using stack 64 | preOrderRecursive(a); // Using Recursion 65 | 66 | return 0; 67 | } 68 | 69 | -------------------------------------------------------------------------------- /024 Trees 1/rightView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | }; 14 | 15 | 16 | void preOrder(Node *root) 17 | { 18 | stack s; 19 | Node *curr = root; 20 | s.push(curr); 21 | 22 | while ( s.empty() == false ) 23 | { 24 | Node *x = s.top(); 25 | s.pop(); 26 | 27 | if (x->right != NULL) 28 | s.push(x->right); 29 | 30 | if (x->left != NULL) 31 | s.push(x->left); 32 | 33 | cout<< x->data <<" "; 34 | 35 | } 36 | cout<data<<" "; 45 | preOrderRecursive(root->left); 46 | preOrderRecursive(root->right); 47 | } 48 | 49 | 50 | int main(){ 51 | 52 | Node *a = new Node(10); 53 | 54 | a->left = new Node(20); 55 | a->right = new Node(30); 56 | 57 | a->left->left = new Node(40); 58 | a->left->right = new Node(50); 59 | 60 | a->right->left = new Node(60); 61 | a->right->right = new Node(70); 62 | 63 | preOrder(a); // Using stack 64 | preOrderRecursive(a); // Using Recursion 65 | 66 | return 0; 67 | } 68 | 69 | -------------------------------------------------------------------------------- /024 Trees 1/sumOfLeaves.cpp: -------------------------------------------------------------------------------- 1 | int sumLeaf(Node* root) 2 | { 3 | if (root == NULL) 4 | return 0; 5 | 6 | if (root->left == NULL && root->right == NULL) 7 | return root->data; 8 | 9 | return sumLeaf(root->left) + sumLeaf(root->right); 10 | } 11 | -------------------------------------------------------------------------------- /024 Trees 1/treeDiameter.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int height (TreeNode *root){ 13 | if (root == NULL) 14 | return 0; 15 | return 1 + max( height(root->left), height(root->right) ); 16 | } 17 | 18 | 19 | int diameterOfBinaryTree(TreeNode* root) { 20 | 21 | if (root == NULL) 22 | return 0; 23 | 24 | int d1 = height (root -> left) + height (root -> right); 25 | int d2 = diameterOfBinaryTree (root ->left); 26 | int d3 = diameterOfBinaryTree (root -> right); 27 | 28 | return max(d1, max(d2, d3)); 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /025 Trees 2/A1 isBalancedBST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | int height(TreeNode* A){ 12 | if (A == NULL) 13 | return -1; 14 | 15 | int lh = height(A->left); 16 | int rh = height(A->right); 17 | 18 | return max(lh, rh) + 1; 19 | } 20 | 21 | 22 | int Solution::isBalanced(TreeNode* A) { 23 | 24 | if (A == NULL) 25 | return 1; 26 | 27 | int lh = height(A->left); 28 | int rh = height(A->right); 29 | 30 | if (lh == -1 && rh == -1) 31 | return 1; 32 | 33 | return !(abs(lh-rh)>1) && isBalanced(A->left) && isBalanced(A->right); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /025 Trees 2/HW1 isSymmetric.cpp: -------------------------------------------------------------------------------- 1 | /*Symmetric Binary Tree 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | 4 | Example : 5 | 1 6 | / \ 7 | 2 2 8 | / \ / \ 9 | 3 4 4 3 10 | 11 | The above binary tree is symmetric. But the following is not: 12 | 1 13 | / \ 14 | 2 2 15 | \ \ 16 | 3 3 17 | 18 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 19 | */ 20 | 21 | /** 22 | * Definition for binary tree 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | 31 | int isSameTree ( TreeNode *A, TreeNode *B ){ 32 | 33 | if ( !A && !B ) 34 | return 1; 35 | 36 | if ( !A || !B ) 37 | return 0; 38 | 39 | return ( (A -> val) == (B -> val) ) && 40 | ( isSameTree ( A -> left, B -> right) ) && 41 | ( isSameTree ( A -> right, B -> left) ); 42 | 43 | } 44 | 45 | int Solution::isSymmetric(TreeNode* A) { 46 | 47 | if ( !A ) 48 | return 1; 49 | 50 | if ( A ){ 51 | if ( isSameTree( A -> left, A -> right ) ) 52 | return 1; 53 | } 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /025 Trees 2/HW2 areIdentical.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Identical Binary Trees 3 | Given two binary trees, write a function to check if they are equal or not. 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | 6 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 7 | 8 | Example : 9 | Input : 10 | 11 | 1 1 12 | / \ / \ 13 | 2 3 2 3 14 | 15 | Output : 16 | 1 or True 17 | */ 18 | 19 | 20 | 21 | /** 22 | * Definition for binary tree 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | int Solution::isSameTree(TreeNode* A, TreeNode* B) { 31 | 32 | if ( !A && !B ) 33 | return 1; 34 | 35 | if ( !A || !B ) 36 | return 0; 37 | 38 | return ( (A -> val) == (B -> val) ) && 39 | ( isSameTree ( A -> left, B -> left) ) && 40 | ( isSameTree ( A -> right, B -> right) ); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /025 Trees 2/README.md: -------------------------------------------------------------------------------- 1 | This folder contain all the solved homework and assignment problems for this topic 2 | -------------------------------------------------------------------------------- /026 BST/A2 validBST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Binary Search Tree 3 | 4 | Given a binary tree, determine if it is a valid binary search tree (BST). 5 | 6 | Assume a BST is defined as follows: 7 | The left subtree of a node contains only nodes with keys less than the node's key. 8 | The right subtree of a node contains only nodes with keys greater than the node's key. 9 | Both the left and right subtrees must also be binary search trees. 10 | 11 | Example : 12 | Input : 13 | 1 14 | / \ 15 | 2 3 16 | 17 | Output : 0 or False 18 | 19 | 20 | Input : 21 | 2 22 | / \ 23 | 1 3 24 | 25 | Output : 1 or True 26 | Return 0 / 1 ( 0 for false, 1 for true ) 27 | for this problem SOLUTION APPROACH : VIDEO : https://www.youtube.com/watch?v=yEwSGhSsT0U Complete solution in the hints. 28 | 29 | */ 30 | 31 | /** 32 | * Definition for binary tree 33 | * struct TreeNode { 34 | * int val; 35 | * TreeNode *left; 36 | * TreeNode *right; 37 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 38 | * }; 39 | */ 40 | 41 | 42 | bool isBST(TreeNode* root, int _min, int _max){ 43 | if (root == NULL) 44 | return true; 45 | 46 | return ((root->val > _min) && (root->val < _max) && (isBST(root->left, _min, root->val)) && (isBST(root->right, root->val, _max)) ); 47 | } 48 | 49 | int Solution::isValidBST(TreeNode* A) { 50 | if (isBST(A, INT_MIN, INT_MAX)) 51 | return 1; 52 | return 0; 53 | } 54 | 55 | -------------------------------------------------------------------------------- /026 BST/A3 kthSmallest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth Smallest Element In Tree 3 | 4 | Given a binary search tree, write a function to find the kth smallest element in the tree. 5 | 6 | Example : 7 | Input : 8 | 2 9 | / \ 10 | 1 3 11 | 12 | and k = 2 13 | 14 | Return : 2 15 | 16 | As 2 is the second smallest element in the tree. 17 | NOTE : You may assume 1 <= k <= Total number of nodes in BST 18 | */ 19 | 20 | 21 | /** 22 | * Definition for binary tree 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | 31 | TC: O(H+K) 32 | 33 | int cnt = 0; 34 | int small = 0; 35 | void printK(TreeNode* root, int k){ 36 | if (root != NULL){ 37 | printK(root->left, k); 38 | cnt++; 39 | if (cnt == k){ 40 | small = root->val; 41 | return; 42 | } 43 | printK(root->right, k); 44 | } 45 | } 46 | 47 | int Solution::kthsmallest(TreeNode* A, int B) { 48 | cnt = 0; 49 | small = 0; 50 | printK(A, B); 51 | 52 | return small; 53 | } 54 | -------------------------------------------------------------------------------- /026 BST/HW2 checkBSToneChild.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Check for BST with exactly one child of each internal nodes 4 | 5 | Given preorder traversal of a binary tree, check if it is possible that it is also a preorder traversal of a BST, 6 | where each internal node (non -leaf nodes) have exactly one child. 7 | 8 | CONSTRAINTS 9 | 1 <= N <= 100 10 | 11 | INPUT 12 | A : [ 4, 10, 5 ,8 ] 13 | 14 | OUTPUT 15 | YES 16 | 17 | EXPLANATION 18 | The possible BST is: 19 | 20 | 4 21 | \ 22 | 10 23 | / 24 | 5 25 | \ 26 | 8 27 | */ 28 | 29 | bool check(vector A, int curr, int low, int high){ 30 | if (curr == A.size()) 31 | return 1; 32 | 33 | if (A[curr] < low) return 0; 34 | if (A[curr] > high) return 0; 35 | 36 | bool a = check (A, curr+1, low, A[curr]); 37 | bool b = check (A, curr+1, A[curr], high); 38 | 39 | return a | b; 40 | } 41 | 42 | string Solution::solve(vector &A) { 43 | 44 | if (check(A, 0, INT_MIN, INT_MAX)) 45 | return "YES"; 46 | else 47 | return "NO"; 48 | 49 | } 50 | -------------------------------------------------------------------------------- /026 BST/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework solutions of this topic 2 | -------------------------------------------------------------------------------- /027 Problem On Trees/A3 invertTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Invert the Binary Tree 4 | Given a binary tree, invert the binary tree and return it. Look at the example for more details. 5 | Example : Given binary tree 6 | 7 | 1 8 | / \ 9 | 2 3 10 | / \ / \ 11 | 4 5 6 7 12 | invert and return 13 | 1 14 | / \ 15 | 3 2 16 | / \ / \ 17 | 7 6 5 4 18 | 19 | */ 20 | 21 | 22 | /** 23 | * Definition for binary tree 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 29 | * }; 30 | */ 31 | 32 | TreeNode* Solution::invertTree(TreeNode* A) { 33 | 34 | if (A == NULL) 35 | return A; 36 | 37 | TreeNode *mirrorLeft = invertTree (A->left); 38 | TreeNode *mirrorRight = invertTree (A->right); 39 | 40 | A->left = mirrorRight; 41 | A->right = mirrorLeft; 42 | 43 | return A; 44 | } 45 | -------------------------------------------------------------------------------- /027 Problem On Trees/HW2 flatterBT2LL1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | TreeNode* Solution::flatten(TreeNode* A) { 11 | TreeNode* root = A; 12 | 13 | while (root) { 14 | TreeNode* curr = root; 15 | TreeNode* temp = root->right; 16 | 17 | curr->right = curr->left; 18 | curr->left = NULL; 19 | while (curr->right) { 20 | curr = curr->right; 21 | } 22 | curr->right = temp; 23 | root = root->right; 24 | } 25 | 26 | return A; 27 | } 28 | -------------------------------------------------------------------------------- /027 Problem On Trees/HW2 flatterBT2LL2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | TreeNode* Solution::flatten(TreeNode* A) { 11 | TreeNode* root = A; 12 | 13 | while (root) { 14 | TreeNode* curr = root; 15 | TreeNode* temp = root->right; 16 | if (curr->left != NULL) { 17 | curr->right = curr->left; 18 | curr->left = NULL; 19 | while (curr->right) { 20 | curr = curr->right; 21 | } 22 | curr->right = temp; 23 | } 24 | root = root->right; 25 | } 26 | 27 | return A; 28 | } 29 | -------------------------------------------------------------------------------- /027 Problem On Trees/README.md: -------------------------------------------------------------------------------- 1 | # Convert Binary Tree to DLL: 2 | 3 | __Naive:__ 4 | 1) preorder and create a singly LL 5 | 2) Mark all the previous pointers by visiting each and every node 6 | 3) head->left = tail 7 | 4) tail->right = head 8 | Extra space for array 9 | 10 | __Recursive_Solution:__ Inplace converting binary tree 11 | 1) Convert Left sub tree to a DLL 12 | 2) Attach the last node of DLL to root 13 | 3) Convert Right sub tree to a DLL 14 | 4) concatenate left list and root then to right list 15 | 16 | 17 | ![image](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/027%20Problem%20On%20Trees/img/BT2DLL%20(1).jpg) 18 | ![rough work](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/027%20Problem%20On%20Trees/img/BT2DLL%20(2).jpg) 19 | -------------------------------------------------------------------------------- /027 Problem On Trees/img/BT2DLL (1).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/027 Problem On Trees/img/BT2DLL (1).jpg -------------------------------------------------------------------------------- /027 Problem On Trees/img/BT2DLL (2).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/027 Problem On Trees/img/BT2DLL (2).jpg -------------------------------------------------------------------------------- /028 Tries/README.md: -------------------------------------------------------------------------------- 1 | # TRIE Implementation: 2 | 3 | *Efficient* Re-__trie__-val of information 4 | 5 | R[problem_no] --> Remedial Class problems 6 | 7 | First refer [Binary tree implementation using 2d array](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/028%20Tries/BinaryTree2dArray.cpp), likewise, we're going to use this 2d matrix to represent nodes in trie to save memory and avoid MLE (Memory Overflow Error) 8 | 9 | ![2d matrix](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/028%20Tries/img/IMG_20200512_224826.jpg) 10 | 11 | In the above image you can look how the matrix looks after inserting 10, 6, 2, 18, 19, 15 in the BST. 12 | By implementing trie in such manner helps you to process the trie earlier and also the dynamic allocation is too slow to process. 13 | 14 | Refer [01 TRIE_best](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/028%20Tries/01%20TRIE_best.cpp) for the fastest implementation of TRIE 15 | -------------------------------------------------------------------------------- /028 Tries/img/IMG_20200512_224826.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/028 Tries/img/IMG_20200512_224826.jpg -------------------------------------------------------------------------------- /028 Tries/img/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the images used in [028 TRIE](https://github.com/FazeelUsmani/Scaler-Academy/tree/master/028%20Tries) 2 | -------------------------------------------------------------------------------- /029 Segment Trees/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the problems of this topic 2 | -------------------------------------------------------------------------------- /030 Heaps 1/HW2 BptsClosertoOrogin.cpp: -------------------------------------------------------------------------------- 1 | vector > Solution::solve(vector > &A, int B) { 2 | vector> v; 3 | int n = A.size(); 4 | for (int i = 0; i < n; ++i){ 5 | long long x=A[i][0]; 6 | long long y=A[i][1]; 7 | v.push_back({x*x+y*y, i}); 8 | } 9 | 10 | priority_queue< pair, vector >, greater > > minHeap(v.begin(), v.end()); 11 | 12 | vector> ans; 13 | for (int i = 0; i < B; ++i){ 14 | pair val = minHeap.top(); 15 | minHeap.pop(); 16 | vector temp = A[val.second]; 17 | ans.push_back(temp); 18 | } 19 | 20 | return ans; 21 | } 22 | -------------------------------------------------------------------------------- /030 Heaps 1/HW2 BptsClosest2Origin.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | bool compare(vector p1, vector p2){ 4 | int d1 = p1[0]*p1[0] + p1[1]*p1[1]; 5 | int d2 = p2[0]*p2[0] + p2[1]*p2[1]; 6 | 7 | return d1 < d2; 8 | } 9 | 10 | vector > Solution::solve(vector > &A, int B) { 11 | 12 | sort(A.begin(), A.end(), compare); 13 | priority_queue , compare> pq(A.begin(), A.end(), compare); 14 | 15 | vector> ans; 16 | 17 | while (A.size() - B){ 18 | A.pop_back(); 19 | } 20 | 21 | return A; 22 | } 23 | -------------------------------------------------------------------------------- /030 Heaps 1/PQArrayMax.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int arr[] = {10, 15, 4}; 7 | priority_queue pq(arr, arr+3); // For vector pass v.begin(), v.end() 8 | // This way is better instead of pushing elements one by one i.e. Build Heap 9 | // push and pop O(log N) 10 | // empty, size and top is O(1) 11 | 12 | while (!pq.empty()){ 13 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int arr[] = {10, 15, 4}; 7 | 8 | for (int &x : arr) 9 | x = -x; 10 | 11 | priority_queue pq(arr, arr+3); // For vector pass v.begin(), v.end() 12 | // This way is better instead of pushing elements one by one i.e. Build Heap 13 | // push and pop O(log N) 14 | // empty, size and top is O(1) 15 | 16 | while (!pq.empty()){ 17 | cout<<-pq.top()<<" "; 18 | pq.pop(); 19 | } 20 | 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /030 Heaps 1/README.md: -------------------------------------------------------------------------------- 1 | ## MIN HEAP: minimum ele at top 2 | 3 | __Insert:__ arr[size - 1] = x and upheapify O(log(size)) 4 | 5 | __Min Heapify:__ Similar to down heapify TC: O(log N) 6 | 7 | __Extract Min:__ O(1) time but to maintain the heap O(log N) for Min Heapify 8 | 9 | __decrease key/update key:__ O(log (h)) go on swapping with largest parents till oth index 10 | 11 | __Delete:__ We can do this in 2 steps: DecreaseKey (3, INT_MIN) and extract Min TC: O(log N) 12 | 13 | __Build Heap:__ Insert ele and then Min Heapify for all. TC: O(n) 14 | 15 | ![Build Heap Proof](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/030%20Heaps%201/img/IMG_20200525_224809.jpg) 16 | 17 | 18 | 19 | 20 | 21 | This folder contains all the solutions taught in Heap class 22 | 23 | -------------------------------------------------------------------------------- /030 Heaps 1/img/IMG_20200525_224809.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/030 Heaps 1/img/IMG_20200525_224809.jpg -------------------------------------------------------------------------------- /030 Heaps 1/img/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the images used in this class 2 | -------------------------------------------------------------------------------- /030 Heaps 1/inbuiltmaxHeap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | priority_queue pq; 7 | pq.push(10); 8 | pq.push(15); 9 | pq.push(4); 10 | 11 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | priority_queue, greater> pq; 7 | pq.push(10); 8 | pq.push(15); 9 | pq.push(4); 10 | 11 | cout< lo; // max heap 3 | priority_queue, greater> hi; // min heap 4 | 5 | public: 6 | // Adds a number into the data structure. 7 | void addNum(int num) 8 | { 9 | lo.push(num); // Add to max heap 10 | 11 | hi.push(lo.top()); // balancing step 12 | lo.pop(); 13 | 14 | if (lo.size() < hi.size()) { // maintain size property 15 | lo.push(hi.top()); 16 | hi.pop(); 17 | } 18 | } 19 | 20 | // Returns the median of current data stream 21 | double findMedian() 22 | { 23 | return lo.size() > hi.size() ? lo.top() : ((double) lo.top() + hi.top()) * 0.5; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /031 Heap 2/HW4 minLargestElement.cpp: -------------------------------------------------------------------------------- 1 | 2 | #define pp pair 3 | 4 | int Solution::solve(vector &A, int B) { 5 | 6 | int n = A.size(); 7 | priority_queue , greater > pq; 8 | 9 | vector state = A; 10 | 11 | for (int i = 0; i < n; ++i) 12 | pq.push({2*A[i], i}); 13 | 14 | while (B--){ 15 | pp temp = pq.top(); 16 | pq.pop(); 17 | state[temp.second] = temp.first; 18 | pq.push({state[temp.second]+A[temp.second], temp.second}); 19 | } 20 | 21 | int ans = INT_MIN; 22 | for (int i = 0; i < n; ++i) 23 | ans = max(ans, state[i]); 24 | 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /031 Heap 2/customHeap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Person{ 5 | int age; 6 | float ht; 7 | Person (int a, float h){ 8 | age = a; 9 | ht = h; 10 | } 11 | }; 12 | 13 | struct myCmp{ 14 | bool operator()(Person const &p1, Person const &p2){ 15 | return p1.ht < p2.ht; 16 | } 17 | }; 18 | 19 | int main(){ 20 | 21 | priority_queue, myCmp> pq; 22 | 23 | float arr[5][2] = { { 30, 5.5 }, { 25, 5 }, { 20, 6 }, { 33, 6.1 }, { 23, 5.6 } }; 24 | 25 | for (int i = 0; i < 5; ++i) { 26 | pq.push(Person(arr[i][0], arr[i][1])); 27 | } 28 | 29 | while (!pq.empty()){ 30 | Person p = pq.top(); 31 | pq.pop(); 32 | cout< &A) { 4 | 5 | int n = A.size(); 6 | int up = 0, down = 0, ret = 1, peak = 0; 7 | 8 | for (int i = 1; i < n; ++i){ 9 | if (A[i-1] < A[i]){ 10 | peak = ++up; 11 | down = 0; 12 | ret += 1+up; 13 | } 14 | else if (A[i-1] == A[i]){ 15 | up = 0; 16 | down = 0; 17 | peak = 0; 18 | ret += 1; 19 | } 20 | else{ 21 | up = 0; 22 | down++; 23 | ret += 1 + down; 24 | if (peak >= down) 25 | ret += -1; 26 | } 27 | } 28 | 29 | return ret; 30 | } 31 | -------------------------------------------------------------------------------- /032 Greedy 1/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homeworks and assignments of this session 2 | -------------------------------------------------------------------------------- /033 Greedy 2/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homeworks and assignments of this session 2 | -------------------------------------------------------------------------------- /034 Dynamic Programming (1D DP)/A1 Stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Stairs 4 | 5 | Problem Description 6 | 7 | You are climbing a stair case and it takes A steps to reach to the top. 8 | 9 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 10 | 11 | 12 | 13 | Problem Constraints 14 | 1 <= A <= 36 15 | 16 | 17 | 18 | Input Format 19 | The first and the only argument contains an integer A, the number of steps. 20 | 21 | 22 | 23 | Output Format 24 | Return an integer, representing the number of ways to reach the top. 25 | 26 | 27 | 28 | Example Input 29 | Input 1: 30 | 31 | A = 2 32 | Input 2: 33 | 34 | A = 3 35 | 36 | 37 | Example Output 38 | Output 1: 39 | 40 | 2 41 | Output 2: 42 | 43 | 3 44 | 45 | 46 | Example Explanation 47 | Explanation 1: 48 | 49 | Distinct ways to reach top: [1, 1], [2]. 50 | Explanation 2: 51 | 52 | Distinct ways to reach top: [1 1 1], [1 2], [2 1]. 53 | 54 | */ 55 | 56 | int Solution::climbStairs(int n) { 57 | 58 | if (n == 1) 59 | return 1; 60 | if (n == 2) 61 | return 2; 62 | 63 | int ans = 0, prev1 = 1, prev2 = 1; 64 | 65 | for (int i = 2; i <= n; ++i){ 66 | ans = prev1 + prev2; 67 | prev2 = prev1; 68 | prev1 = ans; 69 | } 70 | 71 | return ans; 72 | } 73 | -------------------------------------------------------------------------------- /034 Dynamic Programming (1D DP)/A3 minNumSquares.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Minimum Number of Squares 4 | Problem Description 5 | 6 | Given an integer A. Return minimum count of numbers, sum of whose squares is equal to A. 7 | 8 | 9 | 10 | Problem Constraints 11 | 1 <= A <= 105 12 | 13 | 14 | 15 | Input Format 16 | First and only argument is an inetegr A. 17 | 18 | 19 | 20 | Output Format 21 | Return an integer denoting the minimum count. 22 | 23 | 24 | 25 | Example Input 26 | Input 1: 27 | 28 | A = 6 29 | Input 2: 30 | 31 | A = 5 32 | 33 | 34 | Example Output 35 | Output 1: 36 | 37 | 3 38 | Output 2: 39 | 40 | 2 41 | 42 | 43 | Example Explanation 44 | Explanation 1: 45 | 46 | Possible combinations are : (12 + 12 + 12 + 12 + 12 + 12) and (12 + 12 + 22). 47 | Minimum count of numbers, sum of whose squares is 6 is 3. 48 | Explanation 2: 49 | 50 | We can represent 5 using only 2 numbers i.e. 12 + 22 = 5 51 | */ 52 | 53 | int Solution::countMinSquares(int A) { 54 | 55 | int ans[A+1] = {0}; 56 | ans[1] = 1; 57 | 58 | for (int i = 2; i <= A; i++){ 59 | ans[i] = i; 60 | for (int j = 1; j*j <= i; j++){ 61 | ans[i] = min(ans[i], 1 + ans[i- j*j]); 62 | } 63 | } 64 | 65 | return ans[A]; 66 | } 67 | -------------------------------------------------------------------------------- /034 Dynamic Programming (1D DP)/A5 FibonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int *dp; 6 | 7 | int fib(int n){ 8 | if (dp[n] == -1){ 9 | int res; 10 | if (n == 0 || n == 1) 11 | return n; 12 | else 13 | res = fib(n-1)+fib(n-2); 14 | dp[n] = res; 15 | } 16 | 17 | return dp[n]; 18 | } 19 | 20 | 21 | int main() { 22 | 23 | int n; 24 | cin>>n; 25 | dp = new int[n+1]; 26 | for (int i = 0; i <= n; i++) 27 | dp[i] = -1; 28 | 29 | cout< 2 | using namespace std; 3 | 4 | int fib(int n){ 5 | 6 | int f[n+1]; 7 | f[0] = 0; 8 | f[1] = 1; 9 | for (int i = 2; i <= n; i++) 10 | f[i] = f[i-1] + f[i-2]; 11 | 12 | return f[n]; 13 | } 14 | 15 | 16 | int main() { 17 | 18 | int n; 19 | cin>>n; 20 | 21 | cout< &A, int B, int C, int D) { 2 | 3 | int n = A.size(); 4 | vector left(n, 0), right(n, 0); 5 | 6 | left[0] = B*A[0]; 7 | for (int i = 1; i < n; i++) 8 | left[i] = max(left[i-1], B*A[i]); 9 | 10 | right[n-1] = D*A[n-1]; 11 | for (int i = n-2; i >= 0; i--) 12 | right[i] = max(right[i+1], D*A[i]); 13 | 14 | int ans = INT_MIN; 15 | for (int i = 0; i < n; i++){ 16 | ans = max(ans, left[i] + C*A[i] + right[i]); 17 | } 18 | 19 | return ans; 20 | } 21 | -------------------------------------------------------------------------------- /034 Dynamic Programming (1D DP)/README.md: -------------------------------------------------------------------------------- 1 | ## Dynamic Programming: 2 | 3 | 4 | There are around 8 patterns of Dynamic Programming: [Read it here](https://leetcode.com/discuss/general-discussion/458695/Dynamic-Programming-Patterns). This may help you to gain some insignts to identify a problem which can be solved using DP. I know it comes after practice but this will definitely help. 5 | 6 | We can also do [HW4 Maximumsum](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/034%20Dynamic%20Programming%20(1D%20DP)/HW4%20MaximumSum.cpp) by creating [left and right max arrays](https://www.geeksforgeeks.org/given-array-three-numbers-maximize-x-ai-y-aj-z-ak/) by which we can achieve O(N) space complexity. Big O notation is same but space is optimized a bit from 3*N --> N 7 | 8 | Here is the code: [[optimized] HW4 MaximumSum](https://github.com/FazeelUsmani/Scaler-Academy/blob/master/034%20Dynamic%20Programming%20(1D%20DP)/HW4%20maximumSum1.cpp) 9 | 10 | But this approach fails when we have more than 3 integers i.e. (B, C, D, E, F....). So, its better to have a look at both of them 11 | 12 | -------------------------------------------------------------------------------- /035 Dynamic Programming 2/A1 UniquePathGrid.cpp: -------------------------------------------------------------------------------- 1 | int Solution::uniquePathsWithObstacles(vector > &A) { 2 | 3 | int row = A.size(); 4 | int col = A[0].size(); 5 | 6 | if (A[0][0] == 1 || A[row-1][col-1] == 1) 7 | return 0; 8 | 9 | int uPath[row][col]; 10 | 11 | for (int i = 0; i < row; ++i){ 12 | for (int j = 0; j < col; ++j){ 13 | uPath[i][j] = 0; 14 | 15 | if (i == 0 && j == 0) 16 | uPath[i][j] = 1; 17 | 18 | if (A[i][j]) 19 | continue; 20 | 21 | if (i > 0) 22 | uPath[i][j] += uPath[i-1][j]; 23 | 24 | if (j > 0) 25 | uPath[i][j] += uPath[i][j-1]; 26 | } 27 | } 28 | 29 | return uPath[row-1][col-1]; 30 | } 31 | -------------------------------------------------------------------------------- /035 Dynamic Programming 2/A1 UniquePathGrid1.cpp: -------------------------------------------------------------------------------- 1 | int Solution::uniquePathsWithObstacles(vector > &A) { 2 | 3 | int row = A.size(); 4 | int col = A[0].size(); 5 | 6 | if (A[0][0] == 1 || A[row-1][col-1] == 1) 7 | return 0; 8 | 9 | int uPath[row][col]; 10 | 11 | for (int i = 0; i < row; ++i){ 12 | for (int j = 0; j < col; ++j){ 13 | uPath[i][j] = 0; 14 | 15 | if (i == 0 && j == 0) 16 | uPath[i][j] = 1; 17 | 18 | if (A[i][j]) 19 | continue; 20 | 21 | if (i > 0) 22 | uPath[i][j] += uPath[i-1][j]; 23 | 24 | if (j > 0) 25 | uPath[i][j] += uPath[i][j-1]; 26 | } 27 | } 28 | 29 | return uPath[row-1][col-1]; 30 | } 31 | -------------------------------------------------------------------------------- /035 Dynamic Programming 2/A2 RegularExpMatch.cpp: -------------------------------------------------------------------------------- 1 | int Solution::isMatch(const string s, const string p) { 2 | 3 | int n = s.length(), m = p.length(); 4 | 5 | if (m == 0) 6 | return (n == 0); 7 | 8 | vector> match(n+1, vector (m+1, 0)); 9 | match[0][0] = 1; 10 | 11 | for (int j = 1; j <= m; ++j) 12 | if (p[j-1] == '*') 13 | match[0][j] = match[0][j-1]; 14 | 15 | 16 | for (int i = 1; i <= n; ++i){ 17 | for (int j = 1; j <= m; ++j){ 18 | 19 | if (p[j-1] == '*') 20 | match[i][j] = match[i][j-1] || match[i-1][j]; 21 | 22 | else if (p[j-1] == '?' || s[i-1] == p[j-1]) 23 | match[i][j] = match[i-1][j-1]; 24 | 25 | else 26 | match[i][j] = 0; 27 | 28 | } 29 | } 30 | 31 | return match[n][m]; 32 | } 33 | -------------------------------------------------------------------------------- /035 Dynamic Programming 2/A3 minSumPath.cpp: -------------------------------------------------------------------------------- 1 | int m = A.size(), n = A[0].size(); 2 | 3 | cout<> minSum(m, vector (n, 0)); 6 | 7 | for (int i = 0; i < m; ++i){ 8 | for (int j = 0; j < n; ++j){ 9 | int sum = 0; 10 | if (i == 0 || j == 0){ 11 | if (i == 0 && j == 0){ 12 | minSum[i][j] = A[i][j]; 13 | } 14 | else if (i == 0){ 15 | minSum[i][j] = A[i][j] + minSum[i][j-1]; 16 | } 17 | else if (j == 0){ 18 | minSum[i][j] = A[i][j] + minSum[i-1][j]; 19 | } 20 | } 21 | 22 | else 23 | { 24 | minSum[i][j] = A[i][j] + min(minSum[i-1][j], minSum[i][j-1]); 25 | } 26 | } 27 | } 28 | /* 29 | for (int i = 0; i < m; ++i){ 30 | for (int j = 0; j < n; ++j){ 31 | cout<> find_all_palindromes(const string& text) { 3 | int n = text.size(); 4 | vector> palindromes(n, vector(n, false)); 5 | 6 | for(int i = n - 1; i >= 0; i--) { 7 | for(int j = i; j < n; j++) { 8 | if(i == j) { 9 | palindromes[i][j] = true; 10 | } 11 | else if(text[i] == text[j]) { 12 | if(j - i == 1) { 13 | palindromes[i][j] = true; 14 | } 15 | else { 16 | palindromes[i][j] = palindromes[i + 1][j - 1]; 17 | } 18 | } 19 | } 20 | } 21 | 22 | return palindromes; 23 | } 24 | 25 | // Time - O(N^2), Space - O(N^2) 26 | int Solution::minCut(string A) { 27 | int n = A.size(); 28 | if(n == 0) { 29 | return 0; 30 | } 31 | 32 | vector> palindromes = find_all_palindromes(A); 33 | vector dp(n); 34 | 35 | for(int i = 0; i < n; i++) { 36 | dp[i] = INT_MAX; 37 | if(palindromes[0][i]) { 38 | dp[i] = 0; 39 | } 40 | else { 41 | for(int j = i; j > 0; j--) { 42 | if(palindromes[j][i]) { 43 | dp[i] = min(dp[j - 1] + 1, dp[i]); 44 | } 45 | } 46 | } 47 | } 48 | 49 | return dp[n - 1]; 50 | } 51 | -------------------------------------------------------------------------------- /036 Dynamic Programming 3/HW1 dungeonPrincess.cpp: -------------------------------------------------------------------------------- 1 | int Solution::calculateMinimumHP(vector > &A) { 2 | 3 | int m = A.size(), n = A[0].size(); 4 | if (m == 0 || n == 0) 5 | return 0; 6 | 7 | 8 | for (int i = m-1; i >= 0; --i) { 9 | for (int j = n-1; j >= 0; --j) { 10 | 11 | if (i == m-1 && j == n-1) 12 | A[i][j] = max(1, 1-A[i][j]); 13 | 14 | else if (i == m-1) 15 | A[i][j] = max(1, A[i][j+1] - A[i][j]); 16 | 17 | else if (j == n-1) 18 | A[i][j] = max(1, A[i+1][j] - A[i][j]); 19 | 20 | else 21 | A[i][j] = max(1, min(A[i][j+1], A[i+1][j]) - A[i][j]); 22 | } 23 | } 24 | 25 | return A[0][0]; 26 | } 27 | -------------------------------------------------------------------------------- /036 Dynamic Programming 3/HW2 repeatingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | string v; 2 | bool ok; 3 | int memo[1002][1002]; 4 | 5 | int dp(int i,int j,int s){ 6 | if(ok)return 1; 7 | if(s==2){ 8 | ok=true; 9 | return 1; 10 | } 11 | if(i==v.size()||j==v.size())return -(1<<30); 12 | if(memo[i][j])return memo[i][j]; 13 | for(int k=j;ki)return memo[i][j]=max(dp(i+1,k+1,s+1),dp(i+1,j,s)); 15 | } 16 | return memo[i][j]=dp(i+1,j,s); 17 | } 18 | 19 | 20 | int Solution::anytwo(string A) { 21 | ok=false; 22 | memset(memo,0,sizeof(memo)); 23 | v=A; 24 | int uso=dp(0,0,0); 25 | return ok; 26 | } 27 | -------------------------------------------------------------------------------- /036 Dynamic Programming 3/HW3 lengthLongestFibonacciSubsequence.cpp: -------------------------------------------------------------------------------- 1 | int lenLongestFibSubseq(vector& A) { 2 | int N = A.size(); 3 | unordered_map index; 4 | for (int i = 0; i < N; ++i) 5 | index[A[i]] = i; 6 | 7 | unordered_map longest; 8 | int ans = 0; 9 | for (int k = 0; k < N; ++k) 10 | for (int j = 0; j < k; ++j) { 11 | if (A[k] - A[j] < A[j] && index.count(A[k] - A[j])) { 12 | int i = index[A[k] - A[j]]; 13 | longest[j * N + k] = longest[i * N + j] + 1; 14 | ans = max(ans, longest[j * N + k] + 2); 15 | } 16 | } 17 | 18 | return (ans >= 3) ? ans : 0; 19 | } 20 | 21 | int Solution::solve(vector &A) { 22 | return lenLongestFibSubseq(A); 23 | } 24 | -------------------------------------------------------------------------------- /036 Dynamic Programming 3/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homework and assignment solutions of this class 2 | -------------------------------------------------------------------------------- /037 Dynamic Programming 4/A2_minSumPathTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minimumTotal(vector> &A) 5 | { 6 | 7 | int m = A.size(); 8 | int n = A[m - 1].size(); 9 | 10 | for (int i = m - 2; i >= 0; --i) 11 | { 12 | for (int j = 0; j <= i; ++j) 13 | { 14 | if (A[i + 1][j] < A[i + 1][j + 1]) 15 | { 16 | A[i][j] += A[i + 1][j]; 17 | } 18 | else 19 | { 20 | A[i][j] += A[i + 1][j + 1]; 21 | } 22 | } 23 | } 24 | 25 | for (int i = 0; i < m; ++i) 26 | { 27 | for (int j = 0; j < n; ++j) 28 | { 29 | cout << A[i][j] << " "; 30 | } 31 | cout << endl; 32 | } 33 | 34 | return A[0][0]; 35 | } 36 | 37 | int main() 38 | { 39 | 40 | vector> A{{2}, {6, 6}, {7, 8, 4}}; 41 | cout << minimumTotal(A); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /037 Dynamic Programming 4/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homework and assignment solutions of this class 2 | -------------------------------------------------------------------------------- /038 Dynamic Programming 5/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homework and assignment solutions of this class 2 | -------------------------------------------------------------------------------- /039 Dynamic Programming 6/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homework and assignment solutions of this class 2 | -------------------------------------------------------------------------------- /040 Dynamic Programming 7/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the homework and assignment solutions of this class 2 | -------------------------------------------------------------------------------- /041 Dynamic Programming 8/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework solutions taught in this class 2 | -------------------------------------------------------------------------------- /042 Dynamic Programming 9/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the assignment and homework solutions of this class. 2 | 3 | These following are the discussed problems in the class: 4 | 5 | 1) [Super Egg Drop](https://leetcode.com/problems/super-egg-drop/) 6 | 7 | 2) [Minimum Number of Refueling Stops](https://leetcode.com/problems/minimum-number-of-refueling-stops/) 8 | 9 | 3) [k Inverse paris array](https://leetcode.com/problems/k-inverse-pairs-array/) 10 | 11 | -------------------------------------------------------------------------------- /043 Dynamic Programming Problems/README.md: -------------------------------------------------------------------------------- 1 | This day the class didn't happened but asked us to do the following probles: 2 | 3 | 4 | 1) [Number of Valid Strings](https://leetcode.com/discuss/interview-question/353317/Google-or-Onsite-or-Number-of-Valid-Strings) 5 | 6 | 2) [Min Deletions to make Palindrome](https://leetcode.com/discuss/interview-question/371677/Google-or-Onsite-or-Min-Deletions-to-Make-Palindrome) 7 | 8 | 3) [Form String A from Suffix of String B](https://leetcode.com/discuss/interview-question/365191/Google-or-Onsite-or-Form-String-A-from-suffix-of-String-B) 9 | 10 | 4) [Remove at most K element to make array increasing](https://leetcode.com/discuss/interview-question/412366/Google-or-Onsite-or-Remove-at-most-K-element-to-make-array-increasing) 11 | -------------------------------------------------------------------------------- /044 Graphs 1/A3_anotherBFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int solve(int A, vector > &B, int C, int D){ 5 | 6 | if (C == D) 7 | return 0; 8 | 9 | vector > > adj(A); 10 | 11 | for (vector x : B){ 12 | adj[x[0]].push_back({x[1], x[2]}); 13 | adj[x[1]].push_back({x[0], x[2]}); 14 | } 15 | 16 | vector > q (2*A); 17 | bool visited[A] = {false}; 18 | q[0].push(C); 19 | 20 | for (int i = 0; i < 2*A; ++i){ 21 | 22 | while (!q[i].empty()){ 23 | int front = q[i].front(); 24 | q[i].pop(); 25 | if (front == D) 26 | return i; 27 | 28 | if (!visited[front]){ 29 | visited[front] = true; 30 | for (pair p : adj[front]){ 31 | if (!visited[p.first]){ 32 | q[i + p.second].push(p.first); 33 | visited[p.first]; 34 | } 35 | } 36 | } 37 | } 38 | } 39 | 40 | return -1; 41 | } 42 | 43 | int main(){ 44 | 45 | vector > B { {3,11,2}, {5,12,1}, {0,7,2}, {5,6,2}, {6,10,1}, {5,9,1} }; 46 | int A = 13, C = 9, D = 4; 47 | 48 | cout< 2 | using namespace std; 3 | 4 | vector g[1111111]; 5 | pair ans; // storing {distance, node}; 6 | 7 | void dfs(int v, int parent = -1, int distance = 0){ 8 | 9 | if (distance > ans.first){ 10 | ans = {distance, v}; 11 | } 12 | 13 | for (int i = 0; i < g[v].size(); ++i){ 14 | int to = g[v][i]; 15 | if (to != parent){ 16 | dfs(to, v, distance+1); 17 | } 18 | } 19 | } 20 | 21 | 22 | int diameterTreeusingGraph(vector &A){ 23 | 24 | 25 | for (int i = 0; i < A.size(); ++i){ 26 | if (A[i] != -1){ 27 | g[A[i]].push_back(i); 28 | g[i].push_back(A[i]); 29 | } 30 | } 31 | 32 | int v = 0; 33 | ans = {-1, -1}; 34 | dfs(v); 35 | v = ans.second; 36 | dfs(v); 37 | 38 | return ans.first; 39 | } 40 | 41 | int main(){ 42 | 43 | vector A{-1,0,0,0,2,3,5}; 44 | cout< x, vector y){ 18 | 19 | return x[2] < y[2]; 20 | } 21 | 22 | int Solution::solve(int A, vector > &B) { 23 | 24 | if (B.size() == 1) 25 | return B[0][2]; 26 | 27 | sort(B.begin(), B.end(), myCmp); 28 | 29 | int parent[A+1], size[A+1]; 30 | 31 | for (int i = 0; i <= A; ++i){ 32 | parent[i] = i; 33 | size[i] = 1; 34 | } 35 | 36 | int i = 0, cost = 0, edgeCnt = 0; 37 | 38 | while ( (i < B.size()) && (edgeCnt + 1 < B.size()) ){ 39 | int c = find(parent, B[i][0]); 40 | int d = find(parent, B[i][1]); 41 | 42 | if (c != d){ 43 | if (size[c] < size[d]) 44 | swap(c, d); 45 | 46 | parent[d] = c; 47 | size[c] += size[d]; 48 | cost += B[i][2]; 49 | edgeCnt++; 50 | } 51 | ++i; 52 | } 53 | 54 | return cost; 55 | } 56 | -------------------------------------------------------------------------------- /047 Graphs 4/README.md: -------------------------------------------------------------------------------- 1 | In this class, we discussed UNION FIND algorithm and Kruskal's algorithm and solved some related problems 2 | 3 | This folder contains all the assignment and homework solutions of this class. 4 | -------------------------------------------------------------------------------- /047 Graphs 4/UNION_FIND.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int find(int parent[], int node){ // Path functions 5 | if (node == parent[node]) 6 | return node; 7 | parent[node] = find(parent, parent[node]); 8 | 9 | return parent[node]; 10 | } 11 | 12 | void addEdge(int x, int y, int parent[], int size[]){ // union 13 | 14 | int c = find(parent, x); 15 | int d = find(parent, y); 16 | 17 | if (c != d){ 18 | if (size[c] < size[d]) 19 | swap(c, d); 20 | parent[d] = c; 21 | size[c] += size[d]; 22 | } 23 | } 24 | 25 | 26 | int main(){ 27 | 28 | int n = 5; 29 | int parent[n+1], size[n+1]; 30 | 31 | for (int i = 0; i <= n; ++i){ 32 | parent[i] = i; 33 | size[i] = 1; 34 | } 35 | 36 | addEdge(1, 2, parent, size); // add Edge 37 | addEdge(2, 3, parent, size); 38 | addEdge(4, 6, parent, size); 39 | addEdge(6, 5, parent, size); 40 | 41 | // 2 sets containing 1 2 3 & 4 5 6 42 | 43 | return 0; 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /048 Graphs 5/A1 preReqCourses.cpp: -------------------------------------------------------------------------------- 1 | const int maxn = 100000; 2 | int vis[maxn]; 3 | int in[maxn]; 4 | vector adj[maxn]; 5 | 6 | int Solution::solve(int A, vector &B, vector &C) { 7 | 8 | memset(vis, 0, sizeof(vis)); 9 | memset(in, 0, sizeof(in)); 10 | for (int i = 0; i < maxn; ++i) 11 | adj[i].clear(); 12 | 13 | for (int i = 0; i < B.size(); ++i){ 14 | adj[B[i]].push_back(C[i]); 15 | } 16 | 17 | for (int i = 1; i <= A; ++i){ 18 | for (int x : adj[i]){ 19 | in[x]++; 20 | } 21 | } 22 | 23 | queue q; 24 | for (int i = 1; i <= A; ++i){ 25 | if (in[i] == 0){ 26 | q.push(i); 27 | vis[i] = 1; 28 | } 29 | } 30 | 31 | int ans = 0; 32 | while (!q.empty()){ 33 | int temp = q.front(); 34 | q.pop(); 35 | ans++; 36 | for (int x : adj[temp]){ 37 | in[x]--; 38 | if (in[x] == 0 && !vis[x]){ 39 | q.push(x); 40 | vis[x] = 1; 41 | } 42 | } 43 | } 44 | 45 | if (ans == A) 46 | return 1; 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /048 Graphs 5/A3 detectCycle.cpp: -------------------------------------------------------------------------------- 1 | const int maxn = 100009; 2 | int vis[maxn]; 3 | int recStack[maxn]; 4 | vector adj[maxn]; 5 | 6 | bool isCyclic(int v){ 7 | 8 | if (vis[v] == 0){ 9 | vis[v] = 1; 10 | recStack[v] = 1; 11 | 12 | for (int edge: adj[v]){ 13 | if (!vis[edge] && isCyclic(edge)) 14 | return true; 15 | else if (recStack[edge]) 16 | return true; 17 | } 18 | } 19 | recStack[v] = 0; 20 | return false; 21 | } 22 | 23 | 24 | int Solution::solve(int A, vector > &B) { 25 | memset(vis, 0, sizeof(vis)); 26 | memset(recStack, 0, sizeof(recStack)); 27 | for (int i = 0; i < maxn; ++i) 28 | adj[i].clear(); 29 | 30 | for (auto it : B) 31 | adj[it[0]].push_back(it[1]); 32 | int flag = 0; 33 | for (int i = 1; i <= A; ++i){ 34 | if (vis[i] == 0 && isCyclic(i)) 35 | return 1; 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /048 Graphs 5/A3_LexTopologicalSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector solve(int A, vector > &B) { 5 | 6 | vector adj[A+1]; 7 | 8 | for (auto i : B){ 9 | adj[i[0]].push_back(i[1]); 10 | } 11 | 12 | int in[A+1] = {0}; 13 | for (int i = 1; i <= A; ++i){ 14 | for (int x : adj[i]){ 15 | in[x]++; 16 | } 17 | } 18 | 19 | priority_queue , greater > pq; 20 | int vis[A+1] = {0}; 21 | for (int i = 1; i <= A; ++i){ 22 | if (in[i] == 0){ 23 | pq.push(i); 24 | vis[i] = 1; 25 | } 26 | } 27 | 28 | vector ans; 29 | while (!pq.empty()){ 30 | 31 | int temp = pq.top(); 32 | pq.pop(); 33 | ans.push_back(temp); 34 | 35 | sort(adj[temp].begin(), adj[temp].end()); 36 | 37 | for (int x : adj[temp]){ 38 | in[x]--; 39 | if (!vis[x] && in[x] == 0){ 40 | pq.push(x); 41 | vis[x] = 1; 42 | } 43 | } 44 | } 45 | 46 | return ans; 47 | } 48 | 49 | int main(){ 50 | int A = 6; 51 | vector > B { {6, 3}, {6, 1}, {5, 1}, {5, 2}, {3, 4}, {4, 2} }; 52 | 53 | for (int x : solve(A,B)) 54 | cout< 2 | using namespace std; 3 | 4 | vector g[6]; 5 | 6 | void addEdge(int u, int v){ 7 | g[u].push_back(v); 8 | } 9 | 10 | void topologicalSort(){ 11 | int in[6] = {0}; 12 | 13 | for (int i = 0; i < 6; ++i){ 14 | for (int x : g[i]){ 15 | in[x]++; 16 | } 17 | } 18 | 19 | for (int i = 0; i < 6; ++i) 20 | cout< q; 25 | for (int i = 0; i < 6; ++i){ 26 | if (in[i] == 0){ 27 | q.push(i); 28 | vis[i] = 1; 29 | } 30 | } 31 | 32 | while (!q.empty()){ 33 | int front = q.front(); 34 | q.pop(); 35 | cout< "; 36 | for (int x : g[front]){ 37 | in[x]--; 38 | if (in[x] == 0 && !vis[x]){ 39 | q.push(x); 40 | vis[x] = 1; 41 | } 42 | } 43 | } 44 | 45 | } 46 | 47 | int main(){ 48 | 49 | addEdge(4, 1); 50 | addEdge(4, 0); 51 | addEdge(5, 0); 52 | addEdge(5, 2); 53 | addEdge(2, 3); 54 | addEdge(3, 1); 55 | 56 | topologicalSort(); 57 | 58 | for (int i = 0; i < 6; ++i){ 59 | cout< "; 60 | for (int x : g[i]){ 61 | cout< > &A) { 2 | 3 | sort(A.begin(), A.end()); 4 | priority_queue , greater > pq; 5 | 6 | pq.push(A[0][1]); 7 | int rooms = 1; 8 | 9 | for (int i = 1; i < A.size(); ++i){ 10 | if (A[i][0] < pq.top()) 11 | rooms++; 12 | else 13 | pq.pop(); 14 | pq.push(A[i][1]); 15 | } 16 | 17 | return rooms; 18 | } 19 | -------------------------------------------------------------------------------- /050 Practice/01 MISC/3 pickFromBothSides.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | 3 | int maxSum = INT_MIN; 4 | int sum = 0; 5 | int n = A.size(); 6 | 7 | for (int i = n - 1; i >= n-B; --i){ 8 | sum += A[i]; 9 | } 10 | maxSum = max(maxSum, sum); 11 | int i = 0, j = n - B; 12 | 13 | while (j < n){ 14 | sum = sum - A[j++] + A[i++]; 15 | maxSum = max(maxSum, sum); 16 | } 17 | 18 | return maxSum; 19 | } 20 | -------------------------------------------------------------------------------- /050 Practice/01 MISC/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the problems taught in this class 2 | -------------------------------------------------------------------------------- /050 Practice/02 MISC/2 littlePonyAndPartitionSort.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) { 2 | 3 | int n = A.size(); 4 | vector maxLeft(n, 0), minRight(n, 0); 5 | 6 | int currMax = INT_MIN; 7 | for (int i = 0; i < n; ++i){ 8 | maxLeft[i] = max(currMax, A[i]); 9 | currMax = max(currMax, maxLeft[i]); 10 | } 11 | 12 | int currMin = INT_MAX; 13 | for (int i = n-1; i >= 0; --i){ 14 | minRight[i] = min(currMin, A[i]); 15 | currMin = min(currMin, minRight[i]); 16 | } 17 | 18 | int partitions = 1; 19 | for (int i = 0; i < n-1; ++i){ 20 | if (maxLeft[i] <= minRight[i+1]){ 21 | partitions++; 22 | } 23 | } 24 | 25 | 26 | return partitions; 27 | } 28 | -------------------------------------------------------------------------------- /050 Practice/02 MISC/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the practice problems 2 | -------------------------------------------------------------------------------- /050 Practice/03 MISC/1 countTotalSetBits.cpp: -------------------------------------------------------------------------------- 1 | int kerninghan(int n){ 2 | int cnt = 0; 3 | while (n > 0){ 4 | n = (n & (n-1) ); 5 | cnt++; 6 | } 7 | return cnt; 8 | } 9 | 10 | int Solution::solve(int A) { 11 | int ans = 0; 12 | 13 | for (int i = 1; i <= A; ++i){ 14 | ans += kerninghan(i); 15 | } 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /050 Practice/03 MISC/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all practice problems 2 | -------------------------------------------------------------------------------- /050 Practice/04 DP Remedial/1_maxCoinsInALine.cpp: -------------------------------------------------------------------------------- 1 | int Solution::maxcoin(vector &A) { 2 | 3 | int n = A.size(); 4 | int i, x, y, z; 5 | vector > maxVal(n, vector (n, 0)); 6 | 7 | for (int k = 0; k < n; ++k){ 8 | for (int j = k; j < n; ++j){ 9 | i = j-k; 10 | 11 | x = 0; 12 | if ((i+2)<=j) 13 | x = maxVal[i+2][j]; 14 | 15 | y = 0; 16 | if ((i+1) <= (j-1)) 17 | y = maxVal[i+1][j-1]; 18 | 19 | z = 0; 20 | if (i<=(j-2)) 21 | z = maxVal[i][j-2]; 22 | 23 | maxVal[i][j] = max(A[i]+min(x,y), A[j]+min(y,z)); 24 | } 25 | } 26 | 27 | return maxVal[0][n-1]; 28 | } 29 | -------------------------------------------------------------------------------- /050 Practice/04 DP Remedial/2_maxFruits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int solve(vector &A, int B) { 5 | 6 | 7 | long long n = A.size(); 8 | long long maxFruits[n] = {0}; 9 | maxFruits[0] = max(0, A[0]); 10 | 11 | for (int i = 1; i <= B; ++i) 12 | maxFruits[i] = max(maxFruits[i-1], A[i]); 13 | 14 | for (long long i = B+1; i < n; ++i){ 15 | maxFruits[i] = max(maxFruits[i-B+1]+A[i], maxFruits[i-1]); 16 | } 17 | 18 | return maxFruits[n-1]; 19 | } 20 | 21 | 22 | int main(){ 23 | 24 | vector A {1, 2, -3, -5, 4, 6, -3, 2, -1, 2 }; 25 | cout<<"Ans is "< 2 | using namespace std; 3 | 4 | int maxCuts(int A, vector &B){ 5 | 6 | 7 | int maxCut[A+1]; 8 | maxCut[0] = 0; 9 | int i, j; 10 | 11 | for (i = 1; i <= A; ++i){ 12 | int maxVal = INT_MIN; 13 | for (j = 0; j < i; ++j) 14 | maxVal = max(maxVal, B[j] + maxCut[i-j-1]); 15 | maxCut[i] = maxVal; 16 | } 17 | 18 | return maxCut[A]; 19 | } 20 | 21 | int main(){ 22 | 23 | int A = 5; 24 | vector B{3,7,7,10,12}; 25 | cout< > &arr) { 2 | 3 | int m=arr.size(),n=arr[0].size(); 4 | vector > dp(m,vector(n)); 5 | for(int i=0;i=0;i--){ 9 | for(int j=0;j n-k) 9 | k = n-k; 10 | 11 | for (int i = 0; i < k; ++i){ 12 | res *= (n-i); 13 | res /= (i+1); 14 | } 15 | 16 | return res; 17 | } 18 | 19 | int Solution::numTrees(int A) { 20 | 21 | // Use below formula to calculate catalan number in O(N) time 22 | // C_n=\frac{1}{n+1}\binom{2n}{n} 23 | // ans = [1/(n+1)]*[(2nCn)] 24 | 25 | ll c = binomialCoeff(2*A, A); 26 | 27 | return c/(A+1); 28 | } 29 | -------------------------------------------------------------------------------- /050 Practice/05 DP 2 (Remedial)/03_maxCoinTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int dp[100]; 5 | 6 | void dfs(vector &a, vector v[], int u, int parent){ 7 | 8 | dp[u] = a[u-1]; 9 | 10 | int maximum = 0; 11 | for (int child : v[u]) { 12 | 13 | if (child == parent) 14 | continue; 15 | 16 | dfs(a, v, child, u); 17 | 18 | maximum = max(maximum, dp[child]); 19 | } 20 | 21 | dp[u] += maximum; 22 | } 23 | 24 | 25 | int solve(vector &A, vector &B) { 26 | 27 | cout<<"woehoi"; 28 | vector adj[A.size()]; 29 | 30 | for (int i = 0; i < A.size(); ++i){ 31 | adj[A[i]].push_back(B[i]); 32 | adj[B[i]].push_back(A[i]); 33 | } 34 | 35 | dfs (A, adj, 1, 0); 36 | 37 | return dp[1]; 38 | } 39 | 40 | 41 | int main(){ 42 | 43 | vector A{0,1,1,2,2,3}, B{3,1000,5,1,3,10}; 44 | cout< 2 | using namespace std; 3 | 4 | vector ans; 5 | void bfs(int n, int m, int num){ 6 | queue q; 7 | q.push(num); 8 | 9 | while (!q.empty()){ 10 | int stepNum = q.front(); 11 | q.pop(); 12 | 13 | if (stepNum >= n && stepNum <= m) 14 | ans.push_back(stepNum); 15 | 16 | if (num == 0 || stepNum > m) 17 | continue; 18 | 19 | int lastDigit = stepNum%10; 20 | int stepNumA = stepNum*10 + (lastDigit-1); 21 | int stepNumB = stepNum*10 + (lastDigit+1); 22 | 23 | if (lastDigit==0) 24 | q.push(stepNumA); 25 | else if (lastDigit==9) 26 | q.push(stepNumB); 27 | else{ 28 | q.push(stepNumA); 29 | q.push(stepNumB); 30 | } 31 | } 32 | } 33 | 34 | 35 | int main(){ 36 | 37 | ans.clear(); 38 | int n = 20, m = 300; 39 | for (int i = n; i < m; ++i) 40 | bfs(n, m, i); 41 | 42 | sort(ans.begin(), ans.end()); 43 | 44 | for (int &x: ans) 45 | cout< 2 | using namespace std; 3 | 4 | bool isStepNum(int N){ 5 | int prevNum = -1, currNum; 6 | while (N){ 7 | currNum = N%10; 8 | if (prevNum == -1) 9 | prevNum = currNum; 10 | else{ 11 | if (abs(currNum-prevNum) != 1) 12 | return false; 13 | } 14 | prevNum = currNum; 15 | N /= 10; 16 | } 17 | return true; 18 | } 19 | 20 | vector stepnum(int A, int B) { 21 | 22 | vector res; 23 | for (int i = A; i <= B; ++i){ 24 | if (isStepNum(i)){ 25 | res.push_back(i); 26 | } 27 | } 28 | 29 | return res; 30 | } 31 | 32 | int main(){ 33 | vector res = stepnum(20, 50); 34 | for (int &x: res) 35 | cout< 2 | using namespace std; 3 | 4 | vector ans; 5 | vector > stick { {}, {}, {1}, {7}, {4}, {2,3,5}, {0,6,9}, {8} }; 6 | 7 | void recurse(int N, string curr){ 8 | if (N < 0) 9 | return; 10 | 11 | if (N == 0){ 12 | ans.push_back(curr); 13 | return; 14 | } 15 | 16 | for (int i = 2; i <= min(N, 7); ++i){ 17 | for (int j = 0; j < stick[i].size(); ++j){ 18 | if (stick[i][j] == 0 && curr.size() == 0){ 19 | } 20 | else{ 21 | curr.push_back(char('0' + stick[i][j])); 22 | recurse(N-i, curr); 23 | curr.pop_back(); 24 | } 25 | } 26 | } 27 | } 28 | 29 | bool myCmp(string a, string b){ 30 | long long x = stoi(a); 31 | long long y = stoi(b); 32 | 33 | return x < y; 34 | } 35 | 36 | vector solve(int A) { 37 | ans.clear(); 38 | recurse(A, ""); 39 | cout<<"executer "; 40 | sort(ans.begin(), ans.end(), myCmp); 41 | 42 | return ans; 43 | } 44 | 45 | int main(){ 46 | 47 | vector x = solve(9); 48 | 49 | for (string a: x) 50 | cout< 2 | using namespace std; 3 | 4 | void tsp(vector arr, int n, int cost, int &mncost, 5 | int count, bool vis[], int pos) 6 | { 7 | if (count == n) 8 | { 9 | cost += arr[pos][0]; 10 | if (cost < mncost) 11 | mncost = cost; 12 | return; 13 | } 14 | for (int i = 1; i < n; i++) 15 | { 16 | if (arr[pos][i] > 0 && !vis[i]) 17 | { 18 | vis[i] = true; 19 | tsp(arr, n, cost + arr[pos][i], mncost, count + 1, vis, i); 20 | vis[i] = false; 21 | } 22 | } 23 | } 24 | 25 | int Solution::solve(int A, vector &B) 26 | { 27 | bool vis[A]; 28 | for (int i = 0; i < A; i++) 29 | vis[i] = false; 30 | vis[0] = true; 31 | int cost = 0, mncost = INT_MAX; 32 | int count = 1, pos = 0; 33 | tsp(B, A, 0, mncost, count, vis, pos); 34 | 35 | return mncost; 36 | } 37 | 38 | int main() 39 | { 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /052 DP with Bitmasking 2/README.MD: -------------------------------------------------------------------------------- 1 | # DP with BitMasking 2 2 | 3 | This folder contains all the assignments and homework problems of **DP with Bitmasking** topic 4 | -------------------------------------------------------------------------------- /053 Digit DP/README.MD: -------------------------------------------------------------------------------- 1 | # Digit DP 2 | 3 | I recommend to see the following resources for **digit DP** 4 | 5 | 1. Digit DP blog on Codeforces by [flash_7](https://codeforces.com/blog/entry/53960) 6 | 2. Digit DP (Iterative) blog on Codeforces by [Jon.Snow](https://codeforces.com/blog/entry/77096) 7 | 3. Video by [Go code on YT](https://www.youtube.com/watch?v=Pa4YwO8B8-w) 8 | -------------------------------------------------------------------------------- /Contests/01 Contest/01 PairSumDivisibleB.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pair Sum divisible by M 3 | Problem Description 4 | Given an array of integers A and an integer B, find and return the number of pairs in A whose sum is divisible by B. 5 | Since the answer may be large, return the answer modulo (109 + 7). 6 | 7 | 8 | Problem Constraints 9 | 1 <= length of the array <= 100000 10 | 1 <= A[i] <= 109 11 | 1 <= B <= 106 12 | 13 | 14 | Input Format 15 | The first argument given is the integer array A. 16 | The second argument given is the integer B. 17 | 18 | 19 | Output Format 20 | Return the total number of pairs for which the sum is divisible by B modulo (109 + 7). 21 | 22 | 23 | Example Input 24 | Input 1: 25 | A = [1, 2, 3, 4, 5] 26 | B = 2 27 | Input 2: 28 | A = [5, 17, 100, 11] 29 | B = 28 30 | 31 | 32 | 33 | Example Output 34 | Output 1: 35 | 4 36 | Output 2: 37 | 1 38 | 39 | 40 | 41 | Example Explanation 42 | Explanation 1: 43 | All pairs which are divisible by 2 are (1,3),(1,5),(2,4),(3,5). 44 | So total 4 pairs. 45 | */ 46 | 47 | 48 | 49 | int Solution::solve(vector &A, int B) { 50 | int n = A.size(); 51 | int cnt = 0; 52 | for (int i = 0; i < n-1; i++){ 53 | for (int j = i+1; j < n; j++){ 54 | int sum = A[i]+A[j]; 55 | if (sum % B == 0){ 56 | cnt = (cnt + 1) % 1000000007; 57 | } 58 | 59 | } 60 | } 61 | return cnt; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Contests/01 Contest/02 powersOf3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Powers of 3 4 | 5 | Problem Description 6 | Given a positive integer A. Return an array of minimum length whose elements represent the powers of 3 and 7 | he sum of all the elements is equal to A. NOTE: If A cannot be represented as the sum of powers of 3, 8 | then return an array containing only -1. 9 | 10 | 11 | Problem Constraints 12 | 1 <= A <= 109 13 | 14 | 15 | Input Format 16 | Single argument is an integer A. 17 | 18 | 19 | Output Format 20 | Return an array of minimum length of powers of 3 whose elements sums to A. 21 | 22 | 23 | Example Input 24 | Input 1: 25 | 13 26 | Input 2: 27 | 3 28 | 29 | 30 | Example Output 31 | Output 1: 32 | [1, 3, 9] 33 | Output 2: 34 | [3] 35 | 36 | 37 | Example Explanation 38 | Explanation 1: 39 | 30 = 1, 31 = 3, 32 = 9. 40 | Also, 1 + 3 + 9 = 13. Here A = 13 which can be represented as the sum of 1, 3 and 9. 41 | */ 42 | 43 | class Solution: 44 | # @param A : integer 45 | # @return a list of integers 46 | 47 | def solve(self, A): 48 | 49 | if A<3: 50 | return [-1] 51 | 52 | ans = [] 53 | 54 | for i in range(30,-1,-1): 55 | 56 | x = 3**i 57 | 58 | while A-x>=0: 59 | A -= x 60 | ans.append(x) 61 | 62 | 63 | return ans 64 | 65 | 66 | -------------------------------------------------------------------------------- /Contests/01 Contest/03 KSmallestTriplet.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Similar to the Matrix Median problem 3 | Binary Search + finding the smallest element 4 | O(log(high-low)) 5 | isPossible --> O(N^2 log N) 6 | 7 | Note: Prefix aray will help in linear computations but here we've 3 pointers. 8 | */ 9 | 10 | bool isPossible(vector &A, int mid, int B){ 11 | 12 | int n = A.size(); 13 | int cnt = 0; 14 | for (int i = 0; i < n; i++){ 15 | for (int j = i+1; j < n; j++){ 16 | int val = mid - (A[i] + A[j]); 17 | if (val <= 0) 18 | break; 19 | auto it = lower_bound(A.begin(), A.end(), val); 20 | if (it == A.begin()) 21 | continue; 22 | it--; 23 | int idx = it - A.begin(); 24 | if (idx > j) 25 | cnt += idx - j; 26 | } 27 | } 28 | if (cnt < B) 29 | return true; 30 | return false; 31 | } 32 | 33 | 34 | 35 | int Solution::solve(vector &A, int B) { 36 | 37 | int n = A.size(); 38 | sort(A.begin(), A.end()); 39 | int low = 1, high = INT_MAX; 40 | 41 | while (low <= high){ 42 | int mid = low + ((high-low)/2); 43 | if (isPossible(A, mid, B)) 44 | low = mid + 1; 45 | else 46 | high = mid - 1; 47 | } 48 | 49 | return high; 50 | } 51 | -------------------------------------------------------------------------------- /Contests/01 Contest/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems of the first contest 2 | -------------------------------------------------------------------------------- /Contests/02 Contest/04 A-B.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A - B 3 | 4 | Problem Description 5 | Given an array A of integers of size N. Find the size of the largest subset of the array in which every pair satisfy the condition: x2 + y2 + x*y ≡ B mod C, where x and y are two different elements of the subset and C is a prime number. Note: All elements in the array are different. 6 | 7 | 8 | Problem Constraints 9 | 1 <= N <= 100000 10 | 1 <= A[i], B, C <= 109 + 7 11 | 1 <= A[i], B <= C - 1 12 | 13 | 14 | Input Format 15 | First argument is an array A of integers of size N. 16 | Second argument is an integer B. 17 | Third argument is an integer C. 18 | 19 | 20 | Output Format 21 | Return an integer denoting the size of the largest subset satisfying the given condition. 22 | 23 | 24 | Example Input 25 | A = [9, 17, 10, 16] 26 | B = 1 27 | C = 19 28 | 29 | 30 | Example Output 31 | 1 32 | 33 | 34 | Example Explanation 35 | No pair exist in the array which satisfy the condition so, we can only take one element in the subset. 36 | */ 37 | 38 | #define ll long long 39 | int Solution::solve(vector &A, int B, int C) 40 | { 41 | 42 | unordered_map umap; 43 | ll ans = 0; 44 | ll K = B; 45 | ll M = C; 46 | int n = A.size(); 47 | for (int i = 0; i < n; ++i) 48 | { 49 | ll d = (((1LL * A[i] * A[i]) % M) * A[i]) % M - (A[i] * K) % M; 50 | d %= M; 51 | if (d < 0) 52 | d += M; 53 | umap[d]++; 54 | ans = max(ans, umap[d]); 55 | } 56 | 57 | return ans; 58 | } 59 | -------------------------------------------------------------------------------- /Contests/02 Contest/2 Hide Boxes.cpp: -------------------------------------------------------------------------------- 1 | Hide boxes 2 | Problem Description 3 | There are N cubical boxes and the edge length of boxes is given by an array A of size N. 4 | A box can hold another box inside it, if and only if the length of a box is at least twice as large than another box. 5 | There can be atmost one box inside any other box. The box which is inside another box is not visible. 6 | You have to minimize the number of boxes visible. 7 | 8 | 9 | Problem Constraints 10 | 1 <= N <= 100000 11 | 1 <= A[i] <= 109 12 | 13 | 14 | Input Format 15 | First argument is an integer array A of size N. 16 | 17 | 18 | Output Format 19 | Return an integer denoting minimum number of boxes visible. 20 | 21 | 22 | Example Input 23 | A = [1, 2, 2, 4, 3] 24 | 25 | 26 | Example Output 27 | 3 28 | 29 | 30 | Example Explanation 31 | We can put the box at index 1 into box at index 5.Also, the box at index 2 into box at index 4. 32 | So, the visible boxes will be the box at index 3,4,5. 33 | 34 | 35 | int Solution::solve(vector &A) { 36 | 37 | int n = A.size(); 38 | sort(A.begin(), A.end()); 39 | int i = 0, j = n/2, ans = n; 40 | 41 | while (i < n/2 && j < n){ 42 | 43 | if (A[i]*2 <= A[j]){ 44 | ans--; 45 | i++; 46 | } 47 | j++; 48 | } 49 | return ans; 50 | } 51 | -------------------------------------------------------------------------------- /Contests/02 Contest/3 Sort permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort the permutation 3 | 4 | Problem Description 5 | Given a permutation of size N. Each number has some color associated to it. 6 | Find the maximum number of colors that can be used such that you are able to sort the permutation by swapping the elements having same color. 7 | 8 | 9 | Problem Constraints 10 | 1 <= N <= 100000 11 | 12 | 13 | Input Format 14 | First argument is an array of size N consisting of all elements from 1 to N. 15 | 16 | 17 | Output Format 18 | Return an integer denoting the maximum number of colors that can be used. 19 | 20 | 21 | Example Input 22 | Input 1: 23 | A = [1,4,2,3] 24 | 25 | 26 | Example Output 27 | Output 1: 28 | 2 29 | 30 | 31 | Example Explanation 32 | Explanation 1: 33 | We can color 4, 2, 3 with same color and 1 with different color. 34 | Given A = [1,4,2,3]. 35 | After swapping 4 and 2, A => [1,2,4,3]. 36 | Now swap 4 and 3 to get the sorted permutation A => [1,2,3,4]. 37 | */ 38 | 39 | // Similar to minSwaps2 40 | int Solution::solve(vector &A) 41 | { 42 | 43 | int ans = 0; 44 | for (int i = 0; i < A.size(); ++i) 45 | { 46 | while (A[i] != (i + 1)) 47 | { 48 | ans++; 49 | swap(A[i], A[A[i] - 1]); 50 | } 51 | } 52 | 53 | return A.size() - ans; 54 | } 55 | -------------------------------------------------------------------------------- /Contests/02 Contest/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems of the second contest 2 | -------------------------------------------------------------------------------- /Contests/03 Contest/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems of the third contest 2 | -------------------------------------------------------------------------------- /Contests/04 Contest/AdjPosNeg.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | vector A{-1,-2,-3,4,5}; 7 | int n = A.size(); 8 | vector neg, pos; 9 | 10 | for (int i = 0; i < n; i++){ 11 | if (A[i] < 0) 12 | neg.push_back( A[i] ); 13 | else 14 | pos.push_back( A[i] ); 15 | } 16 | 17 | cout<<"Negative "; 18 | for (auto x:neg) 19 | cout< Solution::solve(vector &A) { 4 | 5 | int _min = INT_MAX, _max = INT_MIN, n = A.size(); 6 | sort( A.begin(), A.end() ); 7 | for ( auto x: A ){ 8 | _min = min(x, _min); 9 | _max = max(x, _max); 10 | } 11 | 12 | int diff = 0, zero = 0; 13 | for ( int i = 1; i < n; i++){ 14 | int t = A[i] - A[i-1]; 15 | if ( t == 1 || t == 0 ) 16 | zero++; 17 | else 18 | diff = min(diff, t); 19 | } 20 | 21 | vector ans; 22 | ans.push_back( n - diff - zero ); 23 | ans.push_back(_max - _min - n - 1); 24 | return ans; 25 | } 26 | -------------------------------------------------------------------------------- /Contests/04 Contest/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems of the fourth contest 2 | -------------------------------------------------------------------------------- /Contests/04 Contest/SwapElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | vector A{-1,-2,-3,4,5}; 7 | int n = A.size(); 8 | vector neg, pos; 9 | 10 | for (int i = 0; i < n; i++){ 11 | if (A[i] < 0) 12 | neg.push_back( A[i] ); 13 | else 14 | pos.push_back( A[i] ); 15 | } 16 | 17 | int s1 = neg.size(), s2 = pos.size(); 18 | 19 | if (s1 == 0) 20 | return pos; 21 | if (s2 == 0) 22 | return neg; 23 | 24 | int ind = 0, i = 0, j = 0; 25 | while ( i < s1 && j < s2 ){ 26 | A[ind] = neg[i]; 27 | i++; 28 | ind++; 29 | A[ind] = pos[i]; 30 | j++; 31 | ind++; 32 | } 33 | 34 | while (i < s1){ 35 | A[ind] = neg[i]; 36 | i++; 37 | ind++; 38 | } 39 | 40 | while ( j < s2){ 41 | A[ind] = pos[j]; 42 | j++; 43 | ind++; 44 | } 45 | 46 | for (auto x : A) 47 | cout< &A) { 2 | long long n = A.size(); 3 | sort(A.begin(), A.end()); 4 | 5 | long long sum = 0; 6 | for (int i = 0; i < n; i++){ 7 | sum += A[i] % 1000000007; 8 | } 9 | 10 | long long ans = 0, mul = 1; 11 | for (int i = n-1; i >= 0; i--){ 12 | ans = (ans + A[i]*mul) % 1000000007; 13 | mul++; 14 | } 15 | 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Contests/05 Contest/3_AnotherGCD.cpp: -------------------------------------------------------------------------------- 1 | unordered_set primeFactors(int n) 2 | { 3 | unordered_set temp; 4 | while (n % 2 == 0) 5 | { 6 | temp.insert(2); 7 | n = n/2; 8 | } 9 | 10 | for (int i = 3; i <= sqrt(n); i = i + 2) 11 | { 12 | while (n % i == 0) 13 | { 14 | temp.insert(i); 15 | n = n/i; 16 | } 17 | } 18 | 19 | if (n > 2) 20 | temp.insert(n); 21 | 22 | return temp; 23 | } 24 | 25 | 26 | int Solution::solve(vector &A) { 27 | 28 | bool flag = true; 29 | for (int i = 0; i < A.size(); i++){ 30 | if (A[i] != 1){ 31 | flag = false; 32 | } 33 | } 34 | if (flag) 35 | return -1; 36 | 37 | unordered_map> umap; 38 | 39 | for (int i = 0; i < A.size(); i++){ 40 | unordered_set res = primeFactors(A[i]); 41 | for (auto j : res){ 42 | umap[j].push_back(i); 43 | } 44 | } 45 | 46 | int _max = INT_MIN; 47 | 48 | for (auto x = umap.begin(); x != umap.end(); x++){ 49 | int cnt = 1; 50 | sort(x->second.begin(), x->second.end()); 51 | for (int y = 1; y < x->second.end() - x->second.begin(); y++){ 52 | 53 | if (x->second[y] - x->second[y-1] == 1){ 54 | cnt++; 55 | _max = max(_max, cnt); 56 | } 57 | else{ 58 | cnt = 1; 59 | } 60 | } 61 | } 62 | 63 | return max(_max, 1); 64 | } 65 | -------------------------------------------------------------------------------- /Contests/06 Contest/README.md: -------------------------------------------------------------------------------- 1 | Contest problems 2 | -------------------------------------------------------------------------------- /Contests/07 Contest/1 powerArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int powerArrays (vector &A, int n){ 5 | 6 | int nge[n], pge[n]; 7 | stack s; 8 | s.push(0); 9 | for (int i = 1; i < n; ++i){ 10 | while (!s.empty() && A[s.top()]/2 < A[i]){ 11 | nge[ s.top() ] = i; 12 | s.pop(); 13 | } 14 | s.push(i); 15 | } 16 | 17 | while (!s.empty()){ 18 | nge[s.top()] = n; 19 | s.pop(); 20 | } 21 | for (int x : nge) 22 | cout<= 0; --i){ 29 | while (!s.empty() && A[s.top()]/2 < A[i]){ 30 | pge[ s.top() ] = i; 31 | s.pop(); 32 | } 33 | s.push(i); 34 | } 35 | 36 | while (!s.empty()){ 37 | pge[ s.top() ] = -1; 38 | s.pop(); 39 | } 40 | for (int x : pge) 41 | cout< A{6,4,9,2,3,8}; 55 | cout<<"\nThere are "< 2 | using namespace std; 3 | 4 | bool check(int n){ 5 | 6 | for (int i = 2; i*i <= n; ++i){ 7 | if (n%i == 0) 8 | return false; 9 | } 10 | return true; 11 | } 12 | 13 | int solve(vector &A, int B, int C) { 14 | 15 | int n = A.size(); 16 | int prime[n]; 17 | memset(prime, 0, sizeof(prime)); 18 | 19 | for (int i = 0; i < n; ++i){ 20 | if (check(A[i]) == true){ 21 | prime[i] = 1; 22 | } 23 | } 24 | 25 | 26 | int ans = 0, sum = 0, flag = 0; 27 | 28 | for (int i = 1; i < (1 << n); ++i){ 29 | sum = 0; 30 | flag = 0; 31 | for (int j = 0; j < n; ++j){ 32 | if (i & (1 << j)){ 33 | sum += A[j]; 34 | if (prime[j]) 35 | flag = 1; 36 | } 37 | } 38 | if (sum >= B && sum <= C && flag == 1){ 39 | ++ans; 40 | } 41 | 42 | } 43 | 44 | return ans; 45 | } 46 | 47 | 48 | int main(){ 49 | 50 | vector A = {2,2,4,5}; 51 | int B = 3, C = 7; 52 | 53 | cout< 2 | using namespace std; 3 | 4 | int gcd(int a, int b){ 5 | if (a == 0) 6 | return b; 7 | return (b%a, a); 8 | } 9 | 10 | int main(){ 11 | 12 | vector A{5,7,10,8,3,4}; 13 | 14 | for (int i = 0; i < 6; i+=2) 15 | cout< 2 | using namespace std; 3 | 4 | const int MAXN = 100007; 5 | bool prime[MAXN]; 6 | 7 | void sieve(int n){ 8 | memset(prime, true, sizeof(prime)); 9 | 10 | for (int p = 2; p*p <= n; ++p){ 11 | if (prime[p] == true){ 12 | for (int j = p*p; j <= n; ++j){ 13 | prime[j] = false; 14 | } 15 | } 16 | } 17 | } 18 | 19 | int gcd(int a, int b){ 20 | if (b == 0) 21 | return a; 22 | return gcd(b, a % b); 23 | } 24 | 25 | 26 | int getDiff(int A) { 27 | cout<<"woohoo "; 28 | 29 | int minAns = INT_MAX; 30 | int start = (A/2)+1; 31 | for (int i = 1; i < start; ++i){ 32 | int next = A - i; 33 | if (gcd(i, next) == 1){ 34 | minAns = min(minAns, next-i); 35 | } 36 | } 37 | 38 | return minAns; 39 | } 40 | 41 | 42 | int main(){ 43 | 44 | cout<<"Ans is "< 2 | using namespace std; 3 | 4 | void insertBS(vector &A, int x){ 5 | 6 | int low = 0, high = A.size() - 1; 7 | 8 | while (low<=high){ 9 | int mid = low + (high - low)/2; 10 | if (A[mid] > x) 11 | high = mid-1; 12 | else if (A[mid] < x){ 13 | low = mid+1; 14 | } 15 | else 16 | { 17 | low = mid; 18 | break; 19 | } 20 | } 21 | A.insert(A.begin() + low, x); 22 | } 23 | 24 | vector solve(){ 25 | vector A = {13,4,10,17,6,16}; 26 | sort(A.begin(), A.end()); 27 | 28 | int n = A.size(); 29 | 30 | while (n--){ 31 | int first = A[0], last = A[A.size() - 1]; 32 | int avg = (first+last)/2; 33 | first += avg; 34 | last -= avg; 35 | 36 | A.erase(A.begin()); 37 | A.erase(A.begin()+A.size()-1); 38 | 39 | insertBS(A, first); 40 | insertBS(A, last); 41 | } 42 | 43 | return A; 44 | } 45 | 46 | int main(){ 47 | 48 | vector A = solve(); 49 | for (int x: A) 50 | cout< 2 | using namespace std; 3 | // Scooby Doo 4 | 5 | typedef long long ll; 6 | ll ans; 7 | 8 | ll power1(ll a, ll b){ 9 | ll res = 1; 10 | a = a%1000000007; 11 | while (b>0){ 12 | if (b&1) 13 | res = (res*a)%1000000007; 14 | b = b>>1; 15 | a = (a*a)%1000000007; 16 | } 17 | return res; 18 | } 19 | 20 | void addDigit(int n, int pos, int tot){ 21 | 22 | ll res = 0; 23 | int x = tot-pos+1; 24 | 25 | while (x--){ 26 | res = (res*10 + n)%1000000007; 27 | } 28 | 29 | res = (res*pos)%1000000007; 30 | 31 | ans = (ans+res) % 1000000007; 32 | } 33 | 34 | int solve(string A) { 35 | ans = 0; 36 | int pos = A.size(); 37 | int tot = pos; 38 | 39 | for (int i = pos-1; i >= 0; i--){ 40 | int currNum = int(A[i]-'0'); 41 | addDigit(currNum, pos, tot); 42 | pos--; 43 | } 44 | 45 | return ans; 46 | } 47 | 48 | int main(){ 49 | 50 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | string A= "11111"; 6 | int cnt = 0; 7 | for (char x: A) 8 | if (x == '1') 9 | cnt++; 10 | 11 | int ans = 0; 12 | while (cnt>0){ 13 | ans += cnt; 14 | cnt--; 15 | } 16 | cout< 2 | using namespace std; 3 | #define ll long long 4 | 5 | int solve(int A, int B, int C, int D) { 6 | 7 | if (D == 0) 8 | return 0; 9 | 10 | if (D == 1){ 11 | ll ans = (A)%1000000007; 12 | ans = (ans + B)%1000000007; 13 | ans = (ans + C)%1000000007; 14 | return int(ans); 15 | } 16 | 17 | ll ans = 1; 18 | int mid = 0, cnt = 0; 19 | 20 | vector arr = {1}; 21 | 22 | for (int i = 2; i <= D; ++i){ 23 | ll curr = 0; 24 | curr = (arr[mid] * A); 25 | curr = (curr + (B*i)); 26 | curr = (curr + C); 27 | curr %= 1000000007; 28 | cnt++; 29 | if (cnt%2 == 0){ 30 | cnt = 0; 31 | mid++; 32 | } 33 | arr.push_back(curr); 34 | bool flag = false; 35 | if (ans == 266506762){ 36 | cout<<"woohoo got it! "< 2 | using namespace std; 3 | 4 | int solve(vector &A) 5 | { 6 | 7 | int n = A.size(); 8 | 9 | int i = 0, j = n - 1; 10 | int ans = 0; 11 | vector blue, red; 12 | 13 | while ((i < (n / 2)) && (j >= (n / 2))) 14 | { 15 | if (A[i] > A[j]) 16 | { 17 | red.push_back(A[i]); 18 | blue.push_back(A[j]); 19 | } 20 | else 21 | { 22 | red.push_back(A[j]); 23 | blue.push_back(A[i]); 24 | } 25 | i++; 26 | j--; 27 | } 28 | 29 | i = 0; 30 | j = blue.size() - 1; 31 | 32 | while (i < red.size()) 33 | { 34 | ans += (red[i] ^ blue[j]); 35 | i++; 36 | j--; 37 | } 38 | 39 | return ans; 40 | } 41 | 42 | int main() 43 | { 44 | vector A{23, 35, 6, 25, 10, 34, 45 | 29, 13, 35, 1, 6, 7}; 46 | cout << "Ans is " << solve(A); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Contests/16 Contest/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems of 16th contest 2 | -------------------------------------------------------------------------------- /Contests/17 Contest/NoMoreZeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool check(int n) 5 | { 6 | 7 | while (n > 0) 8 | { 9 | int rem = n % 10; 10 | n /= 10; 11 | if (rem == 0) 12 | return false; 13 | } 14 | 15 | return true; 16 | } 17 | 18 | string solve(int A) 19 | { 20 | 21 | bool flag = true; 22 | int num = A + 1; 23 | string str; 24 | 25 | while (flag) 26 | { 27 | if (check(num)) 28 | { 29 | str = to_string(num); 30 | break; 31 | } 32 | num++; 33 | } 34 | 35 | return str; 36 | } 37 | 38 | int main() 39 | { 40 | cout << "Ans is"; 41 | cout << solve(99) << endl; 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Contests/17 Contest/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solved problems of 17th contest 2 | -------------------------------------------------------------------------------- /Contests/18 Contest/chessmodulo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int solve(int N, vector &B) 5 | { 6 | 7 | sort(B.begin(), B.end()); 8 | int cntB = 0, cntW = 0; 9 | for (int x : B) 10 | { 11 | if (x & 1) 12 | { 13 | cntB++; 14 | } 15 | else 16 | { 17 | cntW++; 18 | } 19 | } 20 | 21 | int curr = N - 1; 22 | int ans1 = 0; 23 | 24 | for (int i = B.size() - 1; i >= 0; i--) 25 | { 26 | ans1 += abs(curr - B[i]); 27 | curr = curr - 2; 28 | } 29 | 30 | curr = N; 31 | int ans2 = 0; 32 | for (int i = B.size() - 1; i >= 0; i--) 33 | { 34 | ans2 += abs(curr - B[i]); 35 | curr = curr - 2; 36 | } 37 | 38 | return min(ans1, ans2); 39 | } 40 | 41 | int main() 42 | { 43 | int A = 100; 44 | vector B{ 45 | 93, 46 | 54, 47 | 57, 48 | 61, 49 | 68, 50 | 66, 51 | 70, 52 | 96, 53 | 64, 54 | 82, 55 | 80, 56 | 75, 57 | 69, 58 | 77, 59 | 76, 60 | 94, 61 | 67, 62 | 86, 63 | 90, 64 | }; 65 | cout << solve(A, B); 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /Contests/18 Contest/permutation game.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/Contests/18 Contest/permutation game.jpg -------------------------------------------------------------------------------- /Contests/18 Contest/permutationGame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define MOD 1000000007 5 | 6 | int solve(vector &A) 7 | { 8 | 9 | sort(A.begin(), A.end()); 10 | 11 | int ans = 0; 12 | int curr = 1; 13 | for (int i = 0; i < A.size(); ++i) 14 | { 15 | if (curr < A[i]) 16 | { 17 | ans += abs(curr - A[i]); 18 | } 19 | else 20 | { 21 | ans += abs(A[i] - curr); 22 | } 23 | curr++; 24 | ans %= MOD; 25 | } 26 | 27 | return ans; 28 | } 29 | 30 | int main() 31 | { 32 | vector A{-1, -1, 3}; 33 | cout << solve(A); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Contests/18 Contest/top 2 in scaler contest.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FazeelUsmani/Scaler-Academy/a7a84e634ba6441257f859a9a5b9c2df673ad903/Contests/18 Contest/top 2 in scaler contest.jpg -------------------------------------------------------------------------------- /Contests/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions for all the contest problems 2 | -------------------------------------------------------------------------------- /Core Subjects/Database/README.MD: -------------------------------------------------------------------------------- 1 | This folder contains all database related questions 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 1/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 2/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 3/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 4/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 5/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 6/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 7/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /Core Subjects/Operating Systems/Operating Systems 8/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the solutions of this topic 2 | -------------------------------------------------------------------------------- /MI/11October.cpp: -------------------------------------------------------------------------------- 1 | int pos, neg; 2 | 3 | void backtrack(vector &A, int pos, int C, vector visited, int val) 4 | { 5 | 6 | if (pos == 0) 7 | { 8 | if (val > C) 9 | neg--; 10 | else 11 | pos++; 12 | } 13 | 14 | if (visited.size() & 1) 15 | { 16 | backtrack(A, pos - 1, C, visited, A[0]); 17 | 18 | int middle = visited.size() / 2; 19 | backtrack(A, pos - 1, C, visited, A[visited[middle]]); 20 | 21 | backtrack(A, pos - 1, C, visited, A[visited[visited.size() - 1]]); 22 | } 23 | else 24 | { 25 | backtrack(A, pos - 1, C, visited, A[0]); 26 | 27 | backtrack(A, pos - 1, C, visited, A[visited[visited.size() - 1]]); 28 | } 29 | } 30 | 31 | int Solution::solve(vector &A, int B, int C) 32 | { 33 | pos = 0; 34 | neg = 0; 35 | 36 | vector visited; 37 | for (int i = 0; i < A.size(); ++i) 38 | visited.push_back(i); 39 | 40 | backtrack(A, B, C, visited, INT_MAX); 41 | 42 | return (pos / (pos + reg)) % 1000000007; 43 | } 44 | -------------------------------------------------------------------------------- /MI/12 December2020.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/noble-integers-in-an-array-count-of-greater-elements-is-equal-to-value 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector A{-5, -2, -3, 0, -6, 8, -10, -6, -8, -1, 6, -9, 0, -6, 2, 2, 2, 0, -5, -5, -8, 9, -10, -8, 8, 3, 8, 0, -6, 0, -1, -9, 9, 6, 2, 5, 4, -6, 9, -1, 3, 6, 0, 5, -10, -8, 9, -6, 3, -5, -9, -3, -6, 3, -9, 4, -4, 9, -6, -8, -8, -4, -6, -9, -8, -2, -2, -1} sort(A.begin(), A.end()); 9 | sort(A.begin(), A.end()); 10 | int ans = -1; 11 | 12 | for (int i = 0; i < A.size() - 1; ++i) 13 | { 14 | if (A[i] == A[i + ]) 15 | continue; 16 | if (A[i] == n - i - 1) 17 | { 18 | ans = 1; 19 | break; 20 | } 21 | } 22 | cout(ans); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scaler-Academy 2 | 3 | 4 | This repository contains all the assignment and homework solutions solved during [Scaler Academy](https://www.scaler.com/) course
5 | 6 | A[FILE_NAME] --> Assignment problem
7 | HW[FILE_NAME] --> Homework problem 8 | 9 | To visualize data structures use [VisuAlgo](https://visualgo.net/en) 10 | 11 | After these 50 classes we had the following lectures: 12 | 13 | 1. Computer Networks - 6 classes 14 | 2. Operating Systems - 5 classes 15 | 3. DBMS - 5 classes 16 | 4. Low Level Design 17 | 5. High Level Design 18 | 6. Devclasses (full stack or backend) 19 | 7. Advanced DS Algo classes (DP with BitMask, DP on digits, Quad Trees) 20 | 21 | 22 | For more information about Scaler Academy, feel free to reach out to me at __fazeelusmani18@gmail.com__ 23 | -------------------------------------------------------------------------------- /basics/README.md: -------------------------------------------------------------------------------- 1 | This folder contains all the basics information regarding C++ like intitializing an array, vector. How to use inbuilt stack, queue, LL .... 2 | -------------------------------------------------------------------------------- /basics/passByRef.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void passByReference(int &i, int &j) { 5 | int temp = i; 6 | i = j; 7 | j = temp; 8 | } 9 | 10 | void passByValue(int i, int j){ 11 | int temp = i; 12 | i = j; 13 | j = temp; 14 | cout<<"a & b are "< 2 | using namespace std; 3 | 4 | struct Node{ 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node (int x){ 9 | data = x; 10 | left = right = NULL; 11 | } 12 | }; 13 | 14 | int main(){ 15 | 16 | Node *a = new Node(10); 17 | 18 | a->left = new Node(20); 19 | a->right = new Node(30); 20 | 21 | a->left->left = new Node(40); 22 | a->left->right = new Node(50); 23 | 24 | a->right->left = new Node(60); 25 | a->right->right = new Node(70); 26 | 27 | return 0; 28 | } 29 | 30 | 31 | /* 32 | This code creates the following tree 33 | 34 | 10 35 | 20 30 36 | 40 50 60 70 37 | 38 | */ 39 | -------------------------------------------------------------------------------- /template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | return 0; 8 | } --------------------------------------------------------------------------------