├── .gitignore ├── AdHoc ├── ACPC10A.cpp ├── ADDREV.py ├── ADDREV_IITROPAR.c ├── AE00.py ├── ArrayDuplicates.py ├── ArrayRotation.cpp ├── BooleanMatrix.cpp ├── CANDY3.py ├── CANTON.cpp ├── CATSDOGS.cpp ├── CF100C.py ├── CF106A.py ├── CHBLLNS.cpp ├── CO92JUDG.cpp ├── ContainerWithMostWater.py ├── ConvertToHex.py ├── EIGHTS.cpp ├── FRIEZA.cpp ├── FirstMissingInteger.py ├── FlightRangeBookings.py ├── FlippingAnImage.py ├── HackerRankLogo.py ├── LargestNumberAtleastTwice.py ├── MAJOR.py ├── MagicSquare.py ├── MaxChunksToMakeSorted2.py ├── MaxDistance.py ├── MaximumSwap.py ├── MinimumOperationsToMakeArrayEqual.py ├── MissingNumber.cpp ├── MooreVotingAlgorithm.cpp ├── NMNNMX.py ├── NSTEPS.cpp ├── NextGreaterElement3.py ├── NonDivisibleSubset.py ├── OneEditDistance.py ├── PALIN.cpp ├── Panda_And_Chain_Reaction_HackerEarth.cpp ├── RearrangeArray.py ├── SAMER08F.cpp ├── ShortestUnsortedContinuousSubarray.py ├── TOANDFRO.cpp ├── TriangularSeries.py ├── UniquePaths.cpp ├── UniquePaths.py ├── WILLITST.py ├── corporate-flight-bookings.py ├── first-missing-positive.py ├── matmul.c ├── nthNonFibonacci.cpp ├── prettyprint.py ├── tourist.py └── two_missing.py ├── Backtracking ├── LetterCombinationsOfAPhoneNumber.py ├── SumOfNDigitsK.py ├── a.out ├── generate-parentheses.py ├── graphColoring.c ├── graphColoring2.c ├── letter-combinations-of-a-phone-number.py ├── nQueen_All.c └── nQueens_Single.py ├── BitManipulation ├── HammingDistance.py ├── MaxXorPair.py ├── MinXorPair.py ├── PowerOfFour.py ├── PowerOfThree.py ├── PowerOfTwo.py └── number-of-steps-to-reduce-a-number-to-zero.py ├── CF1114A.py ├── CONTRIBUTING.md ├── CS591 ├── Backtracking │ └── nqueen.c ├── DivideConquer │ ├── BinarySearch.c │ ├── MaxMinNumber.c │ ├── Mergesort.c │ └── Quicksort.c ├── DynamicProgramming │ ├── FloydWarshall.c │ └── MatrixChainMultiplication_TopDown.c ├── Graph │ ├── dfs.c │ └── tmp.c └── Greedy │ ├── F_Knapsack.c │ ├── TSP_Greedy.c │ └── dijkstraAlgo.c ├── Contests ├── CF1343 │ ├── 1343A.py │ └── 1343B.py ├── Chef_APRIL20B │ └── STRNO.py ├── Chef_AUG18 │ ├── Modular GCD │ │ ├── Final_ModularGCD.py │ │ ├── GCD3.py │ │ ├── GCDMOD1.cpp │ │ ├── GCDMOD2.cpp │ │ ├── GCDMOD2.py │ │ ├── GCDMOD3.cpp │ │ └── Trash.txt │ ├── ProblemSort.cpp │ ├── SHKNUM.py │ ├── a.out │ ├── inputProbSort.txt │ ├── inputSpellbob.txt │ └── spellbob.cpp ├── Chef_COCE2018 │ ├── LUCAS1.py │ ├── QUERARR.py │ └── inp.txt ├── Chef_COOK98 │ ├── ATM2.cpp │ ├── MAKPERM.cpp │ ├── OETW.cpp │ └── OETW2.cpp ├── Chef_COW2018 │ ├── BDMS.py │ ├── DSI2.py │ ├── TA1.py │ └── TRO1.py ├── Chef_CodeIncognito │ ├── INVENTO.cpp │ ├── INVENTON.py │ ├── PRISTG.py │ └── PRISTG_.py ├── Chef_ELE32018 │ ├── CHFPRMDM.py │ ├── CHFPRMDM_2.py │ ├── JACKJILL.py │ └── inp.txt ├── Chef_JAN19B │ ├── DPAIRS.py │ ├── DPAIRS_2.py │ ├── FANCY.py │ ├── HP18.py │ ├── MGAME1.py │ ├── MGAME_intuition.txt │ └── inp.txt ├── Chef_KJSCE │ ├── BAL.py │ ├── BOND.py │ ├── BOOK.py │ └── inp.txt ├── Chef_LTIME64 │ ├── CHEFRES.py │ └── JDELAY.cpp ├── Chef_LTIME70B │ ├── POGO.py │ ├── SEVENSEG.py │ └── TSTROBOTS.py ├── Chef_LTIME71B │ ├── ATTND.py │ ├── FASTFOOD.py │ ├── MINARRS.py │ └── MINARRS2.py ├── Chef_LTIME78B │ ├── APARTS.py │ ├── CMPRESS.py │ ├── DEADEND.py │ └── PIBRO.py ├── Chef_MARCH19B │ ├── CHDIGER.py │ ├── CHNUM.py │ ├── CHNUM_AB.cpp │ ├── CHO.txt │ ├── CHONQ.py │ ├── CHONQ.py.save │ ├── CHONQ_Brute.py │ ├── JAIN │ │ ├── JAIN.py │ │ ├── JAIN_0.py │ │ └── JAIN_AB.py │ ├── SUBPRNJL │ │ ├── SUB.cpp │ │ ├── SUB.txt │ │ ├── SUB2.cpp │ │ ├── SUBPRNJL_0.py │ │ ├── SUBPRNJL_1.py │ │ ├── SUBPRNJL_Brute.py │ │ ├── a.out │ │ ├── input2.txt │ │ ├── othersort.py │ │ ├── prefix.py │ │ ├── vec.cpp │ │ ├── vec2.cpp │ │ └── vec3.cpp │ ├── a.out │ └── input.txt ├── Chef_MARCH20B │ ├── CHPINTU.py │ ├── ENGXOR.cpp │ ├── ENGXOR.py │ └── input.txt ├── Chef_NOV1BB │ ├── CHFTIRED.py │ ├── CHHAPPY.py │ ├── GMEDIAN1.py │ ├── HMAPPY1 │ │ ├── HMAPPY1.py │ │ ├── HMAPPY1_2.py │ │ ├── HMAPPY1_3.py │ │ ├── TC_HMAPPY1.txt │ │ ├── correctout.txt │ │ ├── in1.txt │ │ ├── inp.txt │ │ ├── myout.txt │ │ └── tcGen_hmappy1.py │ └── PRDRG.py ├── Chef_OCT18B │ ├── BITOBYT.py │ ├── CHSERVE.cpp │ ├── HMAPPY.py │ ├── HMAPPY2.py │ ├── MINDSUM.py │ └── inp.txt ├── Chef_SEP18 │ ├── ANDSQR.cpp │ ├── a.out │ └── inp.txt ├── CodeJam19 │ ├── Qualifiers │ │ ├── Crypto.py │ │ ├── Foregone.py │ │ ├── OwnWay.py │ │ └── input.txt │ └── Round1A │ │ ├── GolfPy3.txt │ │ ├── alienrhyme │ │ ├── golfers │ │ ├── pylons │ │ ├── pylons.py │ │ └── pylonsPy3.txt ├── CodingNinjas_CareerCamp │ ├── GetProduct.cpp │ ├── LightCandles.py │ └── Pattern.py ├── Facebook Hacker Cup 2018 │ └── Qualification │ │ └── Tourist │ │ ├── Output.txt │ │ ├── input.txt │ │ ├── tourist.py │ │ └── tourist.txt ├── Google Codejam 2018 │ ├── Solution.cpp │ └── Solution1.cpp ├── HackerEarth_Amdocs_HackFest │ ├── Screenshot 2020-02-16 at 5.49.12 PM.png │ ├── Screenshot 2020-02-16 at 5.50.41 PM.png │ ├── Screenshot 2020-02-16 at 5.59.56 PM.png │ ├── Screenshot 2020-02-16 at 6.00.01 PM.png │ ├── Screenshot 2020-02-16 at 6.00.06 PM.png │ └── Screenshot 2020-02-16 at 6.00.11 PM.png ├── Snackdown19_Online1A │ ├── AVGMAT_Partial.py │ ├── CARDMGK.py │ ├── CHEFADD_Partial.py │ └── TYPING.py ├── Snackdown19_Qualifier │ ├── CHEFPRMS.py │ ├── QABC.cpp │ ├── QUALPREL.py │ └── SPREAD2.py ├── TechGig_GeekGoddess │ └── journalist.cpp └── bleedcode │ ├── a.out │ ├── bloody.py │ ├── bracket.py │ ├── bracket2.cpp │ ├── date.py │ ├── deter.py │ ├── input.txt │ ├── leven.py │ └── second.py ├── Divide_Conquer ├── BinarySearch.c ├── EQUALIZE.cpp ├── LargestArea_Histogram.cpp ├── Maximum_Minimum.c ├── MergeSort.c ├── QuickSort.c └── RandomizedSelect_OrderStat.cpp ├── Dynamic Programming ├── 01Knapsack.java ├── ACODE.py ├── BinaryKnapsack.cpp ├── BuildingHouses.py ├── BuyAndSellStock_WithCoolDown.py ├── CF455A.py ├── Coin-Change.py ├── CoinChange_BottomUp.cpp ├── CoinChange_TopDown.java ├── DPBook │ ├── Fibonacci_DP.py │ ├── Fibonacci_Memoized.py │ ├── MaxSumSubarray.py │ ├── MinCostPath_DP.java │ ├── MinCostPath_DP_FollowUp.java │ ├── MinCostPath_Memo.java │ ├── MinCostTravel_DP.java │ ├── MinCostTravel_Memoized.java │ ├── PP │ │ ├── 1_EditDistance.java │ │ ├── 2_TotalPathCount.java │ │ ├── 3_StringInterleaving.java │ │ └── 3_StringInterleaving_2.py │ ├── PlacingTiles_DP.java │ └── WaysToScore.py ├── EditDistance.py ├── Equal_Hackerrank.java ├── Finding_Nth_Fibonacci_2.cpp ├── Finding_Nth_Fibonacci_Number.cpp ├── GeeksSum.py ├── HouseRobber.java ├── HouseRobber2.py ├── IEMCO5B.py ├── LCS.py ├── LKS.cpp ├── LongestBalancedSubstring.py ├── LongestCommonSubsequence.cpp ├── LongestIncreasingPathInMatrix.py ├── LongestIncreasingSubsequence.cpp ├── LongestPalindromicSubsequence.java ├── MatrixChainMul_CLRS.c ├── MatrixChainMultiplication.c ├── MatrixProduct.cpp ├── MaxProductSubarray.java ├── MaxSumWithoutAdjacentElements.java ├── MaximumSubarray.java ├── MinStepsToReachEnd.java ├── MinSumPathInMatrix.py ├── Min_Number_Of_Squares.java ├── OnesAndZeroes.py ├── PPERM.cpp ├── PPERM.py ├── PerfectString.py ├── RoyAndCoinBoxes.cpp ├── ShortestCommonSupersequence.py ├── StaircaseClimbCTCI.py ├── SumOfSquares.py ├── TLCS.cpp ├── UniquePathsInAGrid.py ├── Wildcard_Matching.py ├── WordWrapProblem.py ├── WorkBreak.py ├── bike-trip.py ├── knapsack_0_1.py ├── maximumSumNonAdjacent.py ├── tetrahedron166E.cpp └── tetrahedron166E.py ├── Graphs ├── AlienDictionary.py ├── Backtracking │ ├── GeneralizedAbbreviations.py │ └── RobotRoomCleaner.py ├── ConnectedComponents.py ├── CourseSchedule.py ├── CourseSchedule2.py ├── CourseSchedule_207.py ├── Dijkstra │ ├── Dijkstra.py │ ├── Dijkstra_Optimized.py │ ├── Dijkstra_Priority_Queue.java │ ├── Dijkstra_Tree_Set.java │ ├── a.out │ ├── dijkstraAlgo.c │ ├── graphinput1.txt │ └── graphinput2.txt ├── FloodFill.py ├── FloydWarshall │ ├── FWA.c │ ├── FloydWarshall.java │ ├── FloydWarshall_IB.java │ └── ginp.txt ├── KnightObstacle.py ├── KnightOnChessBoard.py ├── MaxConnectedColors.py ├── NetworkDelayTime.py ├── NetworkDelayTime_Optimized.py ├── NetworkFlow │ └── Concept.md ├── NumberOfClosedIslands.py ├── NumberOfIslands_DFS.py ├── NumberofIslands.py ├── ReverseGraph.py ├── RottenOranges.py ├── connectivity.cpp ├── in_connectivity.txt └── making-a-large-island.py ├── Greedy ├── BUSYMAN.cpp ├── CHEFTMA.py ├── CIELRCPT.cpp ├── Candies.py ├── Count-n-Say.py ├── EmployeeFreeTime.py ├── FASHION_SPOJ.cpp ├── FractionalKnapsack.cpp ├── Gas_Station.py ├── GlobalAndLocalInversions.py ├── IPCTRAIN.py ├── IPCTRAIN__2.py ├── Job_Sequencing_Deadlines.py ├── JumpGame.java ├── JumpGame2.py ├── Kruskal_MSTAlgorithm │ ├── MinimumSpanningTree.py │ ├── input1.txt │ ├── input2.txt │ ├── kruskal.py │ ├── output1.txt │ └── output2.txt ├── LEMUSIC.py ├── LazyBartenderProblem.py ├── Maximum-Swap.py ├── MeetingRooms2.py ├── MergeIntervals.py ├── MinDominoRotationForEqualRow.py ├── MinXorPair_Greedy.py ├── MinimumHotels.java ├── MinimumHotels.py ├── MinimumTernaryStringCF1009B.cpp ├── MyCalendar3.py ├── MyCalendar3_UsingTreeMap.java ├── TACHSTCK.py ├── couples-holding-hands.py └── inp.txt ├── Hashing ├── All_O(1)_Insert_Delete_GetRandom_with_duplicates.py ├── Anagramic_Combinations.py ├── Anagrams.py ├── Circular_Loop_Array.py ├── DesignHashMap.py ├── DesignHashSet.py ├── FirstNonRepeatingChar.py ├── ImageOverlap.py ├── LargestContinuousSubsequenceZeroSum.py ├── LongestConsecutiveSequence.py ├── LongestDistinctCharacterInString.py ├── LongestSubarraySumK.py ├── Map.class ├── Map.java ├── MapNode.java ├── MaxSizeSubarraySumEqualsK.py ├── NumberOfEquivalentDominoPairs.py ├── OurMapUse.java ├── PairSum_Zero.py ├── RomanNumberToInteger ├── SubarraySumEqualsK.java ├── ValidSudoku.py ├── ZeroSumSubarray.py ├── bear_and_steady_gene.py ├── implementation.cpp └── subarraySumK.py ├── Heap ├── AthLargestElement.py ├── EmployeeFreeTime.py ├── IPCTRAIN_.py ├── SkylineProblem.py ├── SlidingWindowMax_HeapBased.py ├── merge-k-sorted-lists.py └── merge_k_Sorted_lists.py ├── LICENSE ├── LinkedList ├── AddTwoNumbers.py ├── AllOoneDS.py ├── FindDuplicatesInArray.py ├── LRUCache ├── ListCycle.py ├── MergeKSortedLists.py ├── OddEvenLinkedList.py ├── Palindrome-Linked-List.py ├── PartitionList.py ├── REVLL.java ├── RemoveZeroSumConsecutiveNodesFromLinkedList,py ├── ReversingList.py ├── StackWithMiddle.py ├── SwapNodesInPair.py └── swap-nodes-in-pairs.py ├── Misc ├── BST.c ├── BinaryTree_ArrayRep.c ├── CandyCrush1D.py ├── ConstantOrderDS.java ├── DFS.c ├── DesignCircularQueue.py ├── DoubtSolve.c ├── EruptingVolcanoes.c ├── Height_Deletion_BST.c ├── LRUCache.py ├── LRUCache_Optimized.java ├── LargestPalindromeProduct.py ├── Make_Row_Column_Zero.c ├── PBDS.cpp ├── Sudoku.c └── linkedlist.c ├── NextNumber.py ├── Number_Theory ├── EulerTotientFunc.py ├── HappyNumber.py ├── HelpDory.py ├── PresentOnce.py ├── Primality Test │ ├── GCDEX.py │ ├── PRIME1.cpp │ ├── Prime_Numbers_lessthan_10pow6.txt │ ├── RamanujanPrimeSubstring.py │ ├── Roy_and_Shopping.py │ └── Sieve_of_Eratosthenes.py ├── TotalHammingDistance.py └── gottaCatchEmAll.cpp ├── README.md ├── Searching_Sorting ├── AGGRCOW.cpp ├── BinarySearch │ ├── CF1278B_AandB.cpp │ ├── FirstBadVersion.java │ ├── ImplementPowerFunction.cpp │ ├── LowerUpperBoundOfTarget.py │ ├── MergeIntervals.py │ ├── PainterPartition.java │ ├── PainterPartitionProblem.py │ ├── QUERARR.py │ ├── SNAKEEAT_Codechef.cpp │ ├── Search-for-a-range.cpp │ ├── SearchingInShiftedSortedArray.py │ ├── ShiftedSortedArray.py │ └── median-of-two-sorted-arrays.py ├── CREP.py ├── CutTheSticks.py ├── Dutch_National_Flag_Algorithm.cpp ├── GCDOrdering.py ├── GameShopping1009A.py ├── IEMCO5C.py ├── LexicographicalSort.py ├── LinearSearch.c ├── MaximumGap.py ├── MinSwapSegregate.py ├── MinimumMovesToEqualAllArrayElements2.py ├── MinimumTernaryString1009B.py ├── ORDTEAMS_1.py ├── ORDTEAMS_2.py ├── SortArrayOf012.cpp ├── SortColors.py ├── WGHTNUM.py └── WaveArray.py ├── SegmentTrees ├── GMPLANTS.cpp ├── HORRIBLE.cpp ├── Range-Sum-Query-Mutable.py ├── RangeMinQuery_RangeUpdate.cpp ├── RangeMinimumQuery.cpp ├── RangeSumQuery.cpp ├── ginp.txt ├── inp.txt └── lazyinp.txt ├── Stack_Queue ├── Asteroid-Collision.py ├── DailyTemperatures.py ├── DecodeString.py ├── Flatten-Nested-List-Iterator.py ├── KthCharInDoubleDecryptedString.cpp ├── LargestRectInHistogram.cpp ├── LargestRectInHistogram.java ├── LongestValidParenthesis.java ├── LongestValidParenthesis.py ├── MinStack.py ├── MinStack_Optim.java ├── NearestSmallestElement.py ├── NextGreaterElement1.java ├── NumberOfAtoms.py ├── RemoveDuplicateLetters.java ├── Reverse_First_K_Queue.java ├── SlidingWindowMax_DequeBased.py ├── SlidingWindowMin.py ├── TrappingRainWater.py ├── ValidParentheses.py ├── balancing_parenthesis.py ├── dual_stack_sort.py └── nextGreaterLower.java ├── Tree ├── AVL_Insertion.py ├── BSTIterator.py ├── BTMaxPathSum.py ├── BinaryTreeMaximumPathSum.java ├── CountUnivalSubtrees.py ├── DeepestLeavesSum.py ├── Distance-Between-Nodes-In-BST.py ├── EqualTreePartition.java ├── Find-Leaves-Of-Binary_Tree.py ├── InorderSuccessorBST.py ├── InvertBinaryTree.py ├── LCA.py ├── LCA_BST.py ├── MergeTwoBinaryTrees.py ├── PrefixWordPrediction.py ├── Serialize_Deserialize_Binary_Tree.py ├── Sum-of-Left-Leaves.py ├── SumOfLeftLeaves.py ├── Vertical-Order-Traversal-of-a-Binary-Tree.py ├── delete-nodes-and-return-forest.py └── validate-bst.py ├── Trie ├── Add-and-Search-Word.py ├── SearchSuggestionSystem.py ├── StreamOfCharacters.py └── extra-characters-in-a-string.py ├── TwoPointerSW ├── 3Sum.py ├── BeautifulArrangement2.py ├── CF1278A_ShuffleHashing.py ├── FindAllAnagramsInAString.py ├── HIndex2.py ├── Intersection.cpp ├── LongestRepeatingCharReplacement.py ├── MinimumSizeSubarraySum.py ├── ProgrammerString.py ├── Squares_of_a_Sorted_Array.py ├── SubarrayProductLessThanK.java ├── SubarraySumK.cpp ├── TripletWithSumInRange.py ├── container-with-most-water.py ├── one-edit-distance.py └── trapping-rain-water.py ├── maximum-palindrome.py └── maximumGapProblem.py /.gitignore: -------------------------------------------------------------------------------- 1 | /LiveContest/* 2 | /Hiring/* 3 | .idea/ 4 | -------------------------------------------------------------------------------- /AdHoc/ACPC10A.cpp: -------------------------------------------------------------------------------- 1 | //www.spoj.com/problems/ACPC10A/ 2 | #include 3 | using namespace std; 4 | int main(){ 5 | int a,b,c; 6 | cin>>a>>b>>c; 7 | while(a!=0 || b!=0 || c!=0){ 8 | if(b-a==c-b){ 9 | //Arithmetic Progression 10 | cout<<"AP "<<(c+(b-a))<>a>>b>>c; 17 | } 18 | return 0; 19 | } -------------------------------------------------------------------------------- /AdHoc/ADDREV.py: -------------------------------------------------------------------------------- 1 | # Problem: https://www.spoj.com/IITRPRF1/problems/ADDREV/ 2 | 3 | def rev(n): 4 | st=str(n) 5 | st=st[::-1] 6 | s=int(st) 7 | return s 8 | 9 | t=int(input()) 10 | for _ in range(t): 11 | m,n=[int(x) for x in input().strip().split()] 12 | s=rev(m) + rev(n) 13 | print(rev(s)) -------------------------------------------------------------------------------- /AdHoc/ADDREV_IITROPAR.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int rev(int n){ 4 | int sum=0; 5 | while(n>0){ 6 | sum=(sum*10)+(n%10); 7 | n/=10; 8 | } 9 | return sum; 10 | } 11 | int main() 12 | { 13 | /* code */ 14 | int t; 15 | scanf("%d",&t); 16 | while(t--){ 17 | int m,n,r; 18 | scanf("%d %d",&m,&n); 19 | r = rev(m) + rev(n); 20 | r = rev(r); 21 | printf("%d\n",r); 22 | } 23 | return 0; 24 | } -------------------------------------------------------------------------------- /AdHoc/AE00.py: -------------------------------------------------------------------------------- 1 | #Problem: http://www.spoj.com/problems/AE00/ 2 | import math 3 | def T(n,N): 4 | return ((N-(n**2))//n)+1 5 | 6 | N=int(input()) 7 | reqsum=0 8 | k=int(math.sqrt(N)) 9 | for i in range(1,k+1): 10 | reqsum+=T(i,N) 11 | #print(T(i,N)) 12 | print(reqsum) -------------------------------------------------------------------------------- /AdHoc/ArrayDuplicates.py: -------------------------------------------------------------------------------- 1 | # LC 442 2 | class Solution: 3 | def findDuplicates(self, arr: List[int]) -> List[int]: 4 | reps = [] 5 | n = len(arr) 6 | for i in range(n): 7 | if arr[abs(arr[i])%n] > 0: 8 | arr[abs(arr[i])%n] = arr[abs(arr[i])%n] * -1 9 | else: 10 | reps.append(abs(arr[i])) 11 | return sorted(reps) 12 | 13 | -------------------------------------------------------------------------------- /AdHoc/ArrayRotation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size N, rotate it by D elements. 3 | 4 | https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements/0/?track=placement 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | int t; 12 | cin >> t; 13 | while(t--){ 14 | int n,d; 15 | cin >> n; 16 | int arr[n]; 17 | cin >> d; 18 | for(int i=0;i> arr[i]; 20 | } 21 | //on rotation by d places 22 | for(int i=(d%n);i 9 | using namespace std; 10 | typedef long long ll; 11 | #define test ll t; cin >> t; while(t--) 12 | int main() 13 | { 14 | test 15 | { 16 | ll c,d,l; 17 | cin >> c >> d >> l; 18 | if((l-(4*d))<0 or l%4!=0) 19 | cout << "no" << endl; 20 | else 21 | { 22 | ll maxim=(c+d)*4; //everyone stands on their own leg 23 | ll minim=(d*4)+max((ll)0,((c-(2*d))*4)); 24 | if(minim<=l and l<=maxim) 25 | cout << "yes" << endl; 26 | else 27 | cout << "no" << endl; 28 | } 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /AdHoc/CF100C.py: -------------------------------------------------------------------------------- 1 | a0 = '376782365465497859' 2 | a0 = '87489543528930998385608359876385765806784785670487869469874896789457064' 3 | b0 = '87567948756746869874' 4 | b0 = '8578493780570495789469548699569346098358063345873895380949288945445403584' 5 | a = list(a0) 6 | b = list(b0) 7 | 8 | if(len(a)!=len(b)): 9 | padding = len(a)-len(b) 10 | if(padding > 0): 11 | #a is longer 12 | pad = [0]*padding 13 | b = pad + b 14 | elif(padding <0): 15 | #b is longer 16 | pad = [0]*(abs(padding)) 17 | a = pad + a 18 | 19 | c = [] 20 | carry = 0 21 | for i in range(len(a)-1,-1,-1): 22 | val = int(a[i]) + int(b[i]) + carry 23 | carry = 0 24 | if(val > 9): 25 | c.append(str(val%10)) 26 | carry = val//10 27 | else: 28 | c.append(str(val)) 29 | c.append(str(carry)) 30 | c.reverse() 31 | output = ''.join(c) 32 | print(output.lstrip('0')) 33 | 34 | #print(int(a0)+int(b0)) -------------------------------------------------------------------------------- /AdHoc/CF106A.py: -------------------------------------------------------------------------------- 1 | trump = str(input()) 2 | carda, cardb = [str(x) for x in input().strip().split()] 3 | win = 0 4 | deck = ["6", "7", "8", "9", "T", "J", "Q", "K", "A"] 5 | ranka = deck.index(carda[0]) 6 | rankb = deck.index(cardb[0]) 7 | if(carda[1]==cardb[1]): 8 | #same suit 9 | if(ranka > rankb): 10 | win=1 11 | elif(ranka < rankb): 12 | win=2 13 | else: 14 | if(carda[1]==trump[0]): 15 | win=1 16 | elif(cardb[1]==trump[0]): 17 | win=2 18 | 19 | if(win==1): 20 | print("YES") 21 | else: 22 | print("NO") 23 | 24 | -------------------------------------------------------------------------------- /AdHoc/CHBLLNS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Amitrajit Bose 3 | * Problem Link:www.codechef.com/problems/CHBLLNS 4 | * Approach: 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | typedef long long ll; 13 | #define FOR(i,m,n) for(__typeof(n) i = m; i<(n); i++) 14 | #define test ll t; cin >> t; while(t--) 15 | int main() 16 | { 17 | test 18 | { 19 | ll a[3]; 20 | ll k; 21 | FOR(i,0,3) 22 | { 23 | cin >> a[i]; 24 | } 25 | cin >> k; 26 | sort(a,a+3); 27 | ll c=0; 28 | if(k==1) 29 | c=1; 30 | else 31 | { 32 | if(a[0]>=k) 33 | c = k + 2*(k-1); 34 | else if(a[1]>=k) 35 | c = a[0] + k + (k-1); 36 | else if(a[2]>=k) 37 | c = a[0] + a[1] + k; 38 | } 39 | cout << c << endl; 40 | } 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /AdHoc/CO92JUDG.cpp: -------------------------------------------------------------------------------- 1 | // @Amitrajit Bose 2 | // https://www.codechef.com/problems/CO92JUDG 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int t; 8 | cin >> t; 9 | while(t--){ 10 | int n; 11 | cin >> n; 12 | int a[n],b[n]; 13 | 14 | for(int i=0;i> a[i]; 16 | } 17 | 18 | for(int i=0;i> b[i]; 20 | } 21 | int maxa=a[0]; 22 | int suma=a[0]; 23 | int maxb=b[0]; 24 | int sumb=b[0]; 25 | 26 | for(int i=1;i int: 5 | ans = 0 6 | n = len(height) 7 | l = 0 8 | r = n - 1 9 | #ans = min(height[l], height[r]) * (r-l) 10 | while(l != r): 11 | if(height[l] < height[r]): 12 | ans = max(ans, height[l] * (r-l)) 13 | l += 1 14 | else: 15 | ans = max(ans, height[r] * (r-l)) 16 | r -= 1 17 | #ans = max(ans, min(height[l], height[r]) * (r-l)) 18 | return ans 19 | 20 | ''' 21 | [1,8,6,2,5,4,8,3,7] 22 | [1,3,7,3,8,2,1,6,8,9,7,3,2,6,8,2,1,5,6,8,9,0,3,2,5] 23 | [1,2,4,3] 24 | ''' 25 | -------------------------------------------------------------------------------- /AdHoc/ConvertToHex.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toHex(self, num: int) -> str: 3 | val = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] 4 | if num < 0: 5 | num += (16**8) 6 | ans = '' 7 | res = num 8 | while res>=16: 9 | ans = val[res%16] + ans 10 | res = res // 16 11 | 12 | return val[res]+ans 13 | 14 | 15 | def toHexEasy(self, num: int) -> str: 16 | if num >= 0: 17 | return (hex(num))[2:] 18 | else: 19 | return hex((16**8)+num)[2:] -------------------------------------------------------------------------------- /AdHoc/EIGHTS.cpp: -------------------------------------------------------------------------------- 1 | //http://www.spoj.com/problems/EIGHTS/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | long long int t; 8 | cin>>t; 9 | while(t--) 10 | { 11 | long long int k; 12 | long long int out; 13 | cin>>k; 14 | if(k==1) 15 | out=192; 16 | else 17 | out=192+((k-1)*250); 18 | 19 | cout< 0: 7 | newlist.append(A[i]) 8 | return newlist 9 | 10 | def firstMissingPositive(self, nums: List[int]) -> int: 11 | A = self.dropNegatives(nums) 12 | if len(A)==0: 13 | return 1 14 | if len(A)==1: 15 | return 1 if A[0] >= 2 else 2 16 | else: 17 | n = len(A) 18 | for i in range(n): 19 | item = abs(A[i]) 20 | if item <= n: 21 | A[item-1] = -1 * abs(A[item-1]) 22 | res = len(A) + 1 23 | for i in range(n): 24 | if A[i] > 0: 25 | return i+1 26 | return res 27 | 28 | -------------------------------------------------------------------------------- /AdHoc/FlightRangeBookings.py: -------------------------------------------------------------------------------- 1 | # LC 1109 2 | class Solution: 3 | # @param bookings : list of list of integers 4 | # @param n : integer 5 | # @return a list of integers 6 | def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: 7 | mem = [0]*(n+2) 8 | # first 0 will be ignored, because 1 based index, last 0 will be needed 9 | for item in bookings: 10 | mem[item[0]] += item[2] 11 | mem[item[1]+1] -= item[2] 12 | for i in range(2,n+1): 13 | mem[i] += mem[i-1] 14 | return mem[1:-1] 15 | 16 | -------------------------------------------------------------------------------- /AdHoc/FlippingAnImage.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 3 | for i in range(len(A)): 4 | A[i] = A[i][::-1] # reversing 5 | for j in range(len(A[i])): 6 | A[i][j] ^= 1 7 | return A 8 | 9 | -------------------------------------------------------------------------------- /AdHoc/HackerRankLogo.py: -------------------------------------------------------------------------------- 1 | #Problem: https://www.hackerrank.com/challenges/text-alignment/problem 2 | 3 | thickness = int(input("Enter Thickness (Odd Positive Integer): ")) #This must be an odd number 4 | c = 'H' 5 | 6 | #Top Cone 7 | for i in range(thickness): 8 | print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) 9 | 10 | #Top Pillars 11 | for i in range(thickness+1): 12 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)), 13 | 14 | #Middle Belt 15 | for i in range((thickness+1)//2): 16 | print((c*thickness*5).center(thickness*6)) 17 | 18 | #Bottom Pillars 19 | for i in range(thickness+1): 20 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 21 | 22 | #Bottom Cone 23 | for i in range(thickness): 24 | print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)) 25 | 26 | x=input("Press Enter Key To Exit") #Optional 27 | -------------------------------------------------------------------------------- /AdHoc/LargestNumberAtleastTwice.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-number-at-least-twice-of-others/ 2 | class Solution: 3 | def dominantIndex(self, nums: List[int]) -> int: 4 | maxidx = nums.index(max(nums)) 5 | maxval = nums[maxidx] 6 | flag = True 7 | for i in nums: 8 | if i != maxval and i != 0: 9 | if (maxval // i) < 2: 10 | return -1 11 | return(maxidx) 12 | 13 | -------------------------------------------------------------------------------- /AdHoc/MAJOR.py: -------------------------------------------------------------------------------- 1 | # This Fetches TLE 2 | # Expected Approach O(n) 3 | # Moore's Voting Algorithm - [Majority Element] 4 | 5 | # This problem has a good implementation of Python dictionary. Thus kept intentionally. 6 | # Problem : SPOJ -> MAJOR 7 | 8 | from collections import Counter 9 | 10 | t=int(input()) 11 | 12 | for _ in range(t): 13 | n=int(input()) 14 | A=[int(x) for x in input().strip().split()] 15 | D=dict(Counter(A)) 16 | 17 | #find the maximum occurance 18 | mymax=(max(list(D.values()))) 19 | 20 | #find the item with maximum occurance 21 | ans=list(D.keys())[list(D.values()).index(mymax)] 22 | 23 | #check if condition is satisfied 24 | if(mymax > n//2): 25 | print("YES {0}".format(ans)) 26 | else: 27 | print("NO") 28 | -------------------------------------------------------------------------------- /AdHoc/MaxChunksToMakeSorted2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return an integer 4 | def solve(self, A): 5 | preA = [0] 6 | for i in range(len(A)): 7 | preA.append(preA[-1]+A[i]) 8 | A.sort() 9 | preB = [0] 10 | for i in range(len(A)): 11 | preB.append(preB[-1]+A[i]) 12 | chunks = 0 13 | for i in range(1,len(A)+1): 14 | if preA[i] == preB[i]: 15 | chunks += 1 16 | return chunks 17 | 18 | -------------------------------------------------------------------------------- /AdHoc/MaxDistance.py: -------------------------------------------------------------------------------- 1 | #https://www.interviewbit.com/problems/max-distance/ 2 | def maximumGap(A): 3 | left = [A[0]] 4 | right = [A[-1]] 5 | n = len(A) 6 | for i in range(1,n): 7 | left.append(min(left[-1], A[i])) 8 | for i in range(n-2, -1, -1): 9 | right.insert(0, max(right[0], A[i])) 10 | i,j,gap = 0, 0, -1 11 | while (i < n and j < n): 12 | if left[i] < right[j]: 13 | gap = max(gap, j-i) 14 | j += 1 # look for a larger gap 15 | else: 16 | i += 1 17 | return gap 18 | 19 | # test cases 20 | assert(maximumGap([3,5,4,2])==2) 21 | assert(maximumGap([3,2,1,0])==-1) -------------------------------------------------------------------------------- /AdHoc/MissingNumber.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/find-the-missing-number/ 2 | #include 3 | using namespace std; 4 | int findMissingNumber(int a[],int n){ 5 | int i,t; 6 | t=(n+1)*(n+2)/2; //considering the missing number in total 7 | for(i=0;i>n; 16 | cout<<"Enter The Numbers: "; 17 | int a[n]; 18 | for(int i=0;i>a[i]; 20 | } 21 | cout< int: 4 | digits = [int(x) for x in list(str(n))] 5 | ln = len(digits) 6 | A = -1 7 | for i in range(ln-2, -1, -1): 8 | if digits[i] < digits[i+1]: 9 | A = i 10 | break 11 | if A == -1: 12 | return A 13 | 14 | for i in range(ln-1, A, -1): 15 | if digits[i] > digits[A]: 16 | B = i 17 | break 18 | digits[A], digits[B] = digits[B], digits[A] # swap 19 | left = digits[: A + 1] 20 | right = sorted(digits[A + 1 :]) 21 | digits = left + right 22 | str_digits = [str(x) for x in digits] 23 | m = int(''.join(str_digits)) 24 | if m >= -(2**31) and m < (2**31)-1: 25 | return m 26 | else: 27 | return -1 28 | 29 | 30 | -------------------------------------------------------------------------------- /AdHoc/Panda_And_Chain_Reaction_HackerEarth.cpp: -------------------------------------------------------------------------------- 1 | // @amitrajitbose 2 | #include 3 | using namespace std; 4 | typedef long long ll; 5 | #define MOD 1000003 6 | 7 | int main() 8 | { 9 | ll fact[MOD]; 10 | fact[0]=1; 11 | fact[1]=1; 12 | fact[2]=2; 13 | for(ll i=3;i> t; 17 | while(t--) 18 | { 19 | ll n,x; 20 | cin >> n >> x; 21 | if(n 23 | using namespace std; 24 | int feymannsquare(int n){ 25 | return (n*(n+1)*((2*n)+1))/6; 26 | } 27 | int main(){ 28 | int inp; 29 | cin>>inp; 30 | while(inp!=0){ 31 | cout<>inp; 33 | } 34 | return 0; 35 | } -------------------------------------------------------------------------------- /AdHoc/ShortestUnsortedContinuousSubarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findUnsortedSubarray(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | if n <= 1: 5 | return 0 6 | else: 7 | minm, maxm, flag = float('inf'), -float('inf'), False 8 | for i in range(1,n): 9 | if nums[i] < nums[i-1]: 10 | flag = True 11 | if flag: 12 | minm = min(minm, nums[i]) 13 | flag = False 14 | for i in range(n-2,-1,-1): 15 | if nums[i] > nums[i+1]: 16 | flag = True 17 | if flag: 18 | maxm = max(maxm, nums[i]) 19 | for l in range(n): 20 | if minm < nums[l]: 21 | break 22 | for r in range(n-1,-1,-1): 23 | if maxm > nums[r]: 24 | break 25 | return 0 if r-l <= 0 else r-l+1 26 | 27 | 28 | """ 29 | [2,3,3,2,4] 30 | [2,6,4,8,10,9,15] 31 | [2,1] 32 | [2,1,3] 33 | [3,2,1] 34 | """ 35 | -------------------------------------------------------------------------------- /AdHoc/TriangularSeries.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Triangular Series : 1,3,6,10,15,21,28... 3 | Given a number n, find its position in the triangular series (nearest smaller or equal to value). 4 | For example: n=8, output=6 5 | ''' 6 | ''' 7 | Approach: Sridhara Acharya 8 | (n(n+1))/2 = nth element in triangular series 9 | We need to calculate n given the element is known 10 | ''' 11 | from math import floor 12 | from math import sqrt 13 | def find(n): 14 | k = (floor(sqrt(4*2*n))-1)//2 15 | val = ((k+1)*(k+2))//2 16 | if(val == n): 17 | return n 18 | else: 19 | return (k*(k+1))//2 20 | 21 | assert find(6)==6 22 | assert find(8)==6 23 | assert find(10)==10 24 | assert find(16)==15 -------------------------------------------------------------------------------- /AdHoc/UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | // LC 62 2 | long long int comb(int m,int n) 3 | { 4 | long long int res = 1, i; 5 | int a=(m>n)? m: n; 6 | for (i=m+n-2;i>=a; i--) 7 | res *= i; 8 | return res; 9 | } 10 | 11 | long long int fact(int n) 12 | { 13 | long long int res=1,i; 14 | for(i=2;i<=n;i++) 15 | res*=i; 16 | return res; 17 | } 18 | 19 | int Solution::uniquePaths(int m, int n) { 20 | long long int a,k=comb(m,n); 21 | if(m int: 3 | if A==1 or B==1: 4 | return 1 5 | if A==2 or B==2: 6 | return max(A,B) 7 | ans = 1 8 | for i in range(max(A,B), A+B-1): 9 | ans *= i 10 | ans //= (i-max(A,B)+1) 11 | return ans 12 | 13 | # LC 62 Medium 14 | -------------------------------------------------------------------------------- /AdHoc/WILLITST.py: -------------------------------------------------------------------------------- 1 | #www.spoj.com/problems/WILLITST 2 | n=int(input()) 3 | bin=str(bin(n))[2:] 4 | ones=bin.count('1') 5 | if(bin[0]=='1' and ones==1): 6 | print("TAK") 7 | else: 8 | print("NIE") -------------------------------------------------------------------------------- /AdHoc/corporate-flight-bookings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: 3 | pre = [0] * (n + 1) # prefix sum 4 | for i,j,k in bookings: 5 | pre[i-1] += k 6 | pre[j] -= k 7 | for i in range(1, n+1): 8 | pre[i] += pre[i-1] 9 | pre.pop(-1) 10 | return pre 11 | -------------------------------------------------------------------------------- /AdHoc/first-missing-positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | positive_nums = [] 4 | for i in range(len(nums)): 5 | if nums[i] > 0: 6 | positive_nums.append(nums[i]) 7 | for i in range(len(positive_nums)): 8 | num = abs(positive_nums[i]) 9 | if num <= len(positive_nums): 10 | positive_nums[num-1] = -1 * abs(positive_nums[num-1]) 11 | smallest = 1 12 | while smallest <= len(positive_nums): 13 | if positive_nums[smallest-1] > 0: 14 | return smallest 15 | smallest += 1 16 | return smallest 17 | 18 | -------------------------------------------------------------------------------- /AdHoc/nthNonFibonacci.cpp: -------------------------------------------------------------------------------- 1 | // Program to display the n-th non-fibonacci number 2 | #include 3 | using namespace std; 4 | int main(){ 5 | int n; 6 | cin>>n; 7 | int a,b,c,tmp; 8 | a=0; 9 | b=1; 10 | c=n; 11 | /* 12 | a,b are for generating the fibonacci sequence 13 | c stores a copy of n 14 | tmp is used for temporary purpose 15 | */ 16 | while(b-a-11) 18 | c-=(b-a-1); 19 | tmp=a; 20 | a=b; 21 | b=tmp+b; 22 | } 23 | cout<<(a+c)< List[str]: 3 | if not digits: 4 | return [] 5 | 6 | self.pad = [ 7 | [], [], 8 | ['a','b','c'], 9 | ['d','e','f'], 10 | ['g','h','i'], 11 | ['j','k','l'], 12 | ['m','n','o'], 13 | ['p','q','r','s'], 14 | ['t','u','v'], 15 | ['w','x','y','z'] 16 | ] 17 | 18 | self.res = [] 19 | self.dfs(list(digits)) 20 | return self.res 21 | 22 | def dfs(self, digits, patt = "", idx = 0): 23 | if len(digits) == idx: 24 | self.res.append(patt) 25 | else: 26 | x = int(digits[idx]) 27 | for ch in self.pad[x]: 28 | self.dfs(digits, patt + ch, idx + 1) 29 | -------------------------------------------------------------------------------- /Backtracking/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Backtracking/a.out -------------------------------------------------------------------------------- /Backtracking/generate-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n: int) -> List[str]: 3 | res = [] 4 | def backtrack(s = '', left = 0, right = 0): 5 | if len(s) == 2*n: 6 | res.append(s) 7 | return 8 | if left < n: 9 | backtrack(s+'(', left+1, right) 10 | if right < left: 11 | backtrack(s+')', left, right+1) 12 | backtrack() 13 | return res 14 | -------------------------------------------------------------------------------- /Backtracking/letter-combinations-of-a-phone-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | numpad = { 4 | '2':['a','b','c'], 5 | '3':['d','e','f'], 6 | '4':['g','h','i'], 7 | '5':['j','k','l'], 8 | '6':['m','n','o'], 9 | '7':['p','q','r','s'], 10 | '8':['t','u','v'], 11 | '9':['w','x','y','z'] 12 | } 13 | res = [] 14 | # this is the backtracking part 15 | def calc(comb: str, nextdigits: str) -> None: 16 | if len(nextdigits) == 0: 17 | res.append(comb) # base condition 18 | else: 19 | for ch in numpad[nextdigits[0]]: 20 | calc(comb + ch, nextdigits[1:]) # recurse 21 | if len(digits) > 0: 22 | calc("", digits) 23 | return res 24 | -------------------------------------------------------------------------------- /BitManipulation/PowerOfFour.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | def isPowerOfFour(self, n: int) -> bool: 4 | return n > 0 and n == (4 ** (math.log2(n) // 2)) 5 | -------------------------------------------------------------------------------- /BitManipulation/PowerOfThree.py: -------------------------------------------------------------------------------- 1 | threePow19 = 1162261467 # 3**19 2 | class Solution: 3 | def isPowerOfThree(self, n: int) -> bool: 4 | return n>0 and not (threePow19 % n) 5 | -------------------------------------------------------------------------------- /BitManipulation/PowerOfTwo.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, n: int) -> bool: 3 | return n and not(n & (n-1)) # and n to handle n=0 4 | -------------------------------------------------------------------------------- /BitManipulation/number-of-steps-to-reduce-a-number-to-zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSteps (self, num: int) -> int: 3 | if num == 0: 4 | return 0 5 | binary = bin(num)[3:] 6 | return len(binary) + binary.count('1') + 1 7 | -------------------------------------------------------------------------------- /CF1114A.py: -------------------------------------------------------------------------------- 1 | a,d,m = [int(x) for x in input().strip().split()] 2 | g,p,b = [int(x) for x in input().strip().split()] 3 | flag = 1 4 | if(g 2 | #include 3 | 4 | int cmpfunc (const void * a, const void * b) { 5 | return ( *(int*)a > *(int*)b ); 6 | } 7 | void binarysearch(int arr[], int n, int k, int left, int right) 8 | { 9 | int mid=(int)((left+right)/2); 10 | if(rightk) 23 | binarysearch(arr,n,k,left,mid-1); 24 | } 25 | int main() 26 | { 27 | int i,n,searchkey; 28 | int arr[]={4,2,6,1,8,5,3}; 29 | n=sizeof(arr)/sizeof(arr[0]); 30 | searchkey=3; 31 | qsort(arr, n, sizeof(int), cmpfunc); 32 | binarysearch(arr,n,searchkey,0,n-1); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /CS591/DivideConquer/MaxMinNumber.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int max,min; //globally declared 5 | void maxmin(int arr[], int l, int r) 6 | { 7 | if(r-l==0) 8 | { 9 | max=arr[l]; 10 | min=arr[l]; //this case will arise for odd length arrays 11 | } 12 | else if(r-l==1) 13 | { 14 | max=(arr[l]>=arr[r])?arr[l]:arr[r]; //for even length arrays 15 | min=(arr[l]max)?tmax:max; 25 | min=(tmin 2 | #include 3 | void swap(int *a, int *b) 4 | { 5 | int t=*a; 6 | *a=*b; 7 | *b=t; 8 | } 9 | int partition(int arr[], int p, int r) 10 | { 11 | int pivot=arr[r]; 12 | int pIndex=p; 13 | int i; 14 | for(i=p;i 2 | #include 3 | #define INF 999999 4 | 5 | int min(int a, int b) 6 | { 7 | return (a>b)?b:a; 8 | } 9 | 10 | int main() 11 | { 12 | int n=5; //number of vertices 13 | int A[5][5]={ 14 | {0, 1, -1, 1, 5}, 15 | {9, 0, 3, 2, -1}, 16 | {-1,-1,0,4,-1}, 17 | {-1,-1,2,0,3}, 18 | {3,-1,-1,-1,0}}; 19 | //convert -1 edges(no edge) to infinities 20 | int i,j,k,num; 21 | for(i=0;i 2 | #include 3 | 4 | void dfs(int v,int n, int adj[][n], int visited[]) 5 | { 6 | visited[v]=1; 7 | printf("Visit: %d\n",v); 8 | int w; 9 | for(w=0;w0 && !visited[w]) 12 | { 13 | dfs(w,n,adj,visited); 14 | } 15 | } 16 | } 17 | int main() 18 | { 19 | int adj[4][4]={ 20 | {0,0,1,10}, 21 | {1,0,3,1}, 22 | {1,1,0,1}, 23 | {1,1,1,0} 24 | }; 25 | int visited[]={0,0,0,0}; 26 | dfs(0,4,adj,visited); 27 | return 0; 28 | } -------------------------------------------------------------------------------- /CS591/Graph/tmp.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/CS591/Graph/tmp.c -------------------------------------------------------------------------------- /Contests/CF1343/1343A.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left as bs 2 | def prefetch(): 3 | lis = [] 4 | s = 0 5 | p = 0 6 | x = 0 7 | while s < 10**9: 8 | s += (2**p) 9 | p += 1 10 | lis.append(s) 11 | return lis 12 | 13 | def main(): 14 | lhs = prefetch() 15 | for _ in range(int(input())): 16 | n = int(input().strip()) 17 | ind = bs(lhs, n) 18 | for i in range(ind, -1, -1): 19 | if(n % lhs[i] == 0): 20 | print(n//lhs[i]) 21 | break 22 | main() 23 | 24 | -------------------------------------------------------------------------------- /Contests/CF1343/1343B.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for _ in range(int(input())): 3 | n = int(input().strip()) 4 | if ((n//2)%2): 5 | print("NO") 6 | else: 7 | arr = [2*i for i in range(1,(n//2)+1)] 8 | accu = 0 9 | for i in range((n//2)-1): 10 | arr.append(arr[i]-1) 11 | accu += 1 12 | arr.append(arr[(n//2)-1] + accu) 13 | print("YES") 14 | last = arr.pop(-1) 15 | for i in arr: 16 | print(i, end=" ") 17 | print(last) 18 | main() 19 | 20 | -------------------------------------------------------------------------------- /Contests/Chef_APRIL20B/STRNO.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | for _ in range(int(input())): 3 | x, k = map(int, input().strip().split()) 4 | divisors = 0 5 | i = 2 6 | while i**2 <= x: 7 | if (x%i): 8 | i += 1 9 | else: 10 | while not (x%i): 11 | #print (x, i) 12 | divisors += 1 13 | x //= i 14 | if x > 1: 15 | divisors += 1 # because 1 is divisor for any number 16 | res = 1 if divisors >= k else 0 17 | print(res) 18 | #print(res, divisors) 19 | 20 | -------------------------------------------------------------------------------- /Contests/Chef_AUG18/Modular GCD/Final_ModularGCD.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | if(a==0): 3 | return b 4 | return gcd(b%a,a) 5 | 6 | T=int(input()) 7 | for i in range(0,T): 8 | inp = list(map(int,input().split())) 9 | a=inp[0] 10 | b=inp[1] 11 | n=inp[2] 12 | diff=0 13 | if(a>b): 14 | diff=a-b 15 | else: 16 | diff=b-a 17 | if(a==b): 18 | print((pow(a,n,1000000007)+pow(b,n,1000000007))%1000000007) 19 | elif(n>=2): 20 | print(gcd(((pow(a,2)+pow(b,2))),diff)) 21 | elif(n==1): 22 | print(gcd((a+b),diff)) -------------------------------------------------------------------------------- /Contests/Chef_AUG18/Modular GCD/GCDMOD2.py: -------------------------------------------------------------------------------- 1 | #Problem: https://www.codechef.com/AUG18B/problems/GCDMOD 2 | #Author : Amitrajit Bose 3 | 4 | MOD = (10**9)+7 5 | # Function to return gcd of a and b 6 | def gcd(a, b): 7 | if a == 0 : 8 | return b 9 | 10 | return gcd(b%a, a) 11 | 12 | def power(x, y, p) : 13 | res = 1 14 | x = x % p 15 | 16 | while (y > 0) : 17 | if ((y & 1) == 1) : 18 | res = (res * x) % p 19 | 20 | # y must be even now 21 | y = y >> 1 # y = y/2 22 | x = (x * x) % p 23 | 24 | return res 25 | 26 | # MAIN 27 | test=int(input()) 28 | for _ in range(test): 29 | a,b,n = [int(x) for x in input().strip().split()] 30 | one = (power(a, n, MOD) + power(b, n, MOD)) 31 | two = abs(a-b) 32 | out = gcd(one, two) % MOD 33 | print(out) -------------------------------------------------------------------------------- /Contests/Chef_AUG18/Modular GCD/Trash.txt: -------------------------------------------------------------------------------- 1 | ''' 2 | #Stein's Algorithm 3 | def gcd(a, b) : 4 | 5 | if (a == b) : 6 | return a 7 | 8 | if (a == 0) : 9 | return b 10 | 11 | if (b == 0) : 12 | return a 13 | 14 | if ((~a & 1)== 1 ) : 15 | 16 | # b is odd 17 | if ((b & 1)== 1) : 18 | return gcd(a >> 1, b) 19 | else : 20 | # both a and b are even 21 | return (gcd(a >> 1, b >> 1) << 1) 22 | 23 | # a is odd, b is even 24 | if ((~b & 1)== 1) : 25 | return gcd(a, b >> 1) 26 | 27 | # reduce larger number 28 | if (a > b) : 29 | return gcd((a - b) >> 1, b) 30 | 31 | return gcd((b - a) >> 1, a) 32 | 33 | #Fast Exponentiation 34 | def power(x, y, p) : 35 | res = 1 36 | x = x % p 37 | 38 | while (y > 0) : 39 | if ((y & 1) == 1) : 40 | res = (res * x) % p 41 | 42 | # y must be even now 43 | y = y >> 1 # y = y/2 44 | x = (x * x) % p 45 | 46 | return res 47 | ''' -------------------------------------------------------------------------------- /Contests/Chef_AUG18/SHKNUM.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://www.codechef.com/AUG18B/problems/SHKNUM 2 | import math 3 | def upper(x): 4 | if(x==0): 5 | return 1 6 | return (math.ceil(math.log(x)/math.log(2))) 7 | 8 | def lower(x): 9 | if(x==0): 10 | return 1 11 | return (math.floor(math.log(x)/math.log(2))) 12 | 13 | def oneEnd(x): 14 | rem=x 15 | i=1 16 | while(rem!=0): 17 | rem=(x//i)-1 18 | i=i*2 19 | return (i//2) 20 | 21 | def mmain(n): 22 | oE = oneEnd(n) 23 | x = n - oE 24 | if(n==1): 25 | return 2; 26 | elif(upper(n)==lower(n)): 27 | return 1; 28 | elif((oE == 2**upper(x))): 29 | out2=abs(x - 2**lower(x)) 30 | oE = (oE*2)+1 31 | out1=abs(oE-n) 32 | return min(out1,out2) 33 | 34 | 35 | x = n - oneEnd(n) 36 | ud = abs(2**upper(x) - x) 37 | ld = abs(x - 2**lower(x)) 38 | out = min(ld,ud) 39 | return out 40 | 41 | test=int(input()) 42 | for _ in range(test): 43 | n = int(input()) 44 | print(mmain(n)) 45 | 46 | -------------------------------------------------------------------------------- /Contests/Chef_AUG18/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/Chef_AUG18/a.out -------------------------------------------------------------------------------- /Contests/Chef_AUG18/inputProbSort.txt: -------------------------------------------------------------------------------- 1 | 3 3 2 | 16 24 60 3 | 498 861 589 4 | 14 24 62 5 | 72 1557 819 6 | 16 15 69 7 | 435 779 232 8 | -------------------------------------------------------------------------------- /Contests/Chef_AUG18/inputSpellbob.txt: -------------------------------------------------------------------------------- 1 | 7 2 | bob 3 | rob 4 | dbc 5 | ocb 6 | boc 7 | obc 8 | bba 9 | ooo 10 | bob 11 | bba 12 | bbb 13 | ooo 14 | kkk 15 | ooo 16 | -------------------------------------------------------------------------------- /Contests/Chef_COCE2018/LUCAS1.py: -------------------------------------------------------------------------------- 1 | t=int(input()) 2 | for _ in range(t): 3 | freq=[0 for x in range(26)] 4 | s=list(str(input())) 5 | for ch in s: 6 | freq[ord(ch)-97]+=1 7 | freq=filter(lambda a: a != 0, freq) 8 | freq=sorted(freq) 9 | 10 | flag=True 11 | if(freq[0]==1 and freq[1]==2 and len(freq)>2): 12 | freq[0]=2 13 | freq[1]=1 14 | for i in range(2,len(freq)): 15 | if(freq[i] != (freq[i-1]+freq[i-2])): 16 | flag=False 17 | if(flag==True): 18 | print("FIT") 19 | else: 20 | print("UNFIT") 21 | elif(freq[0]==1 and freq[1]==2 and len(freq)==2) or (len(freq)==1 and freq[0]==2): 22 | print("FIT") 23 | else: 24 | print("UNFIT") 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Contests/Chef_COCE2018/QUERARR.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left as bsl 2 | n=int(input()) 3 | arr=[int(x) for x in input().strip().split()] 4 | arr=sorted(arr) 5 | q=int(input()) 6 | for _ in range(q): 7 | low,high,val=[int(x) for x in input().strip().split()] 8 | p=bsl(arr[low:high],val) 9 | #print(p+low) 10 | if(arr[p+low]==val): 11 | print("yes") 12 | else: 13 | print("no") 14 | 15 | -------------------------------------------------------------------------------- /Contests/Chef_COCE2018/inp.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 1 2 3 7 9 3 | 5 4 | 0 3 1 5 | 0 0 1 6 | 0 3 3 7 | 0 3 7 8 | 0 3 9 9 | 10 | -------------------------------------------------------------------------------- /Contests/Chef_COOK98/ATM2.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Author: Amitrajit Bose 4 | * Problem Link: 5 | * Approach: 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | typedef long long ll; 14 | #define rep(m,n) for(i=m; i<(n); i++) 15 | #define test ll t; cin>>t; while(t--) 16 | int main() 17 | { 18 | test 19 | { 20 | ll n,k,x; 21 | cin >> n >> k; 22 | //cout << n << " " << k <> x; 28 | if(x<=k){ 29 | k-=x; 30 | gets[i]=1; //marked 31 | } 32 | } 33 | for(ll i=0;i 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | typedef long long ll; 14 | #define rep(i,m,n) for(i = m; i < (n); i++) 15 | #define test ll t; cin >> t; while(t--) 16 | int main() 17 | { 18 | test 19 | { 20 | int n; 21 | cin >> n; 22 | ll cnt=0; 23 | ll i,x; 24 | int *marker = new int[n+1]; 25 | 26 | fill(marker, marker+n+1, 0); 27 | //memset(marker, 0, sizeof(marker)); 28 | 29 | rep(i,1,n+1){ 30 | cin >> x; 31 | if(x>n or marker[x]==1) 32 | cnt++; 33 | else 34 | marker[x]=1; 35 | } 36 | cout << cnt << endl; 37 | delete [] marker; 38 | marker=NULL; 39 | } 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Contests/Chef_COOK98/OETW2.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | * Author: Amitrajit Bose 5 | * Problem Link: 6 | * Approach: 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | using namespace std; 14 | typedef long long ll; 15 | #define rep(i,m,n) for(i = m; i < (n); i++) 16 | #define test ll t; cin >> t; while(t--) 17 | 18 | int main() 19 | { 20 | test 21 | { 22 | ll i, n; 23 | cin >> n; 24 | 25 | int *arr = new int[n]; 26 | ll ones=0; 27 | ll twos=0; 28 | 29 | rep(i,0,n) 30 | { 31 | cin >> arr[i]; 32 | if(arr[i]==1) 33 | ones+=1; 34 | else 35 | twos+=1; 36 | } 37 | // if all ones or all twos 38 | if(twos==0 or ones==0) 39 | cout << n << endl; 40 | else 41 | { 42 | ll sum=accumulate(arr,arr+n,0); 43 | if(arr[0]==2 and arr[n-1]==2) 44 | cout << sum-1 << endl; 45 | else 46 | cout << sum << endl; // only because digits can be 1 or 2 47 | } 48 | delete [] arr; 49 | arr = NULL; 50 | } 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Contests/Chef_COW2018/BDMS.py: -------------------------------------------------------------------------------- 1 | def bdms(n,k): 2 | if(n==0): 3 | return 0 4 | else: 5 | # n not zero 6 | if(n%2==0): 7 | kick = n//2 8 | n2 = kick 9 | n1 = 0 10 | else: 11 | kick = (n//2) + 1 12 | n2 = kick-1 13 | n1 = 1 14 | if(kick%k==0): 15 | return kick 16 | else: 17 | while(kick%k != 0 and n2>0): 18 | kick+=1 19 | n2-=1 20 | n1+=2 21 | if(n2==0): 22 | return -1 23 | return kick 24 | 25 | 26 | n,k=[int(x) for x in input().strip().split()] 27 | ans=bdms(n,k) 28 | print(bdms(n,k)) -------------------------------------------------------------------------------- /Contests/Chef_COW2018/DSI2.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | male=[0]*400 3 | female=[0]*400 4 | maxim=0 5 | for i in range(n): 6 | a,b,c=[x for x in input().strip().split()] 7 | b=int(b) 8 | c=int(c) 9 | if a=='M': 10 | for j in range(b,c+1): 11 | male[j]+=1 12 | else: 13 | for j in range(b,c+1): 14 | female[j]+=1 15 | for i in range(0,400): 16 | maxim=max(maxim,min(male[i],female[i])) 17 | 18 | print(maxim) -------------------------------------------------------------------------------- /Contests/Chef_COW2018/TA1.py: -------------------------------------------------------------------------------- 1 | # https://math.stackexchange.com/questions/1656120/formula-to-find-the-first-intersection-of-two-arithmetic-progressions 2 | 3 | from math import gcd 4 | x,p=[int(x) for x in input().strip().split()] 5 | y,q=[int(x) for x in input().strip().split()] 6 | origx=x 7 | if(abs(p-q) % gcd(x,y) != 0): 8 | print("-1") 9 | else: 10 | # they will meet 11 | rhs = (q-p)+(x-y) 12 | #print("RHS",rhs) 13 | oldx=x 14 | while(x 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | typedef long long ll; 20 | 21 | #define rep(m,n) for(ll i=m; i<(n); i++) 22 | #define test ll t; cin >> t; while(t--) 23 | 24 | int main() 25 | { 26 | test 27 | { 28 | ll n; 29 | cin >> n; 30 | ll c=0; 31 | if(n==1) 32 | cout<<"1"<= d): 15 | flag=1 16 | else: 17 | for i in range(k,n): 18 | res1 = res1 + a[i] - a[i-k] 19 | res2 = res2 + b[i] - b[i-k] 20 | if(res1+res2 >= d): 21 | flag=1 22 | break 23 | 24 | if(flag): 25 | print("no") 26 | else: 27 | print("yes") 28 | -------------------------------------------------------------------------------- /Contests/Chef_ELE32018/inp.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 10 3 | 4 5 4 5 5 5 4 4 4 5 4 | 10 5 | 5 5 5 5 5 4 4 4 4 4 6 | 10 7 | 4 4 4 4 4 5 5 5 5 5 8 | 10 9 | 4 4 4 4 4 4 4 4 4 5 10 | 10 11 | 4 4 4 5 5 5 4 4 4 4 12 | -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/DPAIRS.py: -------------------------------------------------------------------------------- 1 | n,m = list(map(int, input().strip().split())) 2 | narr = list(map(int, input().strip().split())) 3 | marr = list(map(int, input().strip().split())) 4 | 5 | index = 0 6 | na,ma = [], [] 7 | for i in narr: 8 | na.append((i,index)) 9 | index += 1 10 | index = 0 11 | for i in marr: 12 | ma.append((i,index)) 13 | index += 1 14 | del narr,marr,index 15 | sorted(na) 16 | sorted(ma) 17 | if(len(na)>1 and len(ma)>1): 18 | for i in na: 19 | print('{0} {1}'.format(i[1],ma[0][1])) 20 | print(i[0]+ma[0][0]) 21 | 22 | for i in ma[:0:-1]: 23 | print('{0} {1}'.format(na[-1][1],i[1])) 24 | print(i[0]+na[-1][0]) 25 | elif(len(na)==1 and len(ma)>1): 26 | for i in ma: 27 | print('{0} {1}'.format(0,i[1])) 28 | elif(len(na)>1 and len(ma)==1): 29 | for i in na: 30 | print('{0} {1}'.format(i[1],0)) 31 | elif(len(na)==1 and len(ma)==1): 32 | print('0 0') -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/DPAIRS_2.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | n,m = list(map(int, input().strip().split())) 4 | narr = list(map(int, input().strip().split())) 5 | marr = list(map(int, input().strip().split())) 6 | 7 | minm = min(marr) 8 | minm_index = marr.index(minm) 9 | maxn = max(narr) 10 | maxn_index = narr.index(maxn) 11 | 12 | register = defaultdict(int) 13 | 14 | for i in range(n): 15 | val = minm + narr[i] 16 | if(register[val] == 0): 17 | register[val] += 1 18 | print('{0} {1}'.format(i,minm_index)) 19 | for i in range(m): 20 | val = maxn + marr[i] 21 | if(register[val] == 0): 22 | register[val] += 1 23 | print('{0} {1}'.format(maxn_index,i)) 24 | -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/FANCY.py: -------------------------------------------------------------------------------- 1 | t = int(input()) 2 | for _ in range(t): 3 | arr = input().strip().split() 4 | if 'not' in arr: 5 | print ("Real Fancy") 6 | else: 7 | print ("regularly fancy") -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/HP18.py: -------------------------------------------------------------------------------- 1 | # Author : @amitrajitbose 2 | for _ in range(int(input())): 3 | n,a,b = list(map(int,input().strip().split())) 4 | array = list(map(int,input().strip().split())) 5 | bob, alice, both = 0, 0, 0 6 | for i in array: 7 | if(i%a==0): 8 | bob += 1 9 | if(i%b==0): 10 | alice += 1 11 | if(i%a==0 and i%b==0): 12 | both += 1 13 | 14 | #SUBTASK 1 15 | if(a==b): 16 | if(bob>0): 17 | print("BOB") 18 | else: 19 | print("ALICE") 20 | #SUBTASK 2 21 | elif(both==0): 22 | if(bob > alice): 23 | print("BOB") 24 | elif(bob <= alice): 25 | print("ALICE") 26 | else: 27 | bob_has = bob - both 28 | alice_has = alice - both 29 | if(alice_has > bob_has): 30 | print("ALICE") 31 | elif(alice_has <= bob_has): 32 | print("BOB") -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/MGAME1.py: -------------------------------------------------------------------------------- 1 | for testcase in range(int(input())): 2 | n,p = list(map(int, input().strip().split())) 3 | i = 0 4 | i = (n//2)+1 5 | x = n%i 6 | count = 0 7 | if(n==p): 8 | for j in range(x+1,p+1): 9 | y = x%j 10 | for k in range(y+1,p+1): 11 | count += 1 12 | #print((i,j,k),(n%i%j%k%n)) 13 | print(count) 14 | elif(p>n): 15 | oldi = i 16 | count = 0 17 | 18 | for j in range(x+1,p+1): 19 | y = x%j 20 | for k in range(y+1,p+1): 21 | count += 1 22 | print((i,j,k),(n%i%j%k%n)) 23 | #print("x") 24 | for i in (n+1,p): 25 | x=n%i 26 | for j in range(x+1,p+1): 27 | k = (n//2)+1 28 | count+=1 29 | print((i,j,k),(n%i%j%k%n)) 30 | for i in (n+1,p): 31 | x=n%i 32 | for k in range(x+1,p+1): 33 | j = (n//2)+1 34 | count+=1 35 | print((i,j,k),(n%i%j%k%n)) 36 | print(count) 37 | #print("------------") -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/MGAME_intuition.txt: -------------------------------------------------------------------------------- 1 | Maximize : ((((N mod i)mod j)mod k)mod N) 2 | 3 | A mod B is MAX when B = (A//2)+1 4 | 5 | ----------------------------------------- 6 | 7 | For achieving maximum M we get: 8 | 9 | i = (N//2) + 1 10 | j = (N%i)//2 + 1 11 | k = ((N%i)%j)//2 + 1 12 | 13 | For example: 14 | N = 100 15 | i = 51 16 | j = 25 17 | k = 13 18 | 19 | M = 11 20 | 21 | ---------------------------------------- 22 | So, given an N and a P value 23 | We can find i = N//2 +1 24 | Let N%i be x 25 | j = x+1 ... P 26 | For each j, let y be x%j 27 | k = y+1 ... P 28 | 29 | 30 | 31 | n=3, p=4 32 | i=2, x=1 33 | j=2,3,4 ,y=1 34 | k=2,3 35 | 36 | INPUT = 3,4 37 | 38 | OUTPUTS = 39 | (4) 40 | 41 | if n==p: 42 | case1 = 43 | 44 | if n",finish[i],"--",end=" ")#debug 12 | s=bs(arr,start[i]) 13 | e=bs(arr,finish[i]) 14 | if(start[i]>arr[-1] or finish[i] 2 | using namespace std; 3 | int main() { 4 | int t; 5 | cin >> t; 6 | while(t--) 7 | { 8 | int n; 9 | cin >> n; 10 | int s,j; 11 | int c=0; 12 | for(int i=0;i> s >> j; 14 | if(j-s > 5){ 15 | c++; 16 | } 17 | } 18 | cout<=ones): 19 | res.append('0') 20 | else: 21 | res.append('1') 22 | scalarx = int(''.join(res),2) 23 | fsum = 0 24 | for i in arr: 25 | fsum += i^scalarx 26 | print(fsum) 27 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME71B/MINARRS2.py: -------------------------------------------------------------------------------- 1 | for T in range(int(input())): 2 | n = int(input()) 3 | a = list(map(int, input().split())) 4 | check = [[0 for x in range(20)] for x in range(n)] 5 | m = 0 6 | for i in range(n): 7 | s = bin(a[i]).replace("0b","") 8 | l = len(s) 9 | m = max(l, m) 10 | for j in range(l-1, -1, -1): 11 | print(s[j]) 12 | a[i][l-1-j] = int(s[j]) 13 | s = '' 14 | for i in range(m): 15 | c_z = 0 16 | c_1 = 0 17 | for j in range(n): 18 | if a[j][i] == 0: 19 | c_z += 1 20 | else: 21 | c_1 += 1 22 | if c_1 > c_z: 23 | s += '1' 24 | else: 25 | s += '0' 26 | s = s.lstrip('0') 27 | s = s[::-1] 28 | ans = int(s, 2) 29 | summ = 0 30 | for i in range(n): 31 | summ += (a[i] ^ ans) 32 | print(summ) -------------------------------------------------------------------------------- /Contests/Chef_LTIME78B/CMPRESS.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for _ in range(int(input())): 3 | n = int(input()) 4 | arr = list(map(int, input().strip().split())) 5 | if n == 1: 6 | print(arr[0]) 7 | else: 8 | n += 1 9 | arr.append(1001) 10 | left, right = 0, 1 11 | res = '' 12 | while left <= right and right < n and left < n: 13 | #print(left,right) 14 | if arr[right]-arr[left] == right-left: 15 | right += 1 16 | else: 17 | if right-left >= 3: 18 | res += str(arr[left])+'...'+str(arr[right-1])+',' 19 | else: 20 | for i in range(left, right): 21 | res += str(arr[i])+',' 22 | left = right 23 | print(res.strip(',')) 24 | main() 25 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME78B/DEADEND.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for _ in range(int(input())): 3 | n = int(input()) 4 | arr = list(map(int, input().strip().split())) 5 | arr.sort() 6 | pos = set(arr) 7 | plant = 0 8 | for i in range(n): 9 | if not (arr[i]-1 in pos or arr[i]+1 in pos): 10 | pos.add(arr[i]+1) 11 | plant += 1 12 | #print(pos) 13 | print(plant) 14 | main() -------------------------------------------------------------------------------- /Contests/Chef_LTIME78B/PIBRO.py: -------------------------------------------------------------------------------- 1 | def verify(a,n,k,seg): 2 | pass 3 | 4 | def longestSubSeg(a,n,k): 5 | low = 0 6 | high = n 7 | x = 0 8 | while low <= high: 9 | mid = (low + high)//2 10 | if verify(a,n,k,mid): 11 | x = max(x, mid) 12 | else: 13 | 14 | 15 | for _ in range(int(input())): 16 | n,k = [int(x) for x in input().strip().split()] 17 | a = [int(x) for x in list(input())] 18 | print(a) 19 | print(longestSubSeg(a, n, k)) -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/CHDIGER.py: -------------------------------------------------------------------------------- 1 | def reduce_it(n,d): 2 | n = str(n) + str(d) 3 | s = list(n) 4 | new = [] 5 | new.append(s[0]) #first digit 6 | l = len(s) 7 | 8 | for i in range(1,l): 9 | if(s[i] >= new[-1]): 10 | new.append(s[i]) 11 | else: 12 | new.pop(-1) 13 | new.extend(s[i:]) 14 | break 15 | if(len(new)==len(s)): 16 | new.pop(-1) 17 | num = ''.join(new) 18 | return (int(num)) 19 | 20 | def reducable(n): 21 | if(n<10): 22 | return False 23 | n=list(str(n)) 24 | a=n[0] 25 | for i in n[1:]: 26 | if(a>i): 27 | return True 28 | a=i 29 | return False 30 | 31 | t = int(input()) 32 | for testcase in range(t): 33 | n, d = map(int, input().strip().split()) 34 | if(d < n%10): 35 | n = reduce_it(n,d) 36 | while(reducable(n)): 37 | n = reduce_it(n,d) 38 | print(n) -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/CHNUM.py: -------------------------------------------------------------------------------- 1 | for _ in range(int(input())): 2 | n = int(input()) 3 | arr = [int(x) for x in input().strip().split()] 4 | pc,nc,zc = 0, 0, 0 5 | for i in arr: 6 | if i<0: 7 | nc = nc+1 8 | else: 9 | pc = pc+1 10 | ans = [pc, nc] 11 | if 0 not in ans: 12 | print(max(ans),min(ans)) 13 | else: 14 | print(n, n) 15 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/CHNUM_AB.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Author: Amitrajit Bose 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | typedef long long ll; 12 | #define FOR(i,m,n) for(__typeof(n) i = m; i<(n); i++) 13 | #define test ll t; cin >> t; while(t--) 14 | int main() 15 | { 16 | test 17 | { 18 | ll i,n; 19 | ll ps=0; 20 | ll ng=0; 21 | cin >> n; 22 | ll A[n]; 23 | FOR(i,0,n) 24 | { 25 | cin >> A[i]; 26 | if(A[i]>=0) 27 | ps++; 28 | else 29 | ng++; 30 | } 31 | if(ps==n or ng==n) 32 | cout << n << " " << n << endl; 33 | else 34 | cout << max(ps,ng) << " " << min(ps,ng) << endl; 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/CHONQ.py.save: -------------------------------------------------------------------------------- 1 | from math import floor 2 | for _ in range(int(input())): 3 | n,k=map(int,input().strip().split()) 4 | 5 | ar=[int(x) for x in input().strip().split()] 6 | a=[0] 7 | for i in ar: 8 | a.append(i) 9 | 10 | # Core calculation: Greedy 11 | spot=n+1 12 | for i in range(1,n+2): 13 | #print("\n\nEnter At Pos",i) 14 | cost = 0 15 | for j in range(i,n+1): 16 | print(a[j],"/",(j-i+1),end="+") 17 | cost += floor(a[j]/(j-i+1)) 18 | print("\n") 19 | 20 | #print("COST",cost) 21 | if(cost<=k): 22 | spot=min(spot,i) 23 | break 24 | print(spot) 25 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/CHONQ_Brute.py: -------------------------------------------------------------------------------- 1 | from math import floor 2 | for _ in range(int(input())): 3 | n,k=map(int,input().strip().split()) 4 | 5 | ar=[int(x) for x in input().strip().split()] 6 | a=[0] 7 | for i in ar: 8 | a.append(i) 9 | 10 | # Core calculation: Greedy 11 | spot=n+1 12 | for i in range(1,n+2): 13 | #print("\n\nEnter At Pos",i) 14 | cost = 0 15 | for j in range(i,n+1): 16 | #print("(",a[j],"/",(j-i+1),end=") + ") 17 | cost += floor(a[j]/(j-i+1)) 18 | #print("\n") 19 | #print("COST",cost) 20 | if(cost<=k): 21 | spot=min(spot,i) 22 | break 23 | print(spot) 24 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/JAIN/JAIN_0.py: -------------------------------------------------------------------------------- 1 | tc = int(input()) 2 | for tcs in range(tc): 3 | n = int(input()) 4 | inputs = [] 5 | for i in range(n): 6 | tmp = str(input().strip()) 7 | inputs.append(list(set(list(tmp)))) 8 | cnt=0 9 | for i in range(n-1): 10 | for j in range(i+1,n): 11 | a = inputs[i] 12 | b = inputs[j] 13 | thislist = a+b 14 | if(len(set(thislist[:]))==5): 15 | cnt += 1 16 | print(cnt) 17 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/SUBPRNJL_0.py: -------------------------------------------------------------------------------- 1 | def one_hot_encode(arr): 2 | one_hot = [0]*2001 #because maximum can be 2000 3 | for i in arr: 4 | one_hot[i] += 1 5 | return one_hot 6 | 7 | from math import ceil 8 | tc = int(input()) 9 | for tc_ in range(int(tc)): 10 | counter = 0 11 | n, k = map(int, input().strip().split()) 12 | arr = list(map(int, input().strip().split())) 13 | 14 | for i in range(n): 15 | for j in range(i,n): 16 | m = ceil(k/((j-i)+1)) 17 | S = arr[i:j+1] 18 | freq = one_hot_encode(S) 19 | freq_copy = freq[:] 20 | for index in range(2001): 21 | freq[index] = freq[index] * m 22 | lsum = 0 23 | for val in range(2001): 24 | if(lsum < k): 25 | lsum = lsum + freq[val] 26 | else: 27 | X = val-1 28 | break 29 | 30 | F = freq_copy[X] #S.count(X) 31 | if(freq_copy[F]>=1): 32 | counter+=1 33 | print(counter) 34 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/SUBPRNJL_1.py: -------------------------------------------------------------------------------- 1 | from math import ceil as CEIL 2 | for _ in range(int(input())): 3 | cnt = 0 4 | n, k = [int(x) for x in input().strip().split()] 5 | arr = [int(x) for x in input().strip().split()] 6 | for i in range(n): 7 | for j in range(i,n): 8 | m = CEIL(k/((j-i)+1)) 9 | subseq = arr[i:j+1] 10 | subseq = sorted(subseq) 11 | X = subseq[CEIL(k/m)-1] 12 | F = subseq.count(X) 13 | if(F in subseq == True): 14 | cnt+=1 15 | print(cnt) -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/SUBPRNJL_Brute.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | tc = int(input()) 3 | for tc_ in range(int(tc)): 4 | counter = 0 5 | n, k = map(int, input().strip().split()) 6 | arr = list(map(int, input().strip().split())) 7 | arr = sorted(arr) 8 | for i in range(n): 9 | for j in range(i,n): 10 | m = ceil(k/((j-i)+1)) 11 | S = arr[i:j+1] 12 | print(S) 13 | B = S * m 14 | print(B) 15 | Bsorted = sorted(B) 16 | print(Bsorted) 17 | X = Bsorted[k-1] 18 | print(X) 19 | F = S.count(X) 20 | print(F) 21 | print(S.count(F)) 22 | if(S.count(F)>=1): 23 | counter+=1 24 | print("-----------------------------") 25 | print(counter) -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/Chef_MARCH19B/SUBPRNJL/a.out -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/input2.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 3 3 3 | 1 2 3 4 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/prefix.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | 3 | def binary_search(arr, key): 4 | return (key in arr) 5 | 6 | for _ in range(int(input())): 7 | count = 0 8 | n,k = map(int, input().strip().split()) 9 | arr = [int(x) for x in input().strip().split()] 10 | frequency_vector = [0]*2001 11 | for i in arr: 12 | frequency_vector[i] += 1 13 | pref_sum_fv = [0]*2001 14 | pref_sum_fv[0] = frequency_vector[0] 15 | for i in range(1,2001): 16 | pref_sum_fv[i] = pref_sum_fv[i-1]+frequency_vector[i] 17 | for i in range(n): 18 | for j in range(i,n): 19 | m = ceil(k/((j-i)+1)) 20 | subseq = pref_sum_fv[i:j+1] 21 | X = pref_sum_fv.index(k) 22 | F = frequency_vector[X] 23 | if(F in sub): 24 | count+=1 25 | print(count) -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/Chef_MARCH19B/a.out -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/input.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 3 3 3 | 1 2 3 4 | 6 3 5 | 6 3 1 2 7 8 6 | 5 3 7 | 8 5 9 1 2 8 | 4 2 9 | 4 3 2 1 10 | 5 4 11 | 12 7 23 6 14 12 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH20B/CHPINTU.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for _ in range(int(input())): 3 | n,m = [int(x) for x in input().strip().split()] 4 | types = [0] * (m+1) 5 | present = [False] * (m+1) 6 | f = [int(x) for x in input().strip().split()] 7 | p = [int(x) for x in input().strip().split()] 8 | for i in range(n): 9 | types[f[i]] += p[i] 10 | present[f[i]] = True 11 | # get min price 12 | minp = float('inf') 13 | for i in range(1,m+1): 14 | if present[i]: 15 | minp = min(minp, types[i]) 16 | # print(present) 17 | print(minp) 18 | 19 | main() -------------------------------------------------------------------------------- /Contests/Chef_MARCH20B/ENGXOR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | ll oddSetBits(ll n){ 5 | if (n == 0) return 0; 6 | if (n%2 == 0) return (oddSetBits(floor(n/2))); 7 | if (n%2 == 1) return (1 - oddSetBits(floor(n/2))); 8 | } 9 | 10 | int main() 11 | { 12 | ios_base::sync_with_stdio(false); 13 | cin.tie(NULL); 14 | ll tc; 15 | cin >> tc; 16 | for(ll test=0; test> n >> q; 19 | ll arr[n]; 20 | for(ll i=0; i> arr[i]; 22 | } 23 | for(ll qr=0; qr> elem; 26 | ll odd = 0; 27 | ll even = 0; 28 | for(ll i=0; i0: 14 | n = n & (n-1) 15 | cnt += 1 16 | return cnt%2 17 | 18 | def main(): 19 | for _ in range(int(input())): 20 | n,q = [int(x) for x in input().strip().split()] 21 | arr = [int(x) for x in input().strip().split()] 22 | for query in range(q): 23 | elem = int(input().strip()) 24 | odd, even = 0, 0 25 | for i in arr: 26 | if checkOddSetBits(elem ^ i): 27 | odd += 1 28 | else: 29 | even += 1 30 | print(even,odd) 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH20B/input.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 6 2 3 | 4 2 15 9 8 8 4 | 3 5 | 16 6 | -------------------------------------------------------------------------------- /Contests/Chef_NOV1BB/CHFTIRED.py: -------------------------------------------------------------------------------- 1 | for test in range(int(input())): 2 | a,b=[int(x) for x in input().strip().split()] 3 | print("YES") 4 | ''' 5 | Like seriously Codechef! 6 | You gotta be kidding us, 7 | ''' 8 | -------------------------------------------------------------------------------- /Contests/Chef_NOV1BB/CHHAPPY.py: -------------------------------------------------------------------------------- 1 | # Author: @amitrajitbose 2 | for test in range(int(input())): 3 | n=int(input().strip()) 4 | arr=[int(x) for x in input().strip().split()] 5 | visited={} 6 | for i in arr: 7 | visited[i]=[0,0] 8 | 9 | flag=0 10 | for i in arr: 11 | x=arr[arr[i-1]-1] 12 | if(not visited[x][0]): 13 | visited[x][0]=1 #impacted 14 | visited[x][1]=i #impacted by 15 | elif(visited[x][0] and visited[x][1]!=i): 16 | flag=1 17 | break 18 | 19 | if(flag): 20 | print("Truly Happy") 21 | else: 22 | print("Poor Chef") 23 | 24 | -------------------------------------------------------------------------------- /Contests/Chef_NOV1BB/GMEDIAN1.py: -------------------------------------------------------------------------------- 1 | #author: amitrajitbose 2 | MOD=(10**9)+7 3 | table=[[1 for i in range(1001)] for j in range(1001)] 4 | for i in range(1,1001): 5 | for j in range(1,1001): 6 | table[i][j]=(table[i][j-1]+table[i-1][j])%MOD 7 | 8 | t=int(input()) 9 | for _ in range(t): 10 | n=int(input()) 11 | arr=[int(x) for x in input().strip().split()] 12 | sarr=set(arr) 13 | if(len(sarr)==n): 14 | print((2**(n-1))%MOD) 15 | else: 16 | arr=sorted(arr,reverse=False) 17 | ga,gb=0,0 18 | while(gb=10): 10 | p=[0,0,2**x] 11 | elif(remaining>=2): 12 | p=[0,2**x,0] 13 | else: 14 | p=[2**x,0,0] 15 | print(*p) 16 | 17 | def main(): 18 | t=int(input()) 19 | for _ in range(t): 20 | num=int(input()) 21 | bytelandpopulation(num) 22 | 23 | if __name__=='__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /Contests/Chef_OCT18B/CHSERVE.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Author: Amitrajit Bose 4 | * Problem Link: 5 | * Approach: 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | typedef long long ll; 14 | #define FOR(i,m,n) for(__typeof(n) i = m; i<(n); i++) 15 | #define test ll t; cin >> t; while(t--) 16 | int main() 17 | { 18 | test 19 | { 20 | ll p1,p2,k; 21 | cin >> p1 >> p2 >> k ; 22 | if(((p1+p2)/k)%2 == 0) 23 | cout << "CHEF" << endl; 24 | else 25 | cout << "COOK" << endl; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Contests/Chef_OCT18B/HMAPPY.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Author: Amitrajit Bose 3 | Passes TC: Only Last 4 | ''' 5 | from bisect import bisect_left as bs 6 | n,m=[int(x) for x in input().strip().split()] 7 | a=[int(x) for x in input().strip().split()] 8 | b=[int(x) for x in input().strip().split()] 9 | arr=[] 10 | for i in range(n): 11 | arr.append((a[i],b[i],a[i]*b[i])) 12 | arr=sorted(arr, key=lambda x: x[2]) 13 | arr=sorted(arr, key=lambda x: x[1]) 14 | for i in range(n): 15 | a[i],b[i]=arr[i][0],arr[i][1] 16 | currmean=sum(a)//n 17 | meanpos=bs(a,currmean) 18 | if(a[meanpos]!=currmean and meanpos>0): 19 | meanpos=meanpos-1 20 | for i in range(n-1,meanpos,-1): 21 | diff=abs(a[i]-a[meanpos]) 22 | prevai=a[i] 23 | a[i]=max(0,a[i]-diff) 24 | m=m-(prevai-a[i]) 25 | if(m<=0): 26 | break 27 | s=0 28 | for i in range(n): 29 | s=max(s,(a[i]*b[i])) 30 | print(s) 31 | -------------------------------------------------------------------------------- /Contests/Chef_OCT18B/HMAPPY2.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Author: Amitrajit Bose 4 | Passed only last test case 5 | ''' 6 | from bisect import bisect_left as bs 7 | n,m=[int(x) for x in input().strip().split()] 8 | a=[int(x) for x in input().strip().split()] 9 | b=[int(x) for x in input().strip().split()] 10 | arr=[] 11 | for i in range(n): 12 | arr.append((a[i],b[i],a[i]*b[i])) 13 | arr=sorted(arr, key=lambda x: x[2]) 14 | arr=sorted(arr, key=lambda x: x[1]) 15 | for i in range(n): 16 | a[i],b[i]=arr[i][0],arr[i][1] 17 | 18 | for i in range(n-2,-1,-1): 19 | if(a[i]=(a[i+1]-a[i])): 20 | delta=a[i+1]-a[i] 21 | m-=delta 22 | a[i+1]-=delta 23 | for j in range(i+2,n,1): 24 | if(m>=delta): 25 | a[j]-=delta 26 | if(m<=0): 27 | break 28 | else: 29 | delta=m 30 | a[-1]=max(0,a[-1]-m) 31 | m-=delta 32 | #if(m>0): 33 | # a[-1]-=m 34 | s=0 35 | for i in range(n): 36 | s=max(s,(a[i]*b[i])) 37 | print(s) 38 | -------------------------------------------------------------------------------- /Contests/Chef_OCT18B/inp.txt: -------------------------------------------------------------------------------- 1 | 5 3 2 | 1 2 3 8 12 3 | 1 2 3 4 5 4 | 5 | -------------------------------------------------------------------------------- /Contests/Chef_SEP18/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/Chef_SEP18/a.out -------------------------------------------------------------------------------- /Contests/Chef_SEP18/inp.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 3 2 3 | 1 2 3 4 | 2 2 5 | 1 3 6 | -------------------------------------------------------------------------------- /Contests/CodeJam19/Qualifiers/input.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 103 31 3 | 217 1891 4819 2291 2987 3811 1739 2491 4717 445 65 1079 8383 5353 901 187 649 1003 697 3239 7663 291 123 779 1007 3551 1943 2117 1679 989 3053 4 | 10000 25 5 | 3292937 175597 18779 50429 375469 1651121 2102 3722 2376497 611683 489059 2328901 3150061 829981 421301 76409 38477 291931 730241 959821 1664197 3057407 4267589 4729181 5335543 6 | -------------------------------------------------------------------------------- /Contests/CodeJam19/Round1A/alienrhyme: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | input=sys.stdin.readline 4 | 5 | for cnum in range(int(input())): 6 | n=int(input()) 7 | words=[{} for _ in range(55)] 8 | for _ in range(n): 9 | w=input().strip() 10 | words[len(w)][w]=1 11 | #print(len(w),w) 12 | ans=0 13 | for i in range(1,55)[::-1]: 14 | for j,k in words[i].items(): 15 | if k>=2: 16 | ans+=2 17 | k-=2 18 | j2=j[1:] 19 | k2=k+words[i-1].get(j2,0) 20 | if k2==0: continue 21 | words[i-1][j2]=k2 22 | #print(j2,k2) 23 | print("Case #%d: %d"%(cnum+1,ans)) 24 | -------------------------------------------------------------------------------- /Contests/CodeJam19/Round1A/golfers: -------------------------------------------------------------------------------- 1 | import sys 2 | input=sys.stdin.readline 3 | 4 | t,n,m=map(int,input().split()) 5 | 6 | for _ in range(t): 7 | things=[16,9,5,7,11,13,17] 8 | res=[] 9 | 10 | for i in things: 11 | print(" ".join(map(lambda x:str(i),range(18)))) 12 | sys.stdout.flush() 13 | s=list(map(int,input().split())) 14 | if s[0]==-1: sys.exit(0) 15 | res.append(sum(s)%i) 16 | 17 | ans=0 18 | bad=1 19 | while bad: 20 | bad=0 21 | for i in range(7): 22 | while ans%things[i]!=res[i]: 23 | ans+=1 24 | bad=1 25 | print(ans) 26 | sys.stdout.flush() 27 | s=list(map(int,input().split())) 28 | if s[0]==-1: sys.exit(0) 29 | -------------------------------------------------------------------------------- /Contests/CodingNinjas_CareerCamp/GetProduct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void fun(int* a,int* b) { 5 | *a=(*a)*(*b); 6 | } 7 | 8 | int main() { 9 | int a,b; 10 | cin>>a>>b; 11 | fun(&a,&b); 12 | cout << a ; 13 | -------------------------------------------------------------------------------- /Contests/CodingNinjas_CareerCamp/Pattern.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 1234 3 | 1 4 4 | 1 4 5 | 1234 6 | ''' 7 | 8 | #Write your code here 9 | n = int(input()) 10 | for i in range(1,n+1): 11 | print(i,end="") 12 | print("") 13 | for i in range(2,n): 14 | print(1,end="") 15 | print(" "*(n-2),end="") 16 | print(n) 17 | for i in range(1,n+1): 18 | print(i,end="") 19 | print("") 20 | -------------------------------------------------------------------------------- /Contests/Facebook Hacker Cup 2018/Qualification/Tourist/input.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 4 1 3 3 | LikeSign 4 | Arcade 5 | SweetStop 6 | SwagStore 7 | 4 4 100 8 | FoxGazebo 9 | MPK20Roof 10 | WoodenSculpture 11 | Biryani 12 | 4 3 1 13 | LikeSign 14 | Arcade 15 | SweetStop 16 | SwagStore 17 | 4 3 3 18 | LikeSign 19 | Arcade 20 | SweetStop 21 | SwagStore 22 | 4 3 10 23 | LikeSign 24 | Arcade 25 | SweetStop 26 | SwagStore 27 | 2 1 1000000000000 28 | RainbowStairs 29 | WallOfPhones 30 | 3 2 1 31 | A 32 | B 33 | C 34 | -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.49.12 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.49.12 PM.png -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.50.41 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.50.41 PM.png -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.59.56 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.59.56 PM.png -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.01 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.01 PM.png -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.06 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.06 PM.png -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.11 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.11 PM.png -------------------------------------------------------------------------------- /Contests/Snackdown19_Online1A/AVGMAT_Partial.py: -------------------------------------------------------------------------------- 1 | def manhattan(x1,y1,x2,y2): 2 | return (abs(x1-x2)+abs(y1-y2)) 3 | 4 | t=int(input()) 5 | for _ in range(t): 6 | n,m=[int(x) for x in input().strip().split()] 7 | arr=[] 8 | for eachrow in range(n): 9 | row=list(str(input())) 10 | arr.append(row) 11 | ones=[] 12 | for i in range(n): 13 | for j in range(m): 14 | if(arr[i][j]=='1'): 15 | ones.append((i,j)) 16 | maxrange=(n+m)-2 17 | d=[0 for i in range((n+m)-1)] 18 | l=len(ones) 19 | for i in range(l): 20 | for j in range(i+1,l): 21 | #if(i!=j): 22 | d[manhattan(ones[i][0],ones[i][1],ones[j][0],ones[j][1])]+=1 23 | for i in range(1,maxrange+1): 24 | print(d[i],end=" ") 25 | print("") 26 | 27 | -------------------------------------------------------------------------------- /Contests/Snackdown19_Online1A/CARDMGK.py: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Author: Amitrajit Bose 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | typedef long long ll; 12 | #define FOR(i,m,n) for(__typeof(n) i = m; i<(n); i++) 13 | #define test int t; cin >> t; while(t--) 14 | int main() 15 | { 16 | test 17 | { 18 | ll n; 19 | cin >> n; 20 | ll *arr = new ll[n]; 21 | int flag=0; 22 | FOR(i,0,n) 23 | { 24 | cin >> arr[i]; 25 | if(i>0) 26 | { 27 | if(arr[i]=2) 40 | cout<<"NO"< 2 | using namespace std; 3 | int main() 4 | { 5 | long t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | long a,b,c; 10 | cin>>a>>b>>c; 11 | int ac=__builtin_popcount(a),bc=__builtin_popcount(b),ans=0; 12 | for(int i=1;i<=c/2;i++) 13 | { 14 | int ic=__builtin_popcount(i); 15 | int cic=__builtin_popcount(c-i); 16 | int ipcic=__builtin_popcount(i+(c/2)); 17 | int cipcic=__builtin_popcount(c-(i+(c/2))); 18 | if(ic==ac && cic==bc) 19 | ans++; 20 | if(ipcic==ac && cipcic==bc) 21 | ans++; 22 | } 23 | cout<= 2: 17 | break 18 | if(n > 1): 19 | ch += 1 20 | return ch == 2 21 | def check(n): 22 | if semprime(n) == True: 23 | return True 24 | else: 25 | return False 26 | for _ in range(int(input())): 27 | n=int(input()) 28 | flag=0 29 | for i in range(2,n//2+1): 30 | if check(i)==True and check(n-i)==True: 31 | #print(i,n-i,square(i),square(n-i),"Yes") 32 | print("YES") 33 | flag=1 34 | break 35 | if flag==0: 36 | #print(i,n-i,square(i),square(n-i),"No") 37 | print("NO") 38 | -------------------------------------------------------------------------------- /Contests/Snackdown19_Qualifier/QABC.cpp: -------------------------------------------------------------------------------- 1 | // @author: @amitrajitbose 2 | 3 | #include 4 | using namespace std; 5 | typedef long long ll; 6 | 7 | int main() 8 | { 9 | ll t; 10 | cin >> t; 11 | while(t--) 12 | { 13 | ll n; 14 | cin >> n; 15 | ll A[n]; 16 | ll B[n]; 17 | ll i,m; 18 | int f=1; //flag says TAK TAKA TAK 19 | for(i=0;i>A[i]; 21 | for(i=0;i>B[i]; 23 | for(i=0;i0): 15 | know+=sumk 16 | dontknow=n-know 17 | if(know-1>=n): 18 | sumk=pref[n-1] 19 | else: 20 | sumk=pref[know-1] 21 | day+=1 22 | print(day) 23 | -------------------------------------------------------------------------------- /Contests/bleedcode/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Contests/bleedcode/a.out -------------------------------------------------------------------------------- /Contests/bleedcode/bloody.py: -------------------------------------------------------------------------------- 1 | import itertools as it 2 | 3 | def utilityfunc(num_str): 4 | num_iter = it.permutations(num_str, len(num_str)) 5 | for num_list in num_iter: 6 | 7 | v = ''.join(num_list) 8 | x, y = v[:int(len(v)/2)], v[int(len(v)/2):] 9 | 10 | if x[-1] == '0' and y[-1] == '0': 11 | continue 12 | 13 | if int(x) * int(y) == int(num_str): 14 | return x,y 15 | return False 16 | 17 | 18 | def isVampire(m_int): 19 | 20 | n_str = str(m_int) 21 | 22 | if len(n_str) % 2 == 1: 23 | return False 24 | 25 | fangs = utilityfunc(n_str) 26 | if not fangs: 27 | return False 28 | return True 29 | 30 | for _ in range(int(input())): 31 | n = int(input()) 32 | if isVampire(n): 33 | print ("Bloody") 34 | else: 35 | print("Not Bloody") -------------------------------------------------------------------------------- /Contests/bleedcode/date.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | 3 | def days_between(d1, d2): 4 | d1 = datetime.strptime(d1, "%Y-%m-%d") 5 | d2 = datetime.strptime(d2, "%Y-%m-%d") 6 | return abs((d2 - d1).days) 7 | 8 | for _ in range(int(input())): 9 | date1, date2 = [str(x) for x in input().strip().split()] 10 | d1,m1,y1 = date1.split('/') 11 | d2,m2,y2 = date2.split('/') 12 | days = days_between(y1+'-'+m1+'-'+d1, y2+'-'+m2+'-'+d2) 13 | gap = timedelta(days=days-1) 14 | ans = datetime.strptime("0001-01-01", "%Y-%m-%d") + gap 15 | 16 | month = str(ans.month-1) 17 | mpadding = "0"*(2-len(month)) 18 | month=mpadding+month 19 | 20 | year = str(ans.year-1) 21 | ypadding = "0"*(4-len(year)) 22 | year=ypadding+year 23 | 24 | print("{0}/{1}/{2:4}".format(ans.day,month,year)) -------------------------------------------------------------------------------- /Contests/bleedcode/deter.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | for _ in range(int(input())): 3 | n=int(input()) 4 | ar=[] 5 | for i in range(n): 6 | x=list(map(int,input().split())) 7 | ar.append(x) 8 | det = numpy.linalg.det(ar) 9 | print(int(det)) -------------------------------------------------------------------------------- /Contests/bleedcode/input.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 01/01/1970 26/06/2006 3 | 27/02/1056 10/03/2019 4 | 01/01/0001 31/12/9999 5 | -------------------------------------------------------------------------------- /Contests/bleedcode/leven.py: -------------------------------------------------------------------------------- 1 | # @amitrajitbose 2 | def editDistance(str1,str2): 3 | m=len(str1) 4 | n=len(str2) 5 | table=[[0 for x in range(n+1)] for x in range(m+1)] 6 | for i in range(m+1): 7 | for j in range(n+1): 8 | if(i==0): 9 | table[i][j]=j 10 | elif(j==0): 11 | table[i][j]=i 12 | elif(str1[i-1]==str2[j-1]): 13 | table[i][j]=table[i-1][j-1] #diagonal value + 1, i.e replacing 14 | else: 15 | table[i][j]=1+min(table[i-1][j-1],table[i-1][j],table[i][j-1]) #replace,remove,insert 16 | 17 | return table[m][n] 18 | 19 | for _ in range(int(input())): 20 | 21 | str1, str2 = [str(x) for x in input().strip().split()] 22 | print(editDistance(str1,str2)) -------------------------------------------------------------------------------- /Contests/bleedcode/second.py: -------------------------------------------------------------------------------- 1 | def reValuation(num): 2 | if (num >= 0 and num <= 9): 3 | return chr(num + ord('0')) 4 | else: 5 | return chr(num - 10 + ord('A')) 6 | 7 | 8 | def convert(res, base, inputNum): 9 | 10 | index = 0 11 | while (inputNum > 0): 12 | res+= reValuation(inputNum % base) 13 | inputNum = int(inputNum / base) 14 | 15 | # Reverse the result 16 | res = res[::-1] 17 | 18 | return res 19 | 20 | # Driver Code 21 | for _ in range(int(input())): 22 | inputNum, base = [int(x) for x in input().strip().split()] 23 | res = "" 24 | print(convert(res, base, inputNum)); 25 | 26 | -------------------------------------------------------------------------------- /Dynamic Programming/ACODE.py: -------------------------------------------------------------------------------- 1 | #Problem Link: http://www.spoj.com/problems/ACODE/ 2 | 3 | from itertools import repeat 4 | while(True): 5 | a=str(input()) 6 | arr=list(map(lambda x:x,a)) 7 | n=len(arr) 8 | #thus the word has been broken to characters 9 | dp=list(repeat(0,n+1)) 10 | #bottom up dynamic approach 11 | #traverse the string/number from last to first 12 | if(n==1 and a=='0'): 13 | break 14 | elif(n==1): 15 | print(1) 16 | else: 17 | dp[n]=1 18 | if(arr[n-1]!='0'): 19 | dp[n-1]=1 20 | else: 21 | dp[n-1]=0 22 | 23 | for i in range(n-2,-1,-1): 24 | if(arr[i]=='0'): 25 | dp[i]=0 26 | elif(arr[i]=='1'): 27 | dp[i]=dp[i+1]+dp[i+2] 28 | elif(arr[i]=='2'): 29 | if(int(arr[i+1])>6): 30 | dp[i]=dp[i+1] 31 | else: 32 | dp[i]=dp[i+1]+dp[i+2] 33 | elif(int(arr[i])>2): 34 | dp[i]=dp[i+1] 35 | print(dp[0]) 36 | -------------------------------------------------------------------------------- /Dynamic Programming/CF455A.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem Name: Boredom - Codeforces 3 | Approach - Dynamic Programming 4 | ''' 5 | import itertools 6 | n=int(input()) 7 | arr=[int(x) for x in input().strip().split()] 8 | dp=list(itertools.repeat(0,((10**5)+2))) 9 | 10 | myd={} 11 | 12 | for i in arr: 13 | if i in myd: 14 | myd[i]+=1 15 | else: 16 | myd[i]=1 17 | 18 | if 1 in myd: 19 | dp[1]=myd[1] 20 | 21 | for i in range(2,(10**5)+1): 22 | # either we dont take the ith number 23 | # or we take it and thus all i-1 will also be deleted 24 | # not considering i+1 because it has not been yet computed 25 | if(i in myd): 26 | x = max(dp[i-1], dp[i-2]+(i*myd[i])) 27 | else: 28 | x = max(dp[i-1], dp[i-2]) 29 | dp[i]=x 30 | 31 | print(dp[10**5]) 32 | 33 | -------------------------------------------------------------------------------- /Dynamic Programming/Coin-Change.py: -------------------------------------------------------------------------------- 1 | # LC 322 M 2 | class Solution: 3 | def coinChange(self, coins: List[int], amount: int) -> int: 4 | nums = [float('inf')] * (amount + 1) 5 | nums[0] = 0 6 | for deno in coins: 7 | for amt in range(amount+1): 8 | if deno <= amt: 9 | nums[amt] = min(nums[amt], 1 + nums[amt-deno]) 10 | return nums[amount] if nums[amount] < float('inf') else -1 11 | -------------------------------------------------------------------------------- /Dynamic Programming/DPBook/Fibonacci_DP.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if n==1 or n==2: 3 | return 1 4 | a = 1 5 | b = 1 6 | for i in range(3, n+1): 7 | c = a+b 8 | a = b 9 | b = c 10 | return c 11 | 12 | print(fibonacci(30)) 13 | 14 | -------------------------------------------------------------------------------- /Dynamic Programming/DPBook/Fibonacci_Memoized.py: -------------------------------------------------------------------------------- 1 | class Fibo(object): 2 | """docstring for Fibo""" 3 | def __init__(self): 4 | self.memo = [] 5 | 6 | 7 | def fibonacci(self, n, debug=False): 8 | if debug: 9 | print(self.memo) 10 | if self.memo[n] != 0: 11 | return self.memo[n] 12 | if n==1 or n==2: 13 | self.memo[n] = 1 14 | else: 15 | self.memo[n] = self.fibonacci(n-1) + self.fibonacci(n-2) 16 | return self.memo[n] 17 | 18 | def main(self, n): 19 | self.memo = [0 for i in range(n+1)] 20 | print(self.fibonacci(n)) 21 | 22 | Fibo().main(30) -------------------------------------------------------------------------------- /Dynamic Programming/DPBook/MaxSumSubarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of positive and negative elements, return the maximum 3 | sum of a contiguous subarray 4 | """ 5 | 6 | def max_sum(arr): 7 | max_so_far = 0 8 | max_ending_here = 0 9 | for i in arr: 10 | max_ending_here += i 11 | if max_ending_here < 0: 12 | max_ending_here = 0 13 | if max_ending_here > max_so_far: 14 | max_so_far = max_ending_here 15 | return max_so_far 16 | 17 | print(max_sum([-2,-3,4,-1,-2,1,5,-3])) -------------------------------------------------------------------------------- /Dynamic Programming/DPBook/PP/1_EditDistance.java: -------------------------------------------------------------------------------- 1 | public static int editDist(String a, String b) 2 | { 3 | int m = a.length(); 4 | int n = b.length(); 5 | int editmat[][] = new int[m+1][n+1]; 6 | // for top row 7 | for(int i=0; i<=n; i++) 8 | editmat[0][i] = i; 9 | // for left column 10 | for(int i=0; i<=m; i++) 11 | editmat[i][0] = i; 12 | for(int i=1; i<=m; i++) 13 | { 14 | for(int j=1; j<=n; j++) 15 | { 16 | // if two characters are same 17 | if(a.charAt(i-1) == b.charAt(j-1)) 18 | editmat[i][j] = editmat[i-1][j-1]; 19 | else{ 20 | editmat[i][j] = Math.min(editmat[i][j-1], (Math.min(editmat[i-1][j], editmat[i-1][j-1]))) + 1; 21 | } 22 | } 23 | } 24 | return editmat[m][n]; 25 | } 26 | public static void main(String args[])throws IOException 27 | { 28 | String a = "COMPUTER"; 29 | String b = "COMMUTER"; 30 | System.out.println(editDist(a,b)); 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Dynamic Programming/Finding_Nth_Fibonacci_Number.cpp: -------------------------------------------------------------------------------- 1 | //Tabulation Based Dynamic Programming 2 | //Bottom up 3 | //nth Fibonacci Number 4 | //Author: Amitrajit Bose 5 | /* 6 | NOTE: 7 | First value(n=1) is fibonacciseries[0]=0 8 | Second value(n=2) is fibonacciseries[1]=1 9 | Third value(n=3) is fibonacciseries[2]=1 10 | Fourth value(n=4) is fibonacciseries[3]=2 11 | .. 12 | so on 13 | */ 14 | #include 15 | using namespace std; 16 | #define ll long long int 17 | ll fibo(ll n){ 18 | if(n==1) 19 | return 0; 20 | else if(n==2) 21 | return 1; 22 | else 23 | { 24 | ll lookuptable[n+1]; 25 | lookuptable[0]=0; 26 | lookuptable[1]=1; 27 | for(ll i=2;i<=n;i++){ 28 | lookuptable[i]=lookuptable[i-1]+lookuptable[i-2]; 29 | } 30 | return lookuptable[n-1]; 31 | } 32 | } 33 | int main() { 34 | ll n; 35 | cin>>n; 36 | cout< int: 26 | if len(nums) > 2: 27 | return max(self.util(nums[1:]),self.util(nums[:-1])) 28 | else: 29 | if len(nums)==0: 30 | return 0 31 | else: 32 | return max(nums) 33 | -------------------------------------------------------------------------------- /Dynamic Programming/IEMCO5B.py: -------------------------------------------------------------------------------- 1 | #https://www.codechef.com/IEMCO5/problems/IEMCO5B/ 2 | 3 | def maxSum(arr, n): 4 | max = 0 5 | msisi = [0 for x in range(n)] 6 | for i in range(n): 7 | msisi[i] = arr[i] 8 | for i in range(1, n): 9 | for j in range(i): 10 | if arr[i] > arr[j] and msisi[i] < msisi[j] + arr[i]: 11 | msisi[i] = msisi[j] + arr[i] 12 | for i in range(n): 13 | if max < msisi[i]: 14 | max = msisi[i] 15 | 16 | return max 17 | 18 | t=int(input()) 19 | for _ in range(t): 20 | n=int(input()) 21 | arr=[int(x) for x in input().strip().split(' ')] 22 | print(str(maxSum(arr, n))) -------------------------------------------------------------------------------- /Dynamic Programming/LCS.py: -------------------------------------------------------------------------------- 1 | # Classical Longest Common Subsequence Problem 2 | 3 | a="ACBDHEIHTKNASJHRJKBJWJEVOEWNV" 4 | b="ABCDEKBSKDBUEWBUEUKHSJKHKUELWNV" 5 | 6 | #a="AGGTAB" 7 | #b="GXTXAYB" 8 | 9 | #RECURSIVE APPROACH 10 | def lcs(a,b,i=len(a)-1,j=len(b)-1): 11 | if(i==-1 or j==-1): 12 | return "" 13 | if(a[i]==b[j]): 14 | return lcs(a,b,i-1,j-1)+a[i] 15 | else: 16 | return max(lcs(a,b,i-1,j),lcs(a,b,i,j-1)) 17 | 18 | 19 | 20 | #MEMOIZATION APPROACH 21 | global memo 22 | memo=[[-1 for x in range(len(b))] for x in range(len(a))] 23 | def memoized_lcs(a,b,i=len(a)-1,j=len(b)-1): 24 | if(i==-1 or j==-1): 25 | return "" 26 | if(memo[i][j]!=-1): 27 | return memo[i][j] 28 | if(a[i]==b[j]): 29 | memo[i][j]=memoized_lcs(a,b,i-1,j-1)+a[i] 30 | return memo[i][j] 31 | else: 32 | memo[i][j]=max(memoized_lcs(a,b,i-1,j),memoized_lcs(a,b,i,j-1)) 33 | return memo[i][j] 34 | 35 | #print(lcs(a,b)) #THIS MAY HANG YOUR SYSTEM xD 36 | print(memoized_lcs(a,b)) #OUT: ACDEKSKBWJEWNV 37 | -------------------------------------------------------------------------------- /Dynamic Programming/LongestIncreasingPathInMatrix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-increasing-path-in-a-matrix 2 | class Solution: 3 | def longestIncreasingPath(self, matrix): 4 | m, n = len(matrix), len(matrix[0]) 5 | neighbours = [(0, -1), (0, 1), (1, 0), (-1, 0)] 6 | 7 | @lru_cache(None) 8 | def dfs(x, y): 9 | ans = 1 10 | for dx, dy in neighbours: 11 | if 0 <= x+dx < m and 0 <= y+dy < n and matrix[x+dx][y+dy] < matrix[x][y]: 12 | ans = max(ans, dfs(x+dx, y+dy) + 1) 13 | return ans 14 | 15 | return max(dfs(i, j) for i, j in product(range(m), range(n))) 16 | -------------------------------------------------------------------------------- /Dynamic Programming/LongestPalindromicSubsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestPalindromeSubseq(String s) { 3 | if (s==null) 4 | return 0; 5 | 6 | final int n = s.length(); 7 | 8 | if (n<=1) 9 | return n; 10 | 11 | int dp[][] = new int[n][n]; 12 | 13 | for(int i=0; i arr = new ArrayList<>(); 4 | // *** Problem Conversion Concept *** 5 | // We'll never pick the lower value for corresponding location, we want to maximise 6 | // Because as we pick one we will not be able to pick its neighbours 7 | for(int i=0; i ladder){ 14 | ladder = level + A[level]; // build up the ladder 15 | } 16 | stairs--; // move up the ladder 17 | if(stairs == 0) { 18 | jumps++; 19 | stairs = ladder - level; 20 | } 21 | } 22 | return jumps; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Dynamic Programming/MinSumPathInMatrix.py: -------------------------------------------------------------------------------- 1 | # https://www.interviewbit.com/problems/min-sum-path-in-matrix/ 2 | class Solution: 3 | # @param A : list of list of integers 4 | # @return an integer 5 | def minPathSum(self, A): 6 | for i in range(1, len(A[0])): 7 | A[0][i] += A[0][i-1] 8 | for i in range(1, len(A)): 9 | A[i][0] += A[i-1][0] 10 | for i in range(1, len(A)): 11 | for j in range(1, len(A[0])): 12 | A[i][j] += min(A[i-1][j], A[i][j-1]) 13 | return A[-1][-1] 14 | -------------------------------------------------------------------------------- /Dynamic Programming/Min_Number_Of_Squares.java: -------------------------------------------------------------------------------- 1 | //package com.ib; 2 | 3 | public class MinNumberOfSquares { 4 | public int countMinSquares(int A) { 5 | if (A <= 3) return A; 6 | int[] dp = new int[A+1]; 7 | for (int i=0; i<=3; i++){ 8 | dp[i] = i; 9 | } 10 | for(int i=4; i<=A; i++){ 11 | dp[i] = i; // only with 1+1+1+...i times 12 | for(int j=1; j <= Math.ceil(Math.sqrt(i)); j++){ 13 | int temp = j * j; 14 | if (temp > i) break; 15 | else { 16 | dp[i] = Math.min(dp[i], 1 + dp[i-temp]); 17 | } 18 | } 19 | } 20 | return dp[A]; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Dynamic Programming/PPERM.cpp: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/problems/PPERM 2 | 3 | #include 4 | #define MAX 5000001 5 | #define MOD 1000000007 6 | using namespace std; 7 | typedef long long ll; 8 | 9 | ll isprime[MAX]; 10 | ll primes[MAX]; 11 | ll perm[MAX]; 12 | 13 | void sievePerm(){ 14 | fill(isprime, isprime+MAX, 1); 15 | primes[1]=0; 16 | perm[1]=1; 17 | 18 | isprime[1]=0;//one is not a prime number 19 | for(ll i=2; i*i i: 14 | break 15 | dp[i] = min(dp[i], 1+dp[i-tmp]) 16 | op = dp[n] 17 | del dp 18 | return op 19 | 20 | assert(square_sum(13)== 2) 21 | assert(square_sum(4) == 1) 22 | assert(square_sum(6) == 3) 23 | assert(square_sum(41)== 2) 24 | 25 | -------------------------------------------------------------------------------- /Dynamic Programming/UniquePathsInAGrid.py: -------------------------------------------------------------------------------- 1 | # https://www.interviewbit.com/problems/unique-paths-in-a-grid/ 2 | class Solution: 3 | # @param A : list of list of integers 4 | # @return an integer 5 | def uniquePathsWithObstacles(self, A): 6 | dp = [[0 for i in range(len(A[0]))] for j in range(len(A))] 7 | if A[0][0] == 1 or A[-1][-1] == 1: 8 | return 0 9 | dp[0][0] = 1 10 | for i in range(1,len(A[0])): 11 | dp[0][i] = dp[0][i-1] if A[0][i] == 0 else 0 12 | for i in range(1,len(A)): 13 | dp[i][0] = dp[i-1][0] if A[i][0] == 0 else 0 14 | for i in range(1, len(A)): 15 | for j in range(1, len(A[0])): 16 | if A[i][j] == 1: 17 | dp[i][j] = 0 18 | else: 19 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 20 | return dp[-1][-1] 21 | -------------------------------------------------------------------------------- /Dynamic Programming/Wildcard_Matching.py: -------------------------------------------------------------------------------- 1 | # LC 44 [Hard] 2 | 3 | class Solution: 4 | def isMatch(self, s: str, p: str) -> bool: 5 | ns, np = len(s), len(p) 6 | cache = [[False]*(ns+1) for i in range(np+1)] 7 | 8 | # Empty pattern matches empty string 9 | cache[0][0] = True 10 | 11 | # Even empty string should match * 12 | if len(p) and p[0] == '*': 13 | for i in range(len(p)): 14 | if p[i] == '*': 15 | cache[i+1][0] = cache[i][0] 16 | 17 | for i in range(np): 18 | for j in range(ns): 19 | if p[i]==s[j] or p[i]=='?': 20 | cache[i+1][j+1] = cache[i][j] 21 | elif p[i]=='*': 22 | cache[i+1][j+1]=cache[i+1][j] or cache[i][j+1] 23 | #print(cache) 24 | return cache[np][ns] 25 | -------------------------------------------------------------------------------- /Dynamic Programming/bike-trip.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/bike-trip/ 2 | 3 | for _ in range(int(input())): 4 | n = int(input()) 5 | arr1 = [int(x) for x in input().strip().split()] 6 | arr2 = [int(x) for x in input().strip().split()] 7 | 8 | if n==1: 9 | print(min(arr1[0], arr2[0])) 10 | else: 11 | cost1 = [int(x) for x in input().strip().split()] 12 | cost2 = [int(x) for x in input().strip().split()] 13 | 14 | dp1=arr1[0] 15 | dp2=arr2[0] 16 | 17 | for i in range(1,n): 18 | k = dp1 19 | l = dp2 20 | dp1 = min(k, l+cost2[i-1]) + arr1[i] 21 | dp2 = min(l, k+cost1[i-1]) + arr2[i] 22 | print(min(dp1, dp2)) -------------------------------------------------------------------------------- /Dynamic Programming/knapsack_0_1.py: -------------------------------------------------------------------------------- 1 | class Count: 2 | i=0 3 | def knapsack(cap, n, items, table): 4 | Count.i += 1 5 | if(not table[cap][n] == -1): 6 | return table[cap][n] 7 | elif(n==0 or cap==0): 8 | table[cap][n]=0 9 | elif(items[n][1] > cap): 10 | table[cap][n]=knapsack(cap,n-1,items,table) 11 | else: 12 | reject=knapsack(cap,n-1,items,table) 13 | consider=knapsack(cap-items[n][1],n-1,items,table)+items[n][0] 14 | table[cap][n]=max(consider,reject) 15 | return table[cap][n] 16 | 17 | def main(): 18 | n=int(input("ENTER TOTAL NUMBER OF ITEMS: ")) 19 | bagmax=int(input("ENTER CAPACITY OF BAG: ")) 20 | items = [(0,0)] 21 | for i in range(n): 22 | print("ENTER VALUE & WEIGHT: ") 23 | a,b=[int(x) for x in input().strip().split()] 24 | items.append((a,b)) 25 | 26 | cache = [[-1 for x in range(n+1)] for x in range(bagmax+1)] 27 | print("MAXIMUM WEIGHT: " , knapsack(bagmax, n, items, cache)) 28 | print("TOTAL FUNCTION CALLS: ",Count.i) 29 | 30 | if __name__=="__main__": 31 | main() -------------------------------------------------------------------------------- /Dynamic Programming/maximumSumNonAdjacent.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, find a maximum sum of non-adjacent elements. 3 | 4 | For example, inputs [1, 0, 3, 9, 2] should return 10 (1 + 9). 5 | 6 | The question has been asked by Uber recently. 7 | ''' 8 | # My Article : https://medium.com/@amitrajitbose/hello-readers-geeks-techies-coders-bbbcb246882 9 | 10 | def maxSum2(arr): 11 | #BOTTOM UP APPROACH 12 | cache=[0 for x in range(len(arr))] 13 | cache[0]=arr[0] 14 | cache[1]=max(arr[0],arr[1]) 15 | for i in range(2,len(arr)): 16 | cache[i]=max(cache[i-1], arr[i]+cache[i-2]) 17 | return (cache[-1]) 18 | 19 | print(maxSum2([1,0,3,9,2])) #10 20 | print(maxSum2([5,1,1,5])) #10 21 | print(maxSum2([2,4,6,2,5])) #13 -------------------------------------------------------------------------------- /Dynamic Programming/tetrahedron166E.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long LL; 4 | #define MOD 1000000007 5 | int main() 6 | { 7 | LL n; 8 | cin >> n; 9 | LL home=1; 10 | LL away=0; 11 | LL tmphome, tmpaway; 12 | for(LL i=1;i<=n;i++) 13 | { 14 | tmphome=(3*away)%MOD; //if I reach D, that means I was at A,B or C 15 | tmpaway=((2*away)+home)%MOD; //if I reach A(suppose), then I was at B,C or D(home) 16 | home=tmphome; 17 | away=tmpaway; 18 | } 19 | cout << home < 0: 17 | curr += str(cnt) 18 | self.res.append(curr) 19 | else: 20 | self.helper(curr, word, pos+1, cnt+1) 21 | if cnt > 0: 22 | self.helper(curr + str(cnt) + word[pos], word, pos+1, 0) 23 | else: 24 | self.helper(curr + word[pos], word, pos+1, 0) 25 | 26 | -------------------------------------------------------------------------------- /Graphs/Dijkstra/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Graphs/Dijkstra/a.out -------------------------------------------------------------------------------- /Graphs/Dijkstra/graphinput1.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 1 6 3 | 10 4 | 6 1 5 | 5 6 | 1 2 7 | 8 8 | 8 1 9 | 4 10 | 8 2 11 | 9 12 | 7 8 13 | 3 14 | 7 4 15 | 2 16 | 5 7 17 | 7 18 | 4 5 19 | 25 20 | 5 4 21 | 9 22 | 3 4 23 | 3 24 | 6 3 25 | 3 26 | 6 2 27 | 7 28 | 2 3 29 | 4 30 | 2 5 31 | 10 32 | 6 5 33 | 2 34 | 4 6 35 | 18 36 | 0 0 37 | 1 38 | 1 39 | -------------------------------------------------------------------------------- /Graphs/Dijkstra/graphinput2.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 1 2 3 | 10 4 | 2 3 5 | 50 6 | 1 4 7 | 30 8 | 1 5 9 | 100 10 | 4 5 11 | 60 12 | 3 5 13 | 10 14 | 3 4 15 | 20 16 | 0 0 17 | 0 18 | 1 19 | -------------------------------------------------------------------------------- /Graphs/FloydWarshall/FloydWarshall_IB.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] solve(int[][] A) { 3 | int i, j, k, n=A.length; 4 | final int INF = 999999; 5 | int B[][] = new int[n][n]; 6 | for (i=0;i int: 6 | cnt = 0 7 | for i in range(len(grid)): 8 | for j in range(len(grid[0])): 9 | if grid[i][j] == 0 and self.dfs(grid, i, j): 10 | cnt += 1 11 | return cnt 12 | 13 | def dfs(self, grid, i, j): 14 | if not self.valid(grid,i,j): 15 | return False 16 | if grid[i][j] == 1: 17 | return True 18 | grid[i][j] = 1 # mark 19 | a=self.dfs(grid, i, j+1) 20 | b=self.dfs(grid, i+1, j) 21 | c=self.dfs(grid, i, j-1) 22 | d=self.dfs(grid, i-1, j) 23 | return a & b & c & d 24 | 25 | def valid(self, grid, i, j): 26 | return i>=0 and j>=0 and i int: 4 | count = 0 5 | for i in range(len(grid)): 6 | for j in range(len(grid[0])): 7 | if grid[i][j] == '1': 8 | count += self.dfs(grid, i, j) 9 | return count 10 | 11 | def dfs(self, grid, i, j): 12 | if self.valid(grid,i,j) and grid[i][j] == '1': 13 | grid[i][j] = '0' # mark 14 | self.dfs(grid, i, j+1) 15 | self.dfs(grid, i+1, j) 16 | self.dfs(grid, i, j-1) 17 | self.dfs(grid, i-1, j) 18 | return 1 19 | return 0 20 | 21 | def valid(self, grid, i, j): 22 | return i>=0 and j>=0 and i 5 | using namespace std; 6 | struct Job 7 | { 8 | int start,finish; 9 | }; 10 | 11 | bool comparer(Job i, Job j){ 12 | return (i.finish < j.finish); 13 | } 14 | 15 | int main(){ 16 | int test; 17 | cin>>test; 18 | while(test--){ 19 | int n; 20 | cin>>n; 21 | Job arr[n]; 22 | for(int i=0;i>arr[i].start>>arr[i].finish; 24 | } 25 | sort(arr,arr+n,comparer); 26 | int counter=1; //first activity will always be performed 27 | int j=0; 28 | for(int i=1;i=arr[j].finish){ 30 | counter++; 31 | j=i; 32 | } 33 | } 34 | cout< 3 | using namespace std; 4 | typedef long long ll; 5 | int main() { 6 | int test; 7 | cin >> test; 8 | while(test--) 9 | { 10 | ll n, prev; 11 | ll c=0; 12 | cin >> n; 13 | while(n>0) 14 | { 15 | prev = pow(2, floor(log(n)/log(2))); 16 | if(prev > 2048) 17 | prev=2048; 18 | n-=prev; 19 | c++; 20 | } 21 | cout << c << endl; 22 | } 23 | } -------------------------------------------------------------------------------- /Greedy/Count-n-Say.py: -------------------------------------------------------------------------------- 1 | # Count and say sequence 2 | 3 | def countnsay(seq): 4 | res = '' 5 | n = len(seq) 6 | i = 0 7 | while i < n: 8 | cnt = 1 9 | while i 7 | #include 8 | using namespace std; 9 | typedef long long ll; 10 | #define FOR(i,m,n) for(__typeof(n) i = m; i<(n); i++) 11 | 12 | int main() 13 | { 14 | ll t; 15 | cin >> t; 16 | while(t--) 17 | { 18 | ll n, *m, *w; 19 | cin >> n; 20 | m = new ll[n]; 21 | w = new ll[n]; 22 | FOR(i,0,n) 23 | { 24 | cin >> m[i]; 25 | } 26 | sort(m,m+n); 27 | FOR(i,0,n) 28 | { 29 | cin >> w[i]; 30 | } 31 | sort(w,w+n); 32 | ll summ=0; 33 | FOR(i,0,n) 34 | { 35 | summ += (m[i]*w[i]); 36 | } 37 | delete [] m; 38 | delete [] w; 39 | cout << summ << endl; 40 | } 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Greedy/GlobalAndLocalInversions.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/global-and-local-inversions/ 2 | class Solution: 3 | def isIdealPermutation(self, A: List[int]) -> bool: 4 | """ 5 | Approach: 6 | 1) Every local inversion is a global inversion where i and j differ by one 7 | 2) If we can find atleast one global inversion which is not local inversion, then return False 8 | 3) We need to find atleast one pair of A[i] > A[j] such that j-i > 1 9 | 4) Can be done in linear time by maintaining a global max as we traverse the array 10 | """ 11 | gmax = -float('inf') 12 | for i in range(len(A)-2): 13 | gmax = max(gmax, A[i]) 14 | if (gmax > A[i+2]): 15 | return False 16 | return True 17 | -------------------------------------------------------------------------------- /Greedy/JumpGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Amitrajit Bose 3 | LCM55 4 | */ 5 | class Solution { 6 | public boolean canJump(int[] nums) { 7 | int n = nums.length; 8 | int i = 0; 9 | int mx = 0; 10 | while (i < n && mx < n-1){ 11 | mx = Math.max(mx, i + nums[i]); 12 | i++; 13 | if(i > mx) return false; 14 | } 15 | if (mx >= n-1) return true; 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Greedy/JumpGame2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | n=len(nums) 4 | s, l, g = 0, 0, 0 5 | for i in range(n-1): 6 | l=max(l, i+nums[i]) 7 | if i==g: 8 | s+=1 9 | g=l 10 | return s 11 | 12 | -------------------------------------------------------------------------------- /Greedy/Kruskal_MSTAlgorithm/input1.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 8 3 | 1 2 1 4 | 2 3 2 5 | 3 4 3 6 | 4 1 8 7 | 1 6 7 8 | 4 6 6 9 | 3 5 4 10 | 5 6 5 11 | -------------------------------------------------------------------------------- /Greedy/Kruskal_MSTAlgorithm/input2.txt: -------------------------------------------------------------------------------- 1 | 9 2 | 14 3 | 7 6 1 4 | 8 2 2 5 | 6 5 2 6 | 0 1 4 7 | 2 5 4 8 | 8 6 6 9 | 2 3 7 10 | 7 8 7 11 | 0 7 8 12 | 1 2 8 13 | 3 4 9 14 | 5 4 10 15 | 1 7 11 16 | 3 5 14 17 | -------------------------------------------------------------------------------- /Greedy/Kruskal_MSTAlgorithm/output1.txt: -------------------------------------------------------------------------------- 1 | Enter Total Number Of Vertices: Enter Total Number Of Edges: Enter Source VertexDestination VertexEdge Weight 2 | Total MST Weight: 15 3 | 4 | Resultant Minimum Spanning Tree 5 | Src Destn Weigh 6 | 1 2 1 7 | 2 3 2 8 | 3 4 3 9 | 3 5 4 10 | 5 6 5 11 | -------------------------------------------------------------------------------- /Greedy/Kruskal_MSTAlgorithm/output2.txt: -------------------------------------------------------------------------------- 1 | Enter Total Number Of Vertices: Enter Total Number Of Edges: Enter Source VertexDestination VertexEdge Weight 2 | Total MST Weight: 37 3 | 4 | Resultant Minimum Spanning Tree 5 | Src Destn Weigh 6 | 7 6 1 7 | 8 2 2 8 | 6 5 2 9 | 0 1 4 10 | 2 5 4 11 | 2 3 7 12 | 0 7 8 13 | 3 4 9 14 | -------------------------------------------------------------------------------- /Greedy/LEMUSIC.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Author : @amitrajitbose 3 | Problem : https://www.codechef.com/problems/LEMUSIC 4 | Approach : Greedy 5 | ''' 6 | t=int(input()) 7 | for _ in range(t): 8 | n=int(input()) 9 | arr=[] 10 | for i in range(n): 11 | b,l=[int(x) for x in input().strip().split()] 12 | arr.append((b,l)) 13 | arr=sorted(arr, key=lambda x: x[1]) 14 | band={} 15 | for i in range(n): 16 | band[arr[i][0]]=0 #use as hashmap 17 | k=0 18 | uniqueval=0 19 | repeatedval=0 20 | for i in range(n): 21 | if(band[arr[i][0]]==0): 22 | k+=1 #first time listening to this band 23 | band[arr[i][0]]=1 24 | uniqueval+=arr[i][1]*k 25 | else: 26 | #repeated bands, k unchanged 27 | repeatedval+=arr[i][1] 28 | #print(">>>",uniqueval,",",repeatedval,",",k) 29 | print(uniqueval+(repeatedval*k)) 30 | 31 | -------------------------------------------------------------------------------- /Greedy/Maximum-Swap.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-swap 2 | class Solution: 3 | """ 4 | @param num: a non-negative intege 5 | @return: the maximum valued number 6 | """ 7 | def maximumSwap(self, num: int) -> int: 8 | # Write your code here 9 | num = str(num) 10 | n = len(num) 11 | k = n-1 12 | max_val = int(num) 13 | max_digit = 0 14 | max_index = 0 15 | while(k>=0): 16 | if int(num[k])>max_digit: 17 | max_digit = int(num[k]) 18 | max_index = k 19 | else: 20 | temp = list(num) 21 | temp[max_index], temp[k] = temp[k], temp[max_index] 22 | temp = ''.join(temp) 23 | max_val = max(int(max_val), int(temp)) 24 | k -= 1 25 | return int(max_val) 26 | 27 | -------------------------------------------------------------------------------- /Greedy/MeetingRooms2.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/meeting-rooms-ii 2 | 3 | class Solution: 4 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 5 | ts = [] 6 | for i in intervals: 7 | ts.append([i[0], "S"]) 8 | ts.append([i[1], "E"]) 9 | ts.sort(key=lambda x: (x[0], x[1])) 10 | # it is important to note here that E is lexicographically smaller than S 11 | # therefore when at a given time one meeting starts and another meeting ends we prioritize the ending meeting first so the same room can be reused 12 | room = 0 13 | maxroom = 0 14 | for t in ts: 15 | if t[1] == "S": 16 | room += 1 17 | else: 18 | room -= 1 19 | maxroom = max(maxroom, room) 20 | return maxroom 21 | -------------------------------------------------------------------------------- /Greedy/MergeIntervals.py: -------------------------------------------------------------------------------- 1 | # LC 56 - M 2 | class Solution: 3 | def merge(self, inv: List[List[int]]) -> List[List[int]]: 4 | if not len(inv): 5 | return [] 6 | inv = sorted(inv, key=lambda x: x[0]) 7 | finv = [inv[0]] 8 | for i in range(1, len(inv)): 9 | if finv[-1][1] >= inv[i][0]: 10 | finv[-1][1] = max(finv[-1][1], inv[i][1]) #merging 11 | else: 12 | finv.append(inv[i]) 13 | return finv 14 | -------------------------------------------------------------------------------- /Greedy/MinDominoRotationForEqualRow.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def minDominoRotations(self, A: List[int], B: List[int]) -> int: 4 | freq = Counter(A + B) 5 | n = len(A) 6 | maxkey, maxval = -1, -1 7 | for i in freq: 8 | if freq[i] > maxval: 9 | maxkey = i 10 | maxval = freq[i] 11 | if maxval < n: 12 | return -1 13 | Acnt, Bcnt = 0, 0 14 | for i in range(n): 15 | if A[i] != maxkey and B[i] != maxkey: 16 | return -1 17 | if A[i] != maxkey: 18 | Acnt += 1 19 | elif B[i] != maxkey: 20 | Bcnt += 1 21 | return min(Acnt, Bcnt) 22 | 23 | -------------------------------------------------------------------------------- /Greedy/MinXorPair_Greedy.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return an integer 4 | def findMinXor(self, A): 5 | A.sort() 6 | minxor = 2**32 7 | for i in range(1,len(A)): 8 | minxor = min(A[i]^A[i-1], minxor) 9 | return minxor 10 | -------------------------------------------------------------------------------- /Greedy/MyCalendar3_UsingTreeMap.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/my-calendar-iii 2 | 3 | class MyCalendarThree { 4 | TreeMap delta; 5 | 6 | public MyCalendarThree() { 7 | delta = new TreeMap(); 8 | } 9 | 10 | public int book(int start, int end) { 11 | delta.put(start, delta.getOrDefault(start, 0) + 1); 12 | delta.put(end, delta.getOrDefault(end, 0) - 1); 13 | 14 | int active = 0, ans = 0; 15 | for (int d: delta.values()) { 16 | ans = Math.max(ans, active += d); 17 | } 18 | return ans; 19 | } 20 | } 21 | 22 | /* 23 | Reference: 24 | 25 | .getOrDefault() 26 | --------------- 27 | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. 28 | In this case the default value is 0, the key is start/end respectively. 29 | For more: 30 | https://docs.oracle.com/javase/8/docs/api/java/util/Map.html 31 | https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html 32 | */ 33 | -------------------------------------------------------------------------------- /Greedy/TACHSTCK.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/TACHSTCK 2 | # Approach : Greedy 3 | 4 | n,d=[int(x) for x in input().strip().split()] 5 | arr=[] 6 | for _ in range(n): 7 | arr.append(int(input().strip())) 8 | arr=sorted(arr) 9 | c=0 10 | i=0 11 | while(i < n-1): 12 | if(arr[i]>=arr[i+1]-d): 13 | i+=2 14 | c+=1 15 | else: 16 | i+=1 17 | print(c) 18 | 19 | -------------------------------------------------------------------------------- /Greedy/couples-holding-hands.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSwapsCouples(self, row: List[int]) -> int: 3 | idx = [0]*len(row) 4 | for i in range(len(row)): 5 | idx[row[i]] = i 6 | swaps = 0 7 | # print(row) 8 | for i in range(0, len(row), 2): 9 | if row[i+1] != (row[i] ^ 1): 10 | swaps += 1 11 | 12 | t = idx[row[i]^1] 13 | 14 | # updating idx map 15 | idx[row[i]^1] = i+1 16 | idx[row[i+1]] = t 17 | 18 | # swapping 19 | row[i+1], row[t] = row[t], row[i+1] 20 | 21 | # print(row) 22 | return swaps 23 | -------------------------------------------------------------------------------- /Greedy/inp.txt: -------------------------------------------------------------------------------- 1 | 4 5 2 | 1 2 10 3 | 1 3 24 4 | 2 3 2 5 | 2 4 15 6 | 3 4 7 7 | 8 | -------------------------------------------------------------------------------- /Hashing/Anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of strings 3 | # @return a list of list of integers 4 | def anagrams(self, A): 5 | hmp = dict() 6 | pairs = [] 7 | for i in range(len(A)): 8 | vec = self.vectorize(A[i]) # get the vector string 9 | if vec not in hmp: 10 | hmp[vec] = [i+1] 11 | else: 12 | # found an anagram 13 | hmp[vec].append(i+1) 14 | return list(hmp.values()) 15 | 16 | def vectorize(self, w): 17 | vec = [0] * 26 18 | for i in range(len(w)): 19 | vec[ord(w[i])-97] += 1 20 | return ''.join(list(map(str, vec))) 21 | -------------------------------------------------------------------------------- /Hashing/Circular_Loop_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getNext(self, arr, idx): 3 | return (idx + nums[idx]) % len(nums) 4 | 5 | def circularArrayLoop(self, nums: List[int]) -> bool: 6 | visited = {} 7 | def visit(idx): 8 | if idx in visited and visited[idx] == 1 : 9 | return True 10 | elif idx in visited and visited[idx] == 2 : 11 | return False 12 | else: 13 | visited[idx] = 1 #visiting first time 14 | nidx = self.getNext(nums, idx) 15 | if(nums[idx]*nums[nidx]>0 and nidx!=idx and visit(nidx)): 16 | return True 17 | visited[idx] = 2 18 | return False 19 | 20 | return any(visit(i) for i in range(len(nums))) -------------------------------------------------------------------------------- /Hashing/DesignHashSet.py: -------------------------------------------------------------------------------- 1 | #LCE 705 2 | class MyHashSet: 3 | 4 | def __init__(self): 5 | """ 6 | Initialize your data structure here. 7 | """ 8 | self.mem = [set([])] * 1001 9 | 10 | 11 | def add(self, key: int) -> None: 12 | self.mem[key % 1001].add(key) 13 | 14 | 15 | def remove(self, key: int) -> None: 16 | if key in self.mem[key % 1001]: 17 | self.mem[key % 1001].remove(key) 18 | 19 | 20 | def contains(self, key: int) -> bool: 21 | """ 22 | Returns true if this set contains the specified element 23 | """ 24 | return key in self.mem[key % 1001] 25 | 26 | 27 | # Your MyHashSet object will be instantiated and called as such: 28 | # obj = MyHashSet() 29 | # obj.add(key) 30 | # obj.remove(key) 31 | # param_3 = obj.contains(key) 32 | -------------------------------------------------------------------------------- /Hashing/ImageOverlap.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict as d 2 | class Solution: 3 | 4 | def getindices(self, matrix): 5 | res = [] 6 | for i in range(len(matrix)): 7 | for j in range(len(matrix[0])): 8 | if matrix[i][j]==1: res.append((i,j)) 9 | return res 10 | 11 | def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int: 12 | # ---- O(n^2) solution ----- 13 | a, b = self.getindices(A), self.getindices(B) 14 | res = 0 15 | translationcost = d(int) 16 | for i in a: 17 | for j in b: 18 | cost = (j[0]-i[0],j[1]-i[1]) 19 | translationcost[cost] += 1 20 | res = max(res, translationcost[cost]) 21 | #print(translationcost) 22 | return res -------------------------------------------------------------------------------- /Hashing/LargestContinuousSubsequenceZeroSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return a list of integers 4 | def lszero(self, A): 5 | if len(A)==0: 6 | return [] # corner case 7 | ps = 0 8 | maxlen = 0 9 | maxends = [-1,-1] 10 | hmap = dict() 11 | hmap[ps] = -1 12 | for i in range(len(A)): 13 | ps += A[i] 14 | if ps not in hmap: 15 | hmap[ps] = i 16 | else: 17 | if i-hmap[ps] > maxlen: 18 | maxends = [hmap[ps]+1, i] 19 | maxlen = (i-hmap[ps]) 20 | if maxends == [-1,-1]: 21 | return [] 22 | return A[maxends[0]: maxends[1]+1] 23 | 24 | -------------------------------------------------------------------------------- /Hashing/LongestConsecutiveSequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, A: List[int]) -> int: 3 | s = set(A) 4 | A = list(s) 5 | if len(s)==0: 6 | return 0 7 | maxcount = 1 8 | i = 0 9 | while i < len(s): 10 | if A[i]-1 in s: 11 | # to verify that (i) is not a start element 12 | i += 1 13 | else: 14 | count = 1 15 | j = 1 16 | while A[i]+j in s: 17 | count += 1 18 | j += 1 19 | maxcount = max(maxcount, count) 20 | i += 1 21 | return maxcount 22 | 23 | # LC 128 Hard 24 | # Tags: Hashing 25 | 26 | -------------------------------------------------------------------------------- /Hashing/LongestSubarraySumK.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @param B : integer 4 | # @return an integer 5 | def solve(self, A, B): 6 | prefix = dict() 7 | prefix[0] = -1 # initialising prefix sum 8 | ps = 0 9 | maxlen = -1 10 | for i in range(len(A)): 11 | ps += A[i] 12 | if ps not in prefix: 13 | prefix[ps] = i 14 | if ps-B in prefix: 15 | maxlen = max(maxlen, i-prefix[ps-B]) 16 | return maxlen 17 | 18 | -------------------------------------------------------------------------------- /Hashing/Map.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/038d81bbc882de0cf6fe3bcea366c08c3bc85663/Hashing/Map.class -------------------------------------------------------------------------------- /Hashing/MapNode.java: -------------------------------------------------------------------------------- 1 | 2 | public class MapNode { 3 | K key; 4 | V value; 5 | MapNode next; 6 | 7 | public MapNode(K key, V value) { 8 | this.key = key; 9 | this.value = value; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Hashing/NumberOfEquivalentDominoPairs.py: -------------------------------------------------------------------------------- 1 | #LC1128 2 | from collections import defaultdict 3 | class Solution: 4 | def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: 5 | freq = defaultdict(int) 6 | for i,j in dominoes: 7 | if (i,j) in freq: 8 | freq[(i,j)] += 1 9 | else: 10 | freq[(j,i)] += 1 11 | pairs = 0 12 | for i in freq: 13 | pairs += (freq[i] * (freq[i] - 1)) // 2 14 | return pairs 15 | -------------------------------------------------------------------------------- /Hashing/OurMapUse.java: -------------------------------------------------------------------------------- 1 | 2 | public class OurMapUse { 3 | 4 | public static void main(String[] args) { 5 | Map map = new Map<>(); 6 | for (int i = 0; i < 20; i++) { 7 | map.insert("abc" + i, 1 + i); 8 | System.out.println("i = " + i + " lf = " + map.loadFactor()); 9 | } 10 | 11 | map.removeKey("abc3"); 12 | map.removeKey("abc7"); 13 | 14 | for (int i = 0; i < 20; i++) { 15 | System.out.println("abc" + i + ":" + map.getValue("abc" + i)); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Hashing/PairSum_Zero.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Pair Sum Will Be Zero 3 | Print such pairs from the array 4 | Approach: Hashing 5 | ''' 6 | def findPair(arr): 7 | myhash={} 8 | #sweep 1 9 | for i in arr: 10 | if i in myhash: 11 | myhash[i]+=1 12 | else: 13 | myhash[i]=1 14 | #sweep 2 15 | for i in arr: 16 | if(i==0): 17 | continue 18 | comp=0-i 19 | if(comp in myhash): 20 | f=myhash[i]*myhash[comp] 21 | myhash[i]=0 22 | myhash[comp]=0 23 | for j in range(f): 24 | print(min(i,comp),max(i,comp)) 25 | 26 | 27 | a=[int(x) for x in input().strip().split()] 28 | findPair(a[1:]) 29 | -------------------------------------------------------------------------------- /Hashing/RomanNumberToInteger: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : string 3 | # @return an integer 4 | def romanToInt(self, A): 5 | if A=="": 6 | return 0 7 | dictionary = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 8 | totalSum = 0 9 | firstChar = dictionary[A[-1]] 10 | totalSum += firstChar 11 | for i, char in enumerate(A[::-1]): 12 | if i == 0: 13 | continue 14 | if dictionary[char] < dictionary[A[-i]]: 15 | totalSum -= dictionary[char] 16 | else: 17 | totalSum += dictionary[char] 18 | return totalSum 19 | 20 | print(Solution().romanToInt("MDCCLXXIII")) 21 | -------------------------------------------------------------------------------- /Hashing/SubarraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution { 3 | public int subarraySum(int[] arr, int k) { 4 | HashMap hm = new HashMap<>(); 5 | int cnt = 0; 6 | int cs = 0; //current sum 7 | 8 | for (int i=0; i List[List[int]]: 4 | events = [(start, -height, end) for start, end, height in buildings] 5 | # used negative heights as python maintains min heap, we need maxheap 6 | events.extend([(end, 0, 0) for _, end, _ in buildings]) 7 | events.sort() 8 | res = [[0,0]] # point, height 9 | # print(events) 10 | 11 | maxheap = [(0, float("inf"))] # height, end position 12 | for start, negHt, end in events: 13 | # print(res,"<><><>", maxheap) 14 | while maxheap[0][1] <= start: 15 | # popping old entries, already seen 16 | heappop(maxheap) 17 | if negHt: 18 | # if it is the left/start of a building 19 | heappush(maxheap, (negHt, end)) 20 | if res[-1][1] != -maxheap[0][0]: 21 | res.append([start, -maxheap[0][0]]) 22 | res.pop(0) 23 | return res 24 | -------------------------------------------------------------------------------- /Heap/merge-k-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | from heapq import * 7 | class Solution: 8 | def mergeKLists(self, lists: List[ListNode]) -> ListNode: 9 | heads = [] 10 | for i,node in enumerate(lists): 11 | if node: 12 | heappush(heads, (node.val, i, node)) # value, sequence, node ref 13 | newlist = ptr = ListNode(0) 14 | while heads: 15 | _v, _s, cur = heappop(heads) 16 | ptr.next = cur 17 | if cur.next: 18 | heappush(heads, (cur.next.val, _s, cur.next)) 19 | ptr = ptr.next 20 | return newlist.next 21 | -------------------------------------------------------------------------------- /Heap/merge_k_Sorted_lists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given k sorted arrays/lists, merge them into a 3 | single array 4 | Ex: [1,4,7],[2,5,8],[3,6,9] 5 | 6 | Time: O(kn*log(k)) 7 | ''' 8 | import heapq 9 | 10 | def merge(lists): 11 | merged_list = [] 12 | 13 | heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] 14 | 15 | heapq.heapify(heap) 16 | 17 | while heap: 18 | #print(heap) 19 | val, list_ind, element_ind = heapq.heappop(heap) 20 | 21 | merged_list.append(val) 22 | 23 | if element_ind + 1 < len(lists[list_ind]): 24 | next_tuple = (lists[list_ind][element_ind + 1], 25 | list_ind, 26 | element_ind + 1) 27 | heapq.heappush(heap, next_tuple) 28 | return merged_list 29 | 30 | #Test Cases 31 | print(merge([[10,40,70],[20,50,80],[30,60,90]])) 32 | 33 | print(merge([[],[],[]])) 34 | print(merge([[1],[2],[3]])) 35 | print(merge([[],[2],[]])) 36 | print(merge([[1],[2,4],[3,5]])) 37 | print(merge([[1,13,27,45],[2],[3,5,11,14,17,19,22]])) 38 | -------------------------------------------------------------------------------- /LinkedList/OddEvenLinkedList.py: -------------------------------------------------------------------------------- 1 | # 328 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, val=0, next=None): 5 | # self.val = val 6 | # self.next = next 7 | class Solution: 8 | def oddEvenList(self, head: ListNode) -> ListNode: 9 | if not head: 10 | return 11 | 12 | odd = head 13 | even = head.next 14 | evenStarts = head.next 15 | while True: 16 | if not odd or not even or not even.next: 17 | odd.next = evenStarts 18 | break 19 | # connecting odd nodes 20 | odd.next = even.next 21 | odd = even.next 22 | 23 | if not odd.next: 24 | even.next = None 25 | odd.next = evenStarts 26 | break 27 | # connecting even nodes 28 | even.next = odd.next 29 | even = odd.next 30 | return head 31 | 32 | -------------------------------------------------------------------------------- /LinkedList/RemoveZeroSumConsecutiveNodesFromLinkedList,py: -------------------------------------------------------------------------------- 1 | # 1171 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, val=0, next=None): 5 | # self.val = val 6 | # self.next = next 7 | class Solution: 8 | def removeZeroSumSublists(self, head: ListNode) -> ListNode: 9 | dummy = curr = ListNode(0) 10 | dummy.next = head 11 | ps = 0 12 | psmap = {} 13 | while curr: 14 | ps += curr.val 15 | if not ps in psmap: 16 | psmap[ps] = curr 17 | else: 18 | curr = psmap[ps].next 19 | tSum = ps + curr.val 20 | while tSum != ps and tSum in psmap: 21 | del psmap[tSum] 22 | curr = curr.next 23 | tSum += curr.val 24 | psmap[ps].next = curr.next 25 | curr = curr.next 26 | return dummy.next 27 | 28 | -------------------------------------------------------------------------------- /LinkedList/ReversingList.py: -------------------------------------------------------------------------------- 1 | class Node(): 2 | """docstring for Node""" 3 | def __init__(self, val): 4 | super(Node, self).__init__() 5 | self.val = val 6 | self.next = None 7 | 8 | 9 | def reverseLinkedList(head): 10 | prevn = None 11 | currn = head 12 | nextn = head.next 13 | head.next = None 14 | head = nextn 15 | while (nextn): 16 | prevn = currn 17 | currn = nextn 18 | nextn = head.next 19 | currn.next = prevn #reversing the link 20 | head = nextn 21 | return currn 22 | 23 | def printlist(head): 24 | while head: 25 | print (head.val) 26 | head = head.next 27 | 28 | head = Node(1) 29 | head.next = Node(2) 30 | head.next.next = Node(3) 31 | printlist(head) 32 | head = reverseLinkedList(head) 33 | print('-----') 34 | printlist(head) -------------------------------------------------------------------------------- /LinkedList/SwapNodesInPair.py: -------------------------------------------------------------------------------- 1 | # LC24 2 | # https://leetcode.com/problems/swap-nodes-in-pairs/description/ 3 | ################################################################ 4 | # Definition for singly-linked list. 5 | # class ListNode: 6 | # def __init__(self, val=0, next=None): 7 | # self.val = val 8 | # self.next = next 9 | class Solution: 10 | def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: 11 | if not head or not head.next: 12 | return head 13 | prev, h1, h2, newhead = None, head, head.next, head.next 14 | 15 | while h1 and h2: 16 | if prev: 17 | prev.next = h2 18 | nxt = h2.next 19 | h2.next = h1 20 | prev = h1 21 | if nxt: 22 | h1 = nxt 23 | h2 = nxt.next 24 | prev.next = nxt 25 | else: 26 | prev.next = None 27 | break 28 | return newhead 29 | -------------------------------------------------------------------------------- /LinkedList/swap-nodes-in-pairs.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def swapPairs(self, head: ListNode) -> ListNode: 8 | if not head or not head.next: 9 | return head 10 | newhead = head.next 11 | ptr = head 12 | prev = None 13 | while ptr: 14 | if ptr.next: 15 | tmp = ptr.next.next 16 | ptr.next.next = ptr 17 | if prev: 18 | prev.next = ptr.next 19 | ptr.next = tmp 20 | prev = ptr 21 | ptr = tmp 22 | else: 23 | return newhead 24 | return newhead 25 | 26 | -------------------------------------------------------------------------------- /Misc/BinaryTree_ArrayRep.c: -------------------------------------------------------------------------------- 1 | //Binary Tree SKM Sir Homework 2 | #include 3 | #include 4 | #include 5 | int main(){ 6 | int level; 7 | int i=0; 8 | printf("ENTER LEVELS: "); 9 | scanf("%d",&level); 10 | int n=pow(2,level)-1; 11 | int *a=(int *)malloc(n*sizeof(int)); 12 | printf("ENTER ROOT: "); 13 | scanf("%d",&a[0]); 14 | int l=0; 15 | int k; 16 | while(l 2 | #include 3 | int main() 4 | { 5 | float x=10.1; 6 | printf("%f",x); 7 | if(x==10.1) 8 | printf("\nTRUE"); 9 | else 10 | printf("\nFALSE"); 11 | getch(); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Misc/LRUCache_Optimized.java: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | private LinkedHashMap map; 3 | private final int CAPACITY; 4 | public LRUCache(int capacity) { 5 | CAPACITY = capacity; 6 | map = new LinkedHashMap(capacity, 0.75f, true) { 7 | protected boolean removeEldestEntry(Map.Entry eldest) 8 | { 9 | return size() > CAPACITY; 10 | } 11 | }; 12 | } 13 | 14 | public int get(int key) { 15 | return map.getOrDefault(key, -1); 16 | } 17 | 18 | public void put(int key, int value) { 19 | map.put(key, value); 20 | } 21 | } 22 | 23 | /** 24 | * Your LRUCache object will be instantiated and called as such: 25 | * LRUCache obj = new LRUCache(capacity); 26 | * int param_1 = obj.get(key); 27 | * obj.put(key,value); 28 | */ 29 | -------------------------------------------------------------------------------- /Misc/LargestPalindromeProduct.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the largest palindrome made from the product of two n-digit numbers. 3 | 4 | Since the result could be very large, you should return the largest palindrome mod 1337. 5 | 6 | 7 | 8 | Example: 9 | 10 | Input: 2 11 | 12 | Output: 987 13 | 14 | Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 15 | ''' 16 | 17 | 18 | class Solution: 19 | 20 | def largestPalindrome(self, n: int) -> int: 21 | if n == 1: 22 | return 9 23 | maxlim = (10**n)-1 24 | minlim = 10**(n-1) 25 | for i in range(maxlim-1, maxlim//10, -1): 26 | u = int(str(i) + str(i)[::-1]) 27 | j = maxlim 28 | while (j**2 >= u): 29 | if u % j == 0: 30 | return u 31 | j -= 1 32 | return 0 33 | 34 | 35 | print([Solution().largestPalindrome(i) for i in [1, 2, 3, 4, 5, 6, 7, 8]]) 36 | -------------------------------------------------------------------------------- /NextNumber.py: -------------------------------------------------------------------------------- 1 | def next_number(n): 2 | binary = list(bin(int(n))[2:]) 3 | onecount = binary.count('1') 4 | zerocount = binary.count('0') 5 | if(n==1): 6 | return 2 7 | elif(zerocount==0): 8 | res = '1'+'0'+('1'*(onecount-1)) 9 | return int(res,2) 10 | -------------------------------------------------------------------------------- /Number_Theory/EulerTotientFunc.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Author: @amitrajitbose 3 | Problem : https://www.hackerearth.com/practice/math/number-theory/totient-function/practice-problems/algorithm/euler-totient-function/ 4 | ''' 5 | def SieveOfEratosthenes(n): 6 | prime = [True for i in range(n+1)] 7 | p=2 8 | while(p * p <= n): 9 | 10 | # If prime[p] is not changed, then it is a prime 11 | if (prime[p] == True): 12 | 13 | # Update all multiples of p 14 | for i in range(p * 2, n+1, p): 15 | prime[i] = False 16 | p+=1 17 | prime[1]=False 18 | return prime 19 | 20 | 21 | N=int(input()) 22 | prime=SieveOfEratosthenes(N+1) 23 | ans=N 24 | for i in range(2,N+1): 25 | if(prime[i] and N%i==0): 26 | ans=ans*(1-(1/i)) 27 | print(int(ans)) 28 | -------------------------------------------------------------------------------- /Number_Theory/HappyNumber.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/happy-number/description/ 2 | class Solution: 3 | def isHappy(self, n: int) -> bool: 4 | visited = set([n]) 5 | n = self.getNext(n) 6 | while n != 1 and n not in visited: 7 | visited.add(n) 8 | n = self.getNext(n) 9 | return n == 1 10 | def getNext(self, n): 11 | res = 0 12 | while n>0: 13 | res = res + ((n%10)**2) 14 | n = n // 10 15 | return res 16 | -------------------------------------------------------------------------------- /Number_Theory/HelpDory.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/contests/game-of-codes-3-0/challenges/help-dory 2 | # https://www.hackerrank.com/rest/contests/game-of-codes-3-0/challenges/help-dory/download_pdf?language=English 3 | 4 | def removeAlternate(n): 5 | if (n == 1): 6 | return 1 7 | 8 | if (n % 2 == 0): 9 | return 2 * removeAlternate(n / 2) - 1 10 | else: 11 | return 2 * removeAlternate(((n - 1) / 2)) + 1 12 | 13 | 14 | # Driver code 15 | 16 | for _ in range(int(input())): 17 | n=int(input()) 18 | print(removeAlternate(n)) -------------------------------------------------------------------------------- /Number_Theory/Primality Test/GCDEX.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Author: @amitrajitbose 4 | ''' 5 | phi=[0 for x in range(1000005)] 6 | phi[1]=1 7 | for i in range(2,1000002): 8 | if(phi[i]==0): 9 | phi[i]=i-1 10 | for j in range(i+1,1000001,i): 11 | if(phi[j]==0): 12 | phi[j]=j 13 | phi[j]-=phi[j]/i 14 | res=[0 for x in range(1000001)] 15 | for i in range(1,1000001): 16 | for j in range(i+1,1000001,i): 17 | res[j]+=(i*phi[j//i]) 18 | 19 | for i in range(1,1000001): 20 | res[i]+=res[i-1] 21 | n=1 22 | while(n!=0): 23 | n=int(input()) 24 | if(n==0): 25 | break 26 | else: 27 | print(res[n]) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Number_Theory/Primality Test/Roy_and_Shopping.py: -------------------------------------------------------------------------------- 1 | #Sieve 2 | def SieveOfEratosthenes(n): 3 | 4 | # Create a boolean array "prime[0..n]" and initialize 5 | # all entries it as true. A value in prime[i] will 6 | # finally be false if i is Not a prime, else true. 7 | prime = [True for i in range(n+1)] 8 | reqlist=[] 9 | p=2 10 | while(p * p <= n): 11 | 12 | # If prime[p] is not changed, then it is a prime 13 | if (prime[p] == True): 14 | 15 | # Update all multiples of p 16 | for i in range(p * 2, n+1, p): 17 | prime[i] = False 18 | p+=1 19 | 20 | # Print all prime numbers 21 | for p in range(2, n): 22 | if prime[p]: 23 | reqlist.append(p) 24 | return(reqlist) 25 | 26 | primes=SieveOfEratosthenes(10**6 +1) 27 | t=int(input()) 28 | for _ in range(t): 29 | r=int(input()) 30 | for i in primes: 31 | if i>=r: 32 | print(0) 33 | break 34 | elif r%i==0: 35 | print(r-i) 36 | break -------------------------------------------------------------------------------- /Number_Theory/TotalHammingDistance.py: -------------------------------------------------------------------------------- 1 | # IB # LCM477 2 | from math import ceil, log 3 | class Solution: 4 | # @param A : list of integers 5 | # @return an integer 6 | def ithBitSet(self, n, i): 7 | return (n >> (i-1))%2 8 | def cntBits(self, A): 9 | # Leetcode Hack 10 | #return sum(2 * b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, A))) % ((10**9)+7) 11 | # Gareebo Ka Soluchaan 12 | if len(A) < 1: 13 | return 0 14 | if max(A) < 2: 15 | return max(A) 16 | m = ceil(log(max(A),2)) 17 | res = 0 18 | n = len(A) 19 | MOD = ((10**9)+7) 20 | for i in range(1,m+2): 21 | setcount = sum([self.ithBitSet(j,i) for j in A]) 22 | #print(setcount, n-setcount) 23 | #res += setcount * (n-setcount) # when i <= j 24 | res += setcount * (n-setcount) * 2 # because all pairs, i can be greater than j as well 25 | return res % MOD 26 | 27 | ''' 28 | The function f(x,y) is called the hamming distance for bitwise algebra 29 | ''' 30 | 31 | -------------------------------------------------------------------------------- /Searching_Sorting/BinarySearch/FirstBadVersion.java: -------------------------------------------------------------------------------- 1 | /* The isBadVersion API is defined in the parent class VersionControl. 2 | boolean isBadVersion(int version); */ 3 | 4 | public class Solution extends VersionControl { 5 | public int firstBadVersion(int n) { 6 | int left = 1; 7 | int right = n; 8 | int mid; 9 | while(left <= right) 10 | { 11 | mid = left + (right-left)/2; 12 | if(isBadVersion(mid)) 13 | right = mid-1; 14 | else 15 | left = mid+1; 16 | } 17 | return left; 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /Searching_Sorting/BinarySearch/ImplementPowerFunction.cpp: -------------------------------------------------------------------------------- 1 | int Solution::pow(int x, int n, int d) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | 7 | if (n==0) return 1 % d; 8 | if (d==1) return 0; 9 | 10 | long long int ans = 1; 11 | long long int base = x; 12 | 13 | while (n>0){ 14 | if (n & 1){ 15 | ans = (ans * base) % d; 16 | n -= 1; 17 | } 18 | base = (base * base) % d; 19 | n >>= 1; 20 | } 21 | if (ans < 0) ans = (ans + d) % d; 22 | return ans; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Searching_Sorting/BinarySearch/QUERARR.py: -------------------------------------------------------------------------------- 1 | def bs(arr,low,high): 2 | l=0 3 | r=len(arr)-1 4 | while(l<=r): 5 | mid=l+(r-l)//2 6 | if(arr[mid]>=low and arr[mid]<=high): 7 | return True #index present in range 8 | elif(arr[mid] int: 5 | n = len(nums) 6 | if n == 0: 7 | return -1 8 | if n == 1: 9 | return 0 if nums[0] == target else -1 10 | # apply modified binary search 11 | low = 0 12 | high = n-1 13 | while low <= high: 14 | mid = (low + high) // 2 15 | if nums[mid] == target: 16 | return mid 17 | if nums[low] <= nums[mid]: 18 | # left part sorted 19 | if target >= nums[low] and target <= nums[mid]: 20 | high = mid - 1 21 | else: 22 | low = mid + 1 23 | else: 24 | # right part sorted 25 | if target >= nums[mid] and target <= nums[high]: 26 | low = mid + 1 27 | else: 28 | high = mid - 1 29 | return -1 # target not found 30 | 31 | -------------------------------------------------------------------------------- /Searching_Sorting/CREP.py: -------------------------------------------------------------------------------- 1 | #https://www.codechef.com/DEME2018/problems/CREP/ 2 | 3 | import collections 4 | t=int(input()) 5 | for _ in range(t): 6 | n,k=[int(x) for x in input().strip().split()] 7 | a=[int(x) for x in input().strip().split()] 8 | counter=collections.Counter(a) 9 | summ=0 10 | flag=0 11 | for i in counter.keys(): 12 | if(counter[i]==k): 13 | summ+=i 14 | flag=1 15 | if(flag==1): 16 | print(summ) 17 | elif(flag==0): 18 | print(-1) -------------------------------------------------------------------------------- /Searching_Sorting/CutTheSticks.py: -------------------------------------------------------------------------------- 1 | def cutTheSticks(arr): 2 | arr.sort(reverse = True) 3 | res = [] 4 | while arr: 5 | res.append(len(arr)) 6 | for i in range(len(arr)): 7 | arr[i] -= arr[-1] 8 | while len(arr) and arr[-1] <= 0: 9 | arr.pop(-1) 10 | return res 11 | 12 | if __name__ == '__main__': 13 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 14 | 15 | n = int(input()) 16 | 17 | arr = list(map(int, input().rstrip().split())) 18 | 19 | result = cutTheSticks(arr) 20 | 21 | fptr.write('\n'.join(map(str, result))) 22 | fptr.write('\n') 23 | 24 | fptr.close() 25 | 26 | -------------------------------------------------------------------------------- /Searching_Sorting/GameShopping1009A.py: -------------------------------------------------------------------------------- 1 | #Problem: https://codeforces.com/problemset/problem/1009/A 2 | 3 | n,m=[int(x) for x in input().strip().split()] 4 | c=[int(x) for x in input().strip().split()] 5 | a=[int(x) for x in input().strip().split()] 6 | ptrc=0 7 | ptra=0 8 | lc=len(c) 9 | la=len(a) 10 | cnt=0 11 | while(ptrc=1 or (a==b)): 23 | stack.append(s[i]) 24 | #print(stack) 25 | elif((b-a)>=1): 26 | while((b-a)>=1): 27 | tempstack.append(stack.pop()) 28 | if(len(stack)>0): 29 | b=ord(stack[-1]) 30 | else: 31 | break 32 | stack.append(s[i]) 33 | while(len(tempstack)>0): 34 | stack.append(tempstack.pop()) 35 | #print(stack) 36 | 37 | print(''.join(stack)) -------------------------------------------------------------------------------- /Searching_Sorting/MinSwapSegregate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary string segregate 1s and 0s by swapping only adjacent elements. You need to print the minimum number 3 | of adjacent swaps required to bring all 1s in front and all 0s behind it or vice versa 4 | ''' 5 | def minswap(arr): 6 | oneptr=0 7 | onepenalty=0 8 | zeroptr=0 9 | zeropenalty=0 10 | n=len(arr) 11 | for i in range(n): 12 | if(arr[i]==1): 13 | onepenalty+=(i-oneptr) 14 | oneptr+=1 15 | if(arr[i]==0): 16 | zeropenalty+=(i-zeroptr) 17 | zeroptr+=1 18 | return(min(onepenalty,zeropenalty)) 19 | 20 | print(minswap([1,1,1,0,1,0])) 21 | print(minswap([1,0,0,0,0,1])) 22 | print(minswap([0,0,1,1,0,0])) 23 | print(minswap([1,1,0,1,0,0])) 24 | print(minswap([0,0,1,0,0,1])) 25 | print(minswap([1,0,0,1,1])) 26 | print(minswap([1,0,1,0,1,1])) -------------------------------------------------------------------------------- /Searching_Sorting/MinimumTernaryString1009B.py: -------------------------------------------------------------------------------- 1 | #Problem: https://codeforces.com/contest/1009/problem/B 2 | #THIS FAILS TO CLEAR TC #4 3 | 4 | stack=[] #primary stack 5 | tempstack=[] #secondary stack 6 | s=list(input()) 7 | 8 | l=len(s) 9 | stack.append(s[0]) 10 | 11 | for i in range(1,l): 12 | a=ord(s[i]) 13 | b=ord(stack[-1]) 14 | 15 | if((a-b)==1 or abs(a-b)==2 or (a==b)): 16 | stack.append(s[i]) 17 | #print(stack) 18 | elif((b-a)==1): 19 | while((b-a)==1): 20 | tempstack.append(stack.pop()) 21 | if(len(stack)>0): 22 | b=ord(stack[-1]) 23 | else: 24 | break 25 | stack.append(s[i]) 26 | while(len(tempstack)>0): 27 | stack.append(tempstack.pop()) 28 | #print(stack) 29 | 30 | print(''.join(stack)) 31 | -------------------------------------------------------------------------------- /Searching_Sorting/ORDTEAMS_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ACM ICPC 2017 Online Prelim - Ordering Teams 3 | Solution By : @IAmRiddhi 4 | ''' 5 | def isComparable(a,b): 6 | eq = 0 7 | g1 = 0 8 | g2 = 0 9 | for i in range(3): 10 | if a[i]==b[i]: 11 | eq += 1 12 | elif a[i]>b[i]: 13 | g1 += 1 14 | else: 15 | g2 += 1 16 | return (g1>g2 and g2==0) or (g2>g1 and g1==0) 17 | 18 | for T in range(int(input())): 19 | s1 = list(map(int,input().split())) 20 | s2 = list(map(int,input().split())) 21 | s3 = list(map(int,input().split())) 22 | 23 | if isComparable(s1,s2) and isComparable(s2,s3) and isComparable(s1,s3): 24 | print("yes") 25 | else: 26 | print("no") -------------------------------------------------------------------------------- /Searching_Sorting/SortArrayOf012.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of only three possible elements - 0,1,2. Sort the array. Use minimal possible time and operations. 3 | * Approach: Hash 4 | * Author: Amitrajit Bose 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | int t; 12 | cin >> t; 13 | while(t--){ 14 | int n; 15 | cin >> n; 16 | int b[3]={0,0,0}; 17 | int num; 18 | for(int i=0;i> num; 20 | b[num%3]+=1; 21 | } 22 | for(int i=0;i<3;i++){ 23 | //cout << b[i]; 24 | while(b[i]!=0){ 25 | cout << i << " "; 26 | b[i]-=1; 27 | } 28 | } 29 | cout< None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | 7 | low,mid,high = 0,0,len(arr)-1 8 | while(mid <= high): 9 | if arr[mid] == 2: 10 | arr[mid],arr[high] = arr[high],arr[mid] 11 | high -= 1 12 | elif arr[mid] == 0: 13 | arr[mid],arr[low] = arr[low], arr[mid] 14 | low += 1 15 | mid += 1 16 | else: 17 | mid += 1 18 | -------------------------------------------------------------------------------- /Searching_Sorting/WGHTNUM.py: -------------------------------------------------------------------------------- 1 | #https://www.codechef.com/APRIL18B/problems/WGHTNUM 2 | 3 | t=int(input()) 4 | MOD=1000000007 5 | for _ in range(t): 6 | n,w=[int(x) for x in input().strip().split(' ')] 7 | if(abs(w)<=9): 8 | if(w>=0): 9 | x=n-2 10 | res=(9-w)*pow(10,x,MOD) 11 | print(res%MOD) 12 | else: 13 | x=n-2 14 | res=(10+w)*pow(10,x,MOD) 15 | print(res%MOD) 16 | else: 17 | print(0) -------------------------------------------------------------------------------- /Searching_Sorting/WaveArray.py: -------------------------------------------------------------------------------- 1 | # https://www.interviewbit.com/problems/wave-array/ 2 | class Solution: 3 | # @param A : list of integers 4 | # @return a list of integers 5 | def wave(self, A): 6 | A.sort() 7 | B = [] 8 | n = len(A) 9 | for i in range(1,n,2): 10 | B.append(A[i]) 11 | B.append(A[i-1]) 12 | if n%2: 13 | B.append(A[-1]) 14 | return B 15 | -------------------------------------------------------------------------------- /SegmentTrees/ginp.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 3 4 5 5 3 | 0 1 2 4 | 1 2 3 5 | 3 0 0 0 1 2 3 6 | 2 3 4 7 | 3 1 1 1 2 2 2 8 | 9 | -------------------------------------------------------------------------------- /SegmentTrees/inp.txt: -------------------------------------------------------------------------------- 1 | 5 5 2 | 1 5 2 4 3 3 | q 1 5 4 | q 1 3 5 | q 3 5 6 | u 3 6 7 | q 1 5 8 | 9 | -------------------------------------------------------------------------------- /SegmentTrees/lazyinp.txt: -------------------------------------------------------------------------------- 1 | 10 6 2 | 1 2 3 4 5 6 7 8 9 10 3 | q 5 10 4 | q 2 8 5 | u 2 9 1 6 | q 9 10 7 | u 2 9 -1 8 | q 7 9 9 | 10 | -------------------------------------------------------------------------------- /Stack_Queue/DailyTemperatures.py: -------------------------------------------------------------------------------- 1 | # LCM739 2 | class Solution: 3 | def dailyTemperatures(self, T: List[int]) -> List[int]: 4 | n = len(T) 5 | res = [0] * n 6 | st = [0] 7 | for i in range(1,n): 8 | while st and T[st[-1]] < T[i]: 9 | x = st.pop(-1) 10 | res[x] = i - x 11 | st.append(i) 12 | return res 13 | -------------------------------------------------------------------------------- /Stack_Queue/KthCharInDoubleDecryptedString.cpp: -------------------------------------------------------------------------------- 1 | # Kth Character In Double Decrypted String 2 | # 3 | # 4 | string Solution::solve(string A, int B) 5 | { 6 | stack>st; 7 | long long int len = 0,n=A.size(),freq; 8 | string temp; 9 | for(int i=0;i=B) 22 | break; 23 | len = len*freq; 24 | i--; 25 | } 26 | } 27 | while(!st.empty()){ 28 | pair p = st.top(); 29 | st.pop(); 30 | B = B%p.second; 31 | if(B==0) 32 | return p.first; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Stack_Queue/LongestValidParenthesis.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestValidParentheses(String A) { 3 | Deque st = new ArrayDeque<>(); 4 | st.push(-1); 5 | int n = A.length(); 6 | int maxlen = 0; 7 | for(int i=0; i int: 3 | st = [-1] 4 | maxlen = 0 5 | for i in range(len(s)): 6 | if s[i] == '(': 7 | st.append(i) 8 | else: 9 | st.pop(-1) 10 | if not st: 11 | st.append(i) 12 | else: 13 | maxlen = max(maxlen, i-st[-1]) 14 | return maxlen 15 | -------------------------------------------------------------------------------- /Stack_Queue/MinStack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | self.stack = [] 5 | self.mins = [] 6 | self.min = -1 7 | 8 | # @param x, an integer 9 | # @return an integer 10 | def push(self, x): 11 | self.stack.append(x) 12 | if len(self.stack) == 1 or x <= self.min: 13 | self.mins.append(x) 14 | self.min = x 15 | 16 | # @return nothing 17 | def pop(self): 18 | if not len(self.stack): 19 | return -1 20 | if self.stack[-1] == self.min: 21 | self.mins.pop(-1) 22 | self.min = self.mins[-1] if len(self.mins)>0 else -1 23 | self.stack.pop(-1) 24 | 25 | 26 | # @return an integer 27 | def top(self): 28 | return self.stack[-1] if len(self.stack) else -1 29 | 30 | 31 | # @return an integer 32 | def getMin(self): 33 | return self.min 34 | 35 | -------------------------------------------------------------------------------- /Stack_Queue/NearestSmallestElement.py: -------------------------------------------------------------------------------- 1 | # Stacks 2 | # IB : Nearest Smallest Element 3 | # @amitrajitbose 4 | # 5 | # 6 | class Solution: 7 | # @param A : list of integers 8 | # @return a list of integers 9 | def prevSmaller(self, A): 10 | incrStack = [A[0]] 11 | res = [-1] 12 | for i in range(1, len(A)): 13 | if A[i] <= incrStack[0]: 14 | # first element stores the smallest 15 | # replace the stack 16 | incrStack = [A[i]] 17 | res.append(-1) 18 | else: 19 | for j in range(len(incrStack)-1, -1, -1): 20 | if incrStack[j] < A[i]: 21 | res.append(incrStack[j]) 22 | incrStack.append(A[i]) 23 | break 24 | return res 25 | -------------------------------------------------------------------------------- /Stack_Queue/NextGreaterElement1.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] nextGreaterElement(int[] nums1, int[] nums2) { 3 | if (nums1.length<=0 || nums2.length <= 0){ 4 | return new int[0]; 5 | } 6 | Deque st = new ArrayDeque<>(); //stack 7 | Map map = new HashMap<>(); //solution set 8 | st.push(0); // first index 9 | 10 | for (int i=1; i=nums[q[-1]]): 15 | q.pop(-1) 16 | q.append(i) 17 | #slide the window and add to out array 18 | for i in range(k,n): 19 | out.append(nums[q[0]]) #previous window maximum 20 | #check for residuals 21 | while(len(q) and q[0]<=i-k): 22 | #element does not belong to current window 23 | q.pop(0) 24 | curr=nums[i] 25 | while(len(q) and curr>=nums[q[-1]]): 26 | q.pop(-1) 27 | q.append(i) 28 | out.append(nums[q[0]]) 29 | return out 30 | -------------------------------------------------------------------------------- /Stack_Queue/SlidingWindowMin.py: -------------------------------------------------------------------------------- 1 | from collections import deque as Queue 2 | 3 | def slider(arr,k): 4 | n=len(arr) 5 | q=Queue() 6 | 7 | #from the first k elements keep the max and decreasing 8 | for i in range(k): 9 | while(len(q) and arr[i]<=arr[q[-1]]): 10 | q.pop() 11 | q.append(i) 12 | for i in range(k,n): 13 | #previous window min 14 | print(arr[q[0]],end=" ") 15 | #if any element does not belong to this window we pop the, 16 | while(len(q) and q[0]<=i-k): 17 | #this index does not belong to this window 18 | q.popleft() 19 | #remove all smaller elements 20 | curr=arr[i] 21 | while(len(q) and curr<=arr[q[-1]]): 22 | q.pop() 23 | q.append(i) 24 | print(arr[q[0]]) 25 | 26 | slider([10, 5, 2, 7, 8, 7],3) 27 | slider([2, 10, 5, 7, 7, 8],3) 28 | slider([10,0,3,2,5],2) -------------------------------------------------------------------------------- /Stack_Queue/TrappingRainWater.py: -------------------------------------------------------------------------------- 1 | # One Iteration, Linear Space (Stack) Sol. 2 | # IB : Rain Water Trapped 3 | # Author : @amitrajitbose 4 | # 5 | # 6 | class Solution: 7 | # @param A : tuple of integers 8 | # @return an integer 9 | def trap(self, A): 10 | st = [] 11 | i = 0 12 | ans = 0 13 | while iA[st[-1]]: 15 | top = st.pop(-1) 16 | if not st: 17 | break 18 | dist = i-st[-1]-1 19 | bounded_height = min(A[i], A[st[-1]]) - A[top] 20 | ans += (dist * bounded_height) 21 | st.append(i) #push 22 | i += 1 23 | return ans 24 | # Ref : https://leetcode.com/articles/trapping-rain-water/ 25 | -------------------------------------------------------------------------------- /Stack_Queue/ValidParentheses.py: -------------------------------------------------------------------------------- 1 | # LC - 20 2 | class Solution: 3 | def isValid(self, s: str) -> bool: 4 | stack = [] 5 | hmap = {']':'[', '}':'{', ')':'('} 6 | flag = True 7 | for i in s: 8 | if i in ['[','{','(']: 9 | stack.append(i) 10 | else: 11 | if len(stack) and hmap[i] == stack[-1]: 12 | stack.pop(-1) 13 | else: 14 | flag = False 15 | break 16 | return flag and len(stack)==0 17 | -------------------------------------------------------------------------------- /Tree/BTMaxPathSum.py: -------------------------------------------------------------------------------- 1 | #LCH124 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | class Solution: 11 | def maxPathSum(self, root: TreeNode) -> int: 12 | self.maxsum = -float('inf') 13 | 14 | def maxPathSumUtil(root: TreeNode) -> int: 15 | if not root: 16 | return 0 # base case 17 | leftsum = maxPathSumUtil(root.left) 18 | rightsum = maxPathSumUtil(root.right) 19 | self.maxsum = max(self.maxsum, root.val, root.val + leftsum, root.val + rightsum, root.val + leftsum + rightsum) 20 | return max(0, leftsum, rightsum) + root.val 21 | 22 | maxPathSumUtil(root) 23 | return self.maxsum -------------------------------------------------------------------------------- /Tree/DeepestLeavesSum.py: -------------------------------------------------------------------------------- 1 | # Given the root of a binary tree, return the sum of values of its deepest leaves. 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def maxDepth(self, root: TreeNode) -> int: 11 | if not root: 12 | return 0 13 | else: 14 | return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 15 | 16 | def deepestLeavesSum(self, root: TreeNode) -> int: 17 | leafSum = [0] 18 | def dfs(node, level, maxDep, leafSum): 19 | if not node: 20 | return 21 | if level == maxDep: 22 | leafSum[0] += node.val 23 | else: 24 | dfs(node.left, level + 1, maxDep, leafSum) 25 | dfs(node.right, level + 1, maxDep, leafSum) 26 | dfs(root, 1, self.maxDepth(root), leafSum) 27 | return leafSum[0] 28 | -------------------------------------------------------------------------------- /Tree/InorderSuccessorBST.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/inorder-successor-in-bst/ 2 | # LintCode 448 3 | 4 | """ 5 | Definition for a binary tree node. 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | """ 12 | 13 | 14 | class Solution: 15 | """ 16 | @param: root: The root of the BST. 17 | @param: p: You need find the successor node of p. 18 | @return: Successor of p. 19 | """ 20 | def inorderSuccessor(self, root, p): 21 | # write your code here 22 | possibleSuccessor = None 23 | curr = root 24 | while curr: 25 | if curr.val > p.val: 26 | possibleSuccessor = curr 27 | curr = curr.left # try to look for a lesser value, nearer successor 28 | else: 29 | curr = curr.right # get to the search node so that we can find successor 30 | return possibleSuccessor 31 | 32 | -------------------------------------------------------------------------------- /Tree/InvertBinaryTree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def invertTree(self, root: TreeNode) -> TreeNode: 9 | if root: 10 | root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) 11 | return root 12 | -------------------------------------------------------------------------------- /Tree/MergeTwoBinaryTrees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 9 | if not t1: 10 | return t2 11 | if not t2: 12 | return t1 13 | t1.val += t2.val 14 | t1.left = self.mergeTrees(t1.left, t2.left) 15 | t1.right = self.mergeTrees(t1.right, t2.right) 16 | return t1 17 | 18 | -------------------------------------------------------------------------------- /Tree/PrefixWordPrediction.py: -------------------------------------------------------------------------------- 1 | ''' 2 | DCP #11 3 | Alternate Solution 4 | 5 | This problem was asked by Twitter. 6 | 7 | Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. 8 | 9 | For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. 10 | 11 | Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. 12 | ''' 13 | def predict(s,a): 14 | out=[x for x in a if(x.startswith(s))] 15 | return out 16 | 17 | a=['dog','deer','deal'] 18 | s='de' 19 | print(predict(s,a)) 20 | -------------------------------------------------------------------------------- /Tree/Sum-of-Left-Leaves.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sumOfLeftLeaves(self, root: TreeNode) -> int: 9 | result = 0 10 | if root: 11 | if root.left and not root.left.left and not root.left.right: 12 | result += root.left.val # if left node is leaf 13 | else: 14 | result += self.sumOfLeftLeaves(root.left) # otherwise recurse down to left 15 | result += self.sumOfLeftLeaves(root.right) # then to right side, because we have to check full tree 16 | return result 17 | -------------------------------------------------------------------------------- /Tree/SumOfLeftLeaves.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def __init__(self): 10 | self.leftsum = 0 11 | 12 | def isLeaf(self, root): 13 | return not root.left and not root.right 14 | 15 | def sumOfLeftLeaves(self, root: TreeNode) -> int: 16 | if root: 17 | if root.left and self.isLeaf(root.left): 18 | self.leftsum += root.left.val 19 | self.sumOfLeftLeaves(root.left) 20 | self.sumOfLeftLeaves(root.right) 21 | return self.leftsum 22 | 23 | -------------------------------------------------------------------------------- /Tree/validate-bst.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isValidBST(self, root: TreeNode) -> bool: 9 | return self.isValid(root, None, None) 10 | def isValid(self, node: TreeNode, maxbound: int, minbound: int) -> bool: 11 | # print(str(node), maxbound, minbound) 12 | if not node: 13 | return True 14 | if maxbound != None and node.val >= maxbound: 15 | return False 16 | if minbound != None and node.val <= minbound: 17 | return False 18 | return self.isValid(node.left, node.val, minbound) and self.isValid(node.right, maxbound, node.val) 19 | -------------------------------------------------------------------------------- /TwoPointerSW/3Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | n = len(nums) 5 | if n < 3: 6 | return [] 7 | nums.sort() 8 | # print(nums) 9 | for i in range(n): 10 | if i > 0 and nums[i] == nums[i-1]: 11 | continue 12 | if nums[i] > 0: 13 | break 14 | j, k = i+1, n-1 15 | while j < k: 16 | # print(i,j,k) 17 | triplet = nums[i] + nums[j] + nums[k] 18 | if triplet > 0: 19 | k -= 1 20 | elif triplet < 0: 21 | j += 1 22 | else: 23 | # print("Got") 24 | res.append([nums[i], nums[j], nums[k]]) 25 | j += 1 26 | while j < k and nums[j] == nums[j-1]: 27 | j += 1 28 | while j < k and nums[k] == nums[k-1]: 29 | k -= 1 30 | return res 31 | -------------------------------------------------------------------------------- /TwoPointerSW/BeautifulArrangement2.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/beautiful-arrangement-ii/ 2 | class Solution: 3 | def constructArray(self, n: int, k: int) -> List[int]: 4 | nums = [i+1 for i in range(n)] 5 | l, r, i = 1, n, 0 6 | res = [0] * n 7 | while i < k - 1: 8 | res[i] = l 9 | i += 1 10 | l += 1 11 | res[i] = r 12 | i += 1 13 | r -= 1 14 | while i < n: 15 | if k % 2: 16 | res[i] = l 17 | l += 1 18 | else: 19 | res[i] = r 20 | r -= 1 21 | i += 1 22 | 23 | return res 24 | -------------------------------------------------------------------------------- /TwoPointerSW/CF1278A_ShuffleHashing.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | for _ in range(int(input())): 3 | p = str(input()) 4 | h = str(input()) 5 | if (len(p) > len(h)): 6 | print("NO") 7 | continue 8 | if (len(p) == len(h)): 9 | if sorted(p)==sorted(h): 10 | print("YES") 11 | else: 12 | print("NO") 13 | continue 14 | 15 | window = Counter(p) 16 | s = len(p) 17 | flag = 0 18 | curr = Counter(h[:s]) # first window 19 | i = 0 20 | while i+s <= len(h): 21 | #print("Current Window: ", h[i:i+s], curr) 22 | 23 | if i>0: 24 | curr[h[i-1]] -= 1 # remove the prev char 25 | curr[h[i+s-1]] += 1 # add new next char 26 | if curr[h[i-1]] == 0: 27 | del curr[h[i-1]] # remove the key 28 | 29 | 30 | 31 | if curr == window: 32 | print("YES") 33 | flag = 1 34 | break 35 | i += 1 36 | if flag == 0: 37 | print("NO") 38 | 39 | -------------------------------------------------------------------------------- /TwoPointerSW/HIndex2.py: -------------------------------------------------------------------------------- 1 | #LCM275 2 | class Solution: 3 | def hIndex(self, citations: List[int]) -> int: 4 | 5 | def binSearch(low: int, high: int) -> int: 6 | mid = (low + high) // 2 7 | #print(low,mid,high) 8 | if mid < 1 or mid > len(citations) or low>high: 9 | return -1 10 | if citations[-mid] >= mid: 11 | return max(mid, binSearch(mid+1, high)) 12 | else: 13 | return binSearch(low, mid-1) 14 | 15 | if len(citations) == 0: 16 | return 0 17 | 18 | if len(citations) == 1: 19 | return 1 if citations[-1] >= 1 else 0 20 | 21 | return max(0, binSearch(1, len(citations)+1)) 22 | 23 | -------------------------------------------------------------------------------- /TwoPointerSW/Intersection.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::intersect(const vector &A, const vector &B) { 2 | int p1=0,p2=0; 3 | vector ans; 4 | while (p1 List[int]: # TIme Complexity = O(n) Space Complexity = O(n) 7 | l = len(A) 8 | ans = [None]*l 9 | i = 0 10 | j = l-1 11 | for k in range(l-1,-1,-1): 12 | if abs(A[i]) > abs(A[j]): 13 | ans[k]=A[i]**2 14 | i+=1 15 | else: 16 | ans[k]=A[j]**2 17 | j-=1 18 | return ans 19 | 20 | 21 | -------------------------------------------------------------------------------- /TwoPointerSW/SubarrayProductLessThanK.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-product-less-than-k/ 2 | // import java.util.*; 3 | class Solution { 4 | public int numSubarrayProductLessThanK(int[] nums, int k) { 5 | int count = 0; 6 | int left = 0; 7 | int curr_prod = 1; 8 | if (k<=1) 9 | return 0; 10 | for (int i=0; i= k) 15 | { 16 | curr_prod /= nums[left]; 17 | left += 1; 18 | } 19 | count += i - left + 1; 20 | } 21 | return count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /TwoPointerSW/SubarraySumK.cpp: -------------------------------------------------------------------------------- 1 | // array has to be sorted to apply this method 2 | vector Solution::solve(vector &A, int B) { 3 | int l=0, r=0, sum=A[0]; 4 | while (l B){ 13 | sum -= A[l]; 14 | l++; 15 | } 16 | } 17 | return {-1}; 18 | } 19 | 20 | -------------------------------------------------------------------------------- /TwoPointerSW/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | left, right = 0, len(height)-1 4 | maxarea = 0 5 | while left < right: 6 | maxarea = max(maxarea, (right-left) * min(height[left], height[right])) 7 | if height[left] <= height[right]: 8 | left += 1 9 | else: 10 | right -= 1 11 | return maxarea 12 | -------------------------------------------------------------------------------- /TwoPointerSW/one-edit-distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isOneEditDistance(self, s: str, t: str) -> bool: 3 | s += '#' 4 | t += '#' 5 | 6 | m, n = len(s), len(t) 7 | 8 | if abs(m-n) > 1: 9 | return False 10 | 11 | i, j, diff = 0, 0, 0 12 | while i < m and j < n: 13 | if s[i] == t[j]: 14 | i += 1 15 | j += 1 16 | else: 17 | diff += 1 18 | if diff > 1: 19 | return False 20 | if m == n: 21 | i += 1 22 | j += 1 23 | if m > n: 24 | i += 1 25 | if n > m: 26 | j += 1 27 | 28 | return diff == 1 29 | --------------------------------------------------------------------------------