├── CS591 ├── Graph │ ├── tmp.c │ └── dfs.c ├── DivideConquer │ ├── BinarySearch.c │ ├── Quicksort.c │ └── MaxMinNumber.c └── DynamicProgramming │ └── FloydWarshall.c ├── .gitignore ├── Contests ├── Chef_JAN19B │ ├── inp.txt │ ├── FANCY.py │ ├── DPAIRS_2.py │ ├── MGAME_intuition.txt │ ├── HP18.py │ ├── DPAIRS.py │ └── MGAME1.py ├── Chef_MARCH19B │ ├── SUBPRNJL │ │ ├── input2.txt │ │ ├── a.out │ │ ├── SUBPRNJL_1.py │ │ ├── SUBPRNJL_Brute.py │ │ ├── prefix.py │ │ └── SUBPRNJL_0.py │ ├── a.out │ ├── input.txt │ ├── CHNUM.py │ ├── JAIN │ │ └── JAIN_0.py │ ├── CHONQ.py.save │ ├── CHONQ_Brute.py │ ├── CHNUM_AB.cpp │ └── CHDIGER.py ├── Chef_SEP18 │ ├── inp.txt │ └── a.out ├── Chef_OCT18B │ ├── inp.txt │ ├── BITOBYT.py │ ├── CHSERVE.cpp │ ├── HMAPPY.py │ └── HMAPPY2.py ├── Chef_MARCH20B │ ├── input.txt │ ├── CHPINTU.py │ ├── ENGXOR.cpp │ └── ENGXOR.py ├── Chef_NOV1BB │ ├── HMAPPY1 │ │ ├── inp.txt │ │ ├── tcGen_hmappy1.py │ │ ├── TC_HMAPPY1.txt │ │ └── HMAPPY1.py │ ├── CHFTIRED.py │ ├── CHHAPPY.py │ ├── PRDRG.py │ └── GMEDIAN1.py ├── bleedcode │ ├── input.txt │ ├── a.out │ ├── deter.py │ ├── second.py │ ├── leven.py │ ├── date.py │ └── bloody.py ├── Chef_AUG18 │ ├── a.out │ ├── inputProbSort.txt │ ├── inputSpellbob.txt │ ├── Modular GCD │ │ ├── Final_ModularGCD.py │ │ ├── GCDMOD2.py │ │ └── Trash.txt │ └── SHKNUM.py ├── Chef_COCE2018 │ ├── inp.txt │ ├── QUERARR.py │ └── LUCAS1.py ├── Chef_KJSCE │ ├── inp.txt │ ├── BAL.py │ ├── BOOK.py │ └── BOND.py ├── Chef_CodeIncognito │ ├── INVENTON.py │ ├── PRISTG_.py │ ├── PRISTG.py │ └── INVENTO.cpp ├── Chef_ELE32018 │ ├── inp.txt │ └── JACKJILL.py ├── Chef_COW2018 │ ├── TRO1.py │ ├── DSI2.py │ ├── BDMS.py │ └── TA1.py ├── 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 ├── CodingNinjas_CareerCamp │ ├── GetProduct.cpp │ └── Pattern.py ├── Snackdown19_Qualifier │ ├── QUALPREL.py │ ├── SPREAD2.py │ ├── QABC.cpp │ └── CHEFPRMS.py ├── CodeJam19 │ ├── Qualifiers │ │ └── input.txt │ └── Round1A │ │ ├── alienrhyme │ │ └── golfers ├── Chef_LTIME64 │ └── JDELAY.cpp ├── Chef_LTIME70B │ ├── TSTROBOTS.py │ └── POGO.py ├── Chef_LTIME71B │ ├── ATTND.py │ ├── FASTFOOD.py │ ├── MINARRS.py │ └── MINARRS2.py ├── Chef_LTIME78B │ ├── DEADEND.py │ ├── PIBRO.py │ └── CMPRESS.py ├── CF1343 │ ├── 1343B.py │ └── 1343A.py ├── Facebook Hacker Cup 2018 │ └── Qualification │ │ └── Tourist │ │ └── input.txt ├── Chef_APRIL20B │ └── STRNO.py ├── Chef_COOK98 │ ├── ATM2.cpp │ ├── MAKPERM.cpp │ └── OETW2.cpp └── Snackdown19_Online1A │ ├── AVGMAT_Partial.py │ ├── CHEFADD_Partial.py │ ├── CARDMGK.py │ └── TYPING.py ├── Greedy ├── inp.txt ├── Kruskal_MSTAlgorithm │ ├── input1.txt │ ├── input2.txt │ ├── output1.txt │ └── output2.txt ├── MinXorPair_Greedy.py ├── JumpGame2.py ├── TACHSTCK.py ├── Count-n-Say.py ├── JumpGame.java ├── CIELRCPT.cpp ├── MergeIntervals.py ├── FASHION_SPOJ.cpp ├── MinDominoRotationForEqualRow.py ├── couples-holding-hands.py ├── GlobalAndLocalInversions.py ├── LEMUSIC.py ├── BUSYMAN.cpp ├── MeetingRooms2.py ├── Maximum-Swap.py └── MyCalendar3_UsingTreeMap.java ├── SegmentTrees ├── inp.txt ├── ginp.txt └── lazyinp.txt ├── Hashing ├── Map.class ├── implementation.cpp ├── MapNode.java ├── NumberOfEquivalentDominoPairs.py ├── OurMapUse.java ├── LongestSubarraySumK.py ├── PairSum_Zero.py ├── Anagrams.py ├── LargestContinuousSubsequenceZeroSum.py ├── RomanNumberToInteger ├── ZeroSumSubarray.py ├── LongestConsecutiveSequence.py ├── Circular_Loop_Array.py ├── ImageOverlap.py ├── SubarraySumEqualsK.java ├── DesignHashSet.py ├── subarraySumK.py └── ValidSudoku.py ├── Backtracking ├── a.out ├── generate-parentheses.py ├── LetterCombinationsOfAPhoneNumber.py └── letter-combinations-of-a-phone-number.py ├── Graphs ├── Dijkstra │ ├── a.out │ ├── graphinput2.txt │ └── graphinput1.txt ├── in_connectivity.txt ├── FloydWarshall │ ├── ginp.txt │ └── FloydWarshall_IB.java ├── NumberOfIslands_DFS.py ├── Backtracking │ └── GeneralizedAbbreviations.py └── NumberOfClosedIslands.py ├── BitManipulation ├── PowerOfTwo.py ├── PowerOfFour.py ├── PowerOfThree.py └── number-of-steps-to-reduce-a-number-to-zero.py ├── AdHoc ├── WILLITST.py ├── AE00.py ├── ADDREV.py ├── FlippingAnImage.py ├── CANDY3.py ├── UniquePaths.py ├── corporate-flight-bookings.py ├── ADDREV_IITROPAR.c ├── ArrayDuplicates.py ├── RearrangeArray.py ├── ACPC10A.cpp ├── LargestNumberAtleastTwice.py ├── EIGHTS.cpp ├── nthNonFibonacci.cpp ├── CF106A.py ├── MaxChunksToMakeSorted2.py ├── ConvertToHex.py ├── FlightRangeBookings.py ├── UniquePaths.cpp ├── MissingNumber.cpp ├── prettyprint.py ├── Panda_And_Chain_Reaction_HackerEarth.cpp ├── MaxDistance.py ├── TriangularSeries.py ├── CATSDOGS.cpp ├── ArrayRotation.cpp ├── first-missing-positive.py ├── SAMER08F.cpp ├── MAJOR.py ├── ContainerWithMostWater.py ├── CHBLLNS.cpp ├── FirstMissingInteger.py ├── CF100C.py ├── NextGreaterElement3.py ├── HackerRankLogo.py ├── CO92JUDG.cpp └── ShortestUnsortedContinuousSubarray.py ├── Dynamic Programming ├── DPBook │ ├── Fibonacci_DP.py │ ├── MaxSumSubarray.py │ ├── Fibonacci_Memoized.py │ └── PP │ │ └── 1_EditDistance.java ├── MaximumSubarray.java ├── Coin-Change.py ├── tetrahedron166E.cpp ├── MinSumPathInMatrix.py ├── IEMCO5B.py ├── SumOfSquares.py ├── HouseRobber.java ├── LongestIncreasingPathInMatrix.py ├── maximumSumNonAdjacent.py ├── Min_Number_Of_Squares.java ├── StaircaseClimbCTCI.py ├── CF455A.py ├── MinStepsToReachEnd.java ├── UniquePathsInAGrid.py ├── PPERM.py ├── bike-trip.py ├── ACODE.py ├── Wildcard_Matching.py ├── Finding_Nth_Fibonacci_Number.cpp ├── PPERM.cpp ├── LongestPalindromicSubsequence.java ├── LCS.py ├── HouseRobber2.py ├── knapsack_0_1.py ├── GeeksSum.py ├── MaxSumWithoutAdjacentElements.java └── EditDistance.py ├── Misc ├── DoubtSolve.c ├── BinaryTree_ArrayRep.c ├── LRUCache_Optimized.java └── LargestPalindromeProduct.py ├── NextNumber.py ├── Stack_Queue ├── DailyTemperatures.py ├── LongestValidParenthesis.py ├── ValidParentheses.py ├── LongestValidParenthesis.java ├── TrappingRainWater.py ├── NearestSmallestElement.py ├── SlidingWindowMin.py ├── MinStack.py ├── KthCharInDoubleDecryptedString.cpp ├── NextGreaterElement1.java └── SlidingWindowMax_DequeBased.py ├── Searching_Sorting ├── WaveArray.py ├── WGHTNUM.py ├── CREP.py ├── GameShopping1009A.py ├── SortColors.py ├── BinarySearch │ ├── FirstBadVersion.java │ ├── ImplementPowerFunction.cpp │ ├── QUERARR.py │ └── ShiftedSortedArray.py ├── CutTheSticks.py ├── MinimumTernaryString1009B.py ├── ORDTEAMS_2.py ├── SortArrayOf012.cpp ├── IEMCO5C.py ├── MinSwapSegregate.py └── LexicographicalSort.py ├── TwoPointerSW ├── Intersection.cpp ├── container-with-most-water.py ├── SubarraySumK.cpp ├── BeautifulArrangement2.py ├── SubarrayProductLessThanK.java ├── Squares_of_a_Sorted_Array.py ├── HIndex2.py ├── one-edit-distance.py ├── CF1278A_ShuffleHashing.py └── 3Sum.py ├── Tree ├── InvertBinaryTree.py ├── MergeTwoBinaryTrees.py ├── PrefixWordPrediction.py ├── SumOfLeftLeaves.py ├── Sum-of-Left-Leaves.py ├── validate-bst.py ├── BTMaxPathSum.py ├── InorderSuccessorBST.py └── DeepestLeavesSum.py ├── Number_Theory ├── HappyNumber.py ├── HelpDory.py ├── Primality Test │ ├── GCDEX.py │ └── Roy_and_Shopping.py ├── EulerTotientFunc.py └── TotalHammingDistance.py ├── CF1114A.py ├── CONTRIBUTING.md ├── Heap ├── merge-k-sorted-lists.py ├── AthLargestElement.py ├── merge_k_Sorted_lists.py └── SkylineProblem.py └── LinkedList ├── ReversingList.py ├── swap-nodes-in-pairs.py ├── RemoveZeroSumConsecutiveNodesFromLinkedList,py ├── OddEvenLinkedList.py └── SwapNodesInPair.py /CS591/Graph/tmp.c: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /LiveContest/* 2 | /Hiring/* 3 | .idea/ 4 | -------------------------------------------------------------------------------- /Contests/Chef_JAN19B/inp.txt: -------------------------------------------------------------------------------- 1 | 3 2 2 | 10 1 100 3 | 4 3 4 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/input2.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 3 3 3 | 1 2 3 4 | -------------------------------------------------------------------------------- /Contests/Chef_SEP18/inp.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 3 2 3 | 1 2 3 4 | 2 2 5 | 1 3 6 | -------------------------------------------------------------------------------- /Contests/Chef_OCT18B/inp.txt: -------------------------------------------------------------------------------- 1 | 5 3 2 | 1 2 3 8 12 3 | 1 2 3 4 5 4 | 5 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH20B/input.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 6 2 3 | 4 2 15 9 8 8 4 | 3 5 | 16 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_NOV1BB/HMAPPY1/inp.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 9 7 10 3 | 1 1 1 0 1 1 1 1 0 4 | ?!?!?!? 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Hashing/Map.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Hashing/Map.class -------------------------------------------------------------------------------- /Backtracking/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Backtracking/a.out -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Graphs/Dijkstra/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Graphs/Dijkstra/a.out -------------------------------------------------------------------------------- /Contests/Chef_AUG18/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Contests/Chef_AUG18/a.out -------------------------------------------------------------------------------- /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_SEP18/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Contests/Chef_SEP18/a.out -------------------------------------------------------------------------------- /Contests/bleedcode/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Contests/bleedcode/a.out -------------------------------------------------------------------------------- /Graphs/in_connectivity.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 5 3 | 1 6 4 | 6 2 5 | 2 3 6 | 4 5 7 | 7 5 8 | 3 9 | 6 5 10 | 1 3 11 | 1 7 12 | 13 | -------------------------------------------------------------------------------- /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_MARCH19B/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Contests/Chef_MARCH19B/a.out -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Hashing/implementation.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Hash is a unique data structure that supports insertion, deletion, search at constant time*/ 4 | 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH19B/SUBPRNJL/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/Contests/Chef_MARCH19B/SUBPRNJL/a.out -------------------------------------------------------------------------------- /Contests/Chef_KJSCE/inp.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 14 5 3 | 25 56 38 31 100 4 | 20 30 38 60 30 200 0 100 40 70 30 40 1 56 5 | 30 30 38 120 31 300 500 100 50 100 40 60 2 70 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_CodeIncognito/INVENTON.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/problems/INVENTO 2 | 3 | t=int(input()) 4 | for _ in range(t): 5 | n=int(input()) 6 | x=len(str(bin(n))) 7 | print(x-2) -------------------------------------------------------------------------------- /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") -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Graphs/FloydWarshall/ginp.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 1 2 3 | 1 4 | 1 4 5 | 1 6 | 1 5 7 | 5 8 | 2 1 9 | 9 10 | 2 3 11 | 3 12 | 2 4 13 | 2 14 | 3 4 15 | 4 16 | 4 3 17 | 2 18 | 4 5 19 | 3 20 | 5 1 21 | 3 22 | 0 0 23 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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_COW2018/TRO1.py: -------------------------------------------------------------------------------- 1 | t=int(input()) 2 | for _ in range(t): 3 | n=int(input()) 4 | if(n<60): 5 | print("NO") 6 | else: 7 | if(360/(180-n)==360//(180-n)): 8 | print("YES") 9 | else: 10 | print("NO") -------------------------------------------------------------------------------- /Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 5.49.12 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amitrajitbose/Competitive_Programming/HEAD/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/HEAD/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/HEAD/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/HEAD/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/HEAD/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/HEAD/Contests/HackerEarth_Amdocs_HackFest/Screenshot 2020-02-16 at 6.00.11 PM.png -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_NOV1BB/HMAPPY1/tcGen_hmappy1.py: -------------------------------------------------------------------------------- 1 | #TestCase Generator For HMAPPY1 2 | low = int(input()) 3 | high= int(input()) 4 | print(high-low) 5 | for i in range(low,high): 6 | print("10 7 10") 7 | print(*bin(i)[2:]) 8 | print("?!?!?!?") 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /Contests/Chef_KJSCE/BAL.py: -------------------------------------------------------------------------------- 1 | from math import gcd 2 | test=int(input()) 3 | for _ in range(test): 4 | x,y,n,m=[int(bla) for bla in input().strip().split()] 5 | lcm=(x*y)//gcd(x,y) 6 | if((lcm//x)<=n and (lcm//y)<=m): 7 | print("YES") 8 | else: 9 | print("NO") 10 | -------------------------------------------------------------------------------- /Misc/DoubtSolve.c: -------------------------------------------------------------------------------- 1 | #include 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /Contests/Chef_CodeIncognito/PRISTG_.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/INCC2018/problems/PRISTG/ 2 | 3 | a=str(input().strip()) 4 | b=str(input().strip()) 5 | c=0 6 | 7 | for i in range(0,len(a)): 8 | for j in range(i+1,len(a)+1): 9 | #print(a[i:j]) 10 | if(a[i:j] in b): 11 | c+=1 12 | print(c) 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /AdHoc/CANDY3.py: -------------------------------------------------------------------------------- 1 | #Problem: www.spoj.com/probleams/CANDY3/ 2 | test=int(input()) 3 | for _ in range(test): 4 | gapline=input() 5 | n=int(input()) 6 | candies=0 7 | for i in range(n): 8 | c=int(input()) 9 | candies+=c 10 | candies=candies%n 11 | if(candies==0): 12 | print("YES") 13 | else: 14 | print("NO") -------------------------------------------------------------------------------- /Contests/Snackdown19_Qualifier/QUALPREL.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | for _ in range(int(input())): 3 | n,k=map(int,input().split()) 4 | ar=list(map(int,input().split())) 5 | ar.sort() 6 | min=ar[n-k] 7 | x=bisect.bisect_left(ar,min) 8 | tmp=ar[x:] 9 | #print(ar,x,tmp) 10 | print(len(tmp)) 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /AdHoc/UniquePaths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, A: int, B: int) -> 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/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 | -------------------------------------------------------------------------------- /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_LTIME64/JDELAY.cpp: -------------------------------------------------------------------------------- 1 | #include 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< 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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME70B/TSTROBOTS.py: -------------------------------------------------------------------------------- 1 | for _ in range(int(input())): 2 | n,m = [int(x) for x in input().strip().split()] 3 | stk = [] 4 | visited = {m:True} 5 | uniq = 1 6 | steps = list(input()) 7 | curr = m 8 | for i in steps: 9 | if i=='L': 10 | curr-=1 11 | elif i=='R': 12 | curr+=1 13 | 14 | if curr not in visited: 15 | uniq+=1 16 | visited[curr]=True 17 | print(uniq) 18 | 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /AdHoc/RearrangeArray.py: -------------------------------------------------------------------------------- 1 | # IB rearrange-array 2 | 3 | class Solution: 4 | # @param A : list of integers 5 | # Modify the array A which is passed by reference. 6 | # You do not need to return anything in this case. 7 | def arrange(self, A): 8 | for i in range(len(A)): 9 | A[i] += (A[A[i]]%len(A))*len(A) 10 | for i in range(len(A)): 11 | A[i] //= len(A) 12 | 13 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME71B/ATTND.py: -------------------------------------------------------------------------------- 1 | for _ in range(int(input())): 2 | names = [] 3 | namedict = {} 4 | for i in range(int(input())): 5 | fn,sn = [str(x) for x in input().strip().split()] 6 | names.append((fn,sn)) 7 | if fn in namedict: 8 | namedict[fn] += 1 9 | else: 10 | namedict[fn] = 1 11 | for i in names: 12 | if namedict[i[0]]==1: 13 | print(i[0]) 14 | else: 15 | print(i[0],i[1]) 16 | 17 | -------------------------------------------------------------------------------- /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 Solution::intersect(const vector &A, const vector &B) { 2 | int p1=0,p2=0; 3 | vector ans; 4 | while (p1 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 | } -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /Dynamic Programming/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | // Kadane Algorithm 4 | int n = nums.length; 5 | int maxsum = Integer.MIN_VALUE; 6 | int local = 0; 7 | for(int i=0; i TreeNode: 9 | if root: 10 | root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) 11 | return root 12 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 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<=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 | -------------------------------------------------------------------------------- /Stack_Queue/LongestValidParenthesis.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestValidParentheses(self, s: str) -> 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Greedy/CIELRCPT.cpp: -------------------------------------------------------------------------------- 1 | // https://www.codechef.com/problems/CIELRCPT 2 | #include 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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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)< 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 | -------------------------------------------------------------------------------- /Contests/Chef_CodeIncognito/PRISTG.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def gen_all_substrings(s): 4 | lt = lambda pair: pair[0] < pair[1] 5 | index_pairs = filter(lt, permutations(range(len(s)+1), 2)) 6 | return (s[i:j] for i,j in index_pairs) 7 | 8 | def get_all_substrings(s): 9 | return list(gen_all_substrings(s)) 10 | 11 | a=str(input().strip()) 12 | b=str(input().strip()) 13 | asub=get_all_substrings(a) 14 | count=0 15 | for i in asub: 16 | if(i in b): 17 | count+=1 18 | print(count) 19 | -------------------------------------------------------------------------------- /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 < 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Snackdown19_Qualifier/SPREAD2.py: -------------------------------------------------------------------------------- 1 | #Author : @amitrajitbose 2 | t=int(input()) 3 | for _ in range(t): 4 | n=int(input()) 5 | arr=[int(x) for x in input().strip().split()] 6 | pref=[0 for x in range(n)] 7 | pref[0]=arr[0] 8 | day=0 9 | for i in range(1,n): 10 | pref[i]=pref[i-1]+arr[i] 11 | know=1 12 | dontknow=n-1 13 | sumk=pref[0] 14 | while(dontknow>0): 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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 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 | } -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME70B/POGO.py: -------------------------------------------------------------------------------- 1 | import sys 2 | for _ in range(int(input())): 3 | n,k = map(int, input().strip().split()) 4 | arr = list(map(int, input().strip().split())) 5 | maxsum = -1 * sys.maxsize 6 | allsum = [] 7 | for i in range(k): 8 | sub = arr[i::k] 9 | allsum.append([sub,sum(sub)]) 10 | maxsum = max(maxsum, allsum[-1][-1]) 11 | for i in range(k,n): 12 | sub = allsum.pop(0) 13 | rem = sub[0].pop(0) 14 | sub[1]=sub[1]-rem 15 | allsum.append(sub) 16 | maxsum = max(maxsum, allsum[-1][-1]) 17 | print(maxsum) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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= 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/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))) -------------------------------------------------------------------------------- /Searching_Sorting/SortColors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, arr: List[int]) -> 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 | -------------------------------------------------------------------------------- /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 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< 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 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_NOV1BB/PRDRG.py: -------------------------------------------------------------------------------- 1 | # Author: @amitrajitbose 2 | from fractions import Fraction as F 3 | inp=[int(x) for x in input().strip().split()] 4 | t=inp[0] 5 | table=[0,0.5,0.25] 6 | for i in range(3,30): 7 | if(i%2): 8 | x=table[i-1]+(1/(2**i)) 9 | else: 10 | x=table[i-2]+(1/(2**i)) 11 | table.append(x) 12 | #print(i,x) 13 | 14 | for _ in range(t-1): 15 | n=inp[_+1] 16 | x=F(table[n]).numerator 17 | y=F(table[n]).denominator 18 | #print(F(table[n])) 19 | print(x,end=" ") 20 | print(y,end=" ") 21 | n=inp[-1] 22 | x=F(table[n]).numerator 23 | y=F(table[n]).denominator 24 | #print(F(table[n])) 25 | print(x,end=" ") 26 | print(y) 27 | 28 | -------------------------------------------------------------------------------- /Dynamic Programming/HouseRobber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | int n = nums.length; 4 | if (n==0) 5 | return 0; 6 | if (n==1) 7 | return nums[0]; 8 | if (n==2) 9 | return Math.max(nums[0], nums[1]); 10 | else 11 | { 12 | int dp[] = new int[n]; 13 | dp[0] = nums[0]; 14 | dp[1] = Math.max(nums[0], nums[1]); 15 | for(int i=2; 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 | -------------------------------------------------------------------------------- /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/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/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)) -------------------------------------------------------------------------------- /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; i2): 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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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= 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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/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/ZeroSumSubarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return an integer 4 | def solve(self, A): 5 | # line of thought 6 | # we can create a prefix sum 7 | # if any element in the prefix sum repeats or it is zero at any point 8 | # then we can conclude that there is atleast one subarray with sum zero 9 | prefixsum = set([A[0]]) 10 | s = A[0] 11 | for i in range(1,len(A)): 12 | if s == 0: 13 | return 1 14 | s += A[i] 15 | if s == 0: 16 | return 1 17 | if s in prefixsum: 18 | return 1 19 | prefixsum.add(s) 20 | return 0 21 | 22 | -------------------------------------------------------------------------------- /AdHoc/SAMER08F.cpp: -------------------------------------------------------------------------------- 1 | // http://www.spoj.com/problems/SAMER08F/ 2 | 3 | /* 4 | This is the classical Feymann squares problem. 5 | Let N be the size of the length of one side of square 6 | 7 | For N=1, 8 | One 1x1 square = 1 9 | 10 | For N=2, 11 | One 2x2 + Four 1x1 = 1+4 = 5 12 | 13 | For N=3, 14 | One 3x3 + Four 2x2 + Nine 1x1 = 1+4+9 = 14 15 | 16 | For N=n 17 | One nxn + Four (n-1)x(n-1) + ..... (n^2) (1x1) 18 | 19 | So this follows n*(n+1)*(2n+1)/6 20 | */ 21 | 22 | #include 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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME71B/FASTFOOD.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.setrecursionlimit(110000) 3 | def reverse_precompute(arr): 4 | n = len(arr) 5 | temp = [0]*n 6 | temp[-1] = arr[-1] 7 | for i in range(n-2,-1,-1): 8 | temp[i] = temp[i+1] + arr[i] 9 | return temp 10 | 11 | def switch(a,b,ind,n,precomputed_b): 12 | if(ind==n-1): 13 | return max(a[-1],b[-1]) 14 | else: 15 | return max(precomputed_b[ind], a[ind]+switch(a,b,ind+1,n,precomputed_b)) 16 | 17 | for _ in range(int(input())): 18 | n = int(input()) 19 | a = [int(x) for x in input().strip().split()] 20 | b = [int(x) for x in input().strip().split()] 21 | precomputed_b = reverse_precompute(b) 22 | print(switch(a,b,0,n,precomputed_b)) 23 | -------------------------------------------------------------------------------- /Dynamic Programming/StaircaseClimbCTCI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Staircase Problem 3 | https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem 4 | ''' 5 | #!/bin/python3 6 | 7 | import math 8 | import os 9 | import random 10 | import re 11 | import sys 12 | 13 | # Complete the stepPerms function below. 14 | def stepPerms(cache,n): 15 | return cache[n] 16 | 17 | if __name__ == '__main__': 18 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 19 | cache=[1,1,2] 20 | for i in range(3,51): 21 | cache.append(cache[i-1]+cache[i-2]+cache[i-3]) 22 | s = int(input()) 23 | for s_itr in range(s): 24 | n = int(input()) 25 | res = stepPerms(cache,n) 26 | fptr.write(str(res) + '\n') 27 | 28 | fptr.close() 29 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Greedy/FASHION_SPOJ.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author : @amitrajitbose 3 | Problem : SPOJ FASHION 4 | */ 5 | 6 | #include 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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<A[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 | -------------------------------------------------------------------------------- /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 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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_CodeIncognito/INVENTO.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Author: Amitrajit Bose 4 | * Problem Link: 5 | * Approach: 6 | */ 7 | /* 8 | THIS CODE IS LOGICALLY CORRECT 9 | BUT WRONG ANSWER DUE TO LOG2() 10 | SO BE CAREFUL 11 | */ 12 | 13 | #include 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"< 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< 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 | -------------------------------------------------------------------------------- /Searching_Sorting/IEMCO5C.py: -------------------------------------------------------------------------------- 1 | #https://www.codechef.com/IEMCO5/problems/IEMCO5C/ 2 | 3 | from fractions import gcd 4 | n,q,k=[int(x) for x in input().strip().split(' ')] 5 | segments=[] 6 | starts=[] 7 | for _ in range(n): 8 | s,e=[int(x) for x in input().strip().split(' ')] 9 | starts.append(s) #start elements 10 | elementsinsegment=((e-s)//k)+1 11 | segments.append(elementsinsegment) 12 | 13 | avg=0 14 | for query in range(q): 15 | val=int(input()) 16 | for i in range(n): 17 | if(segments[i] 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Dynamic Programming/MinStepsToReachEnd.java: -------------------------------------------------------------------------------- 1 | package com.ib; 2 | 3 | public class MinStepsToReachEnd { 4 | public int solve(int[] A){ 5 | if(A.length <= 1){ 6 | return 0; 7 | } 8 | int ladder = A[0], stairs = A[0], jumps = 1; 9 | for(int level = 1; level < A.length; level++){ 10 | if(level == A.length-1){ 11 | return jumps; 12 | } 13 | if(level + A[level] > 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 | -------------------------------------------------------------------------------- /AdHoc/ContainerWithMostWater.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/container-with-most-water/ 2 | 3 | class Solution: 4 | def maxArea(self, height: List[int]) -> 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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/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)) -------------------------------------------------------------------------------- /Graphs/NumberOfIslands_DFS.py: -------------------------------------------------------------------------------- 1 | # LC 200 2 | class Solution: 3 | def numIslands(self, grid: List[List[str]]) -> 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 i0){ 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 | -------------------------------------------------------------------------------- /Contests/Chef_KJSCE/BOOK.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left as bs 2 | t=int(input()) 3 | for _ in range(t): 4 | n,m=[int(x) for x in input().strip().split()] 5 | arr=[int(x) for x in input().strip().split()] 6 | arr=sorted(arr) 7 | start=[int(x) for x in input().strip().split()] 8 | finish=[int(x) for x in input().strip().split()] 9 | q=len(start) 10 | for i in range(q): 11 | #print(start[i],"->",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]>>",uniqueval,",",repeatedval,",",k) 29 | print(uniqueval+(repeatedval*k)) 30 | 31 | -------------------------------------------------------------------------------- /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))) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_KJSCE/BOND.py: -------------------------------------------------------------------------------- 1 | var={ 2 | 0:'A', 3 | 1:'B', 4 | 2:'C', 5 | 3:'D', 6 | 4:'E', 7 | 5:'F', 8 | 6:'G' 9 | } 10 | 11 | path=[('A',1,0), 12 | ('B',3,2), 13 | ('C',4,3), 14 | ('D',2,5), 15 | ('E',6,6), 16 | ('F',0,4), 17 | ('G',6,1)] 18 | 19 | blackjump=[[0,1,3,2,4,6,5], 20 | [1,3,2,4,6,5,0], 21 | [2,4,6,5,0,1,3], 22 | [3,2,4,6,5,0,1], 23 | [4,6,5,0,1,3,2], 24 | [5,0,1,3,2,4,6], 25 | [6,5,0,1,3,2,4] 26 | ] 27 | 28 | t=int(input()) 29 | for _ in range(t): 30 | s=str(input()) 31 | steps=list(s) 32 | curr=0 #start at A 33 | for i in range(len(steps)): 34 | x=int(steps[i]) 35 | #follow black 36 | x=x%7 37 | curr=blackjump[curr][x] 38 | #print(var[curr]) 39 | #go one white 40 | curr=path[curr][2] 41 | #print(var[curr]) 42 | #print("--") 43 | print(var[curr]) 44 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Contests/Chef_LTIME71B/MINARRS.py: -------------------------------------------------------------------------------- 1 | for _ in range(int(input())): 2 | n = int(input()) 3 | arr = [int(x) for x in input().strip().split()] 4 | maxxlen = len(bin(max(arr)))-2 5 | binaries = [] 6 | for i in arr: 7 | bform = '{0:0'+str(maxxlen)+'b}' 8 | bform = bform.format(i) 9 | binaries.append(list(bform)) 10 | res = [] 11 | for i in range(maxxlen): 12 | zeroes, ones = 0, 0 13 | for j in range(n): 14 | if(binaries[j][i]=='0'): 15 | zeroes+=1 16 | else: 17 | ones+=1 18 | if(zeroes>=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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /Contests/Chef_COOK98/MAKPERM.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(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 | -------------------------------------------------------------------------------- /Greedy/BUSYMAN.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link: https://www.spoj.com/problems/BUSYMAN/ 2 | // UNWEIGHTED JOB SCHEDULING PROBLEM a.k.a ACTIVITY SELECTION PROBLEM 3 | 4 | #include 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< 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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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"< 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 | -------------------------------------------------------------------------------- /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 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 -------------------------------------------------------------------------------- /CS591/DivideConquer/BinarySearch.c: -------------------------------------------------------------------------------- 1 | #include 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 | -------------------------------------------------------------------------------- /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_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 | -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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] 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 | -------------------------------------------------------------------------------- /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 | 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 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 | -------------------------------------------------------------------------------- /Heap/AthLargestElement.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | # @param A : integer 4 | # @param B : list of integers 5 | # @return a list of integers 6 | def solve(self, A, B): 7 | hp = [] 8 | heapq.heapify(hp) 9 | res = [] 10 | for val in B: 11 | if len(hp)==A and val < hp[0]: 12 | pass # when incoming element is less than Ath min element (root of heap) 13 | elif len(hp) == A: 14 | heapq.heappushpop(hp, val) # when incoming element will get inside top A elements 15 | else: 16 | heapq.heappush(hp, val) # when heap is undersized, less than A, we fill everything 17 | 18 | if len(hp) < A: 19 | res.append(-1) 20 | else: 21 | res.append(hp[0]) 22 | return res 23 | 24 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /AdHoc/FirstMissingInteger.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dropNegatives(self, A): 3 | j = 0 4 | newlist = [] 5 | for i in range(len(A)): 6 | if A[i] > 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 | -------------------------------------------------------------------------------- /Hashing/subarraySumK.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array, find the total number of contiguous 3 | subarrays that sum up to k. 4 | ''' 5 | class Solution: 6 | def subarraySum(self, arr, k): 7 | """ 8 | :type nums: List[int] 9 | :type k: int 10 | :rtype: int 11 | """ 12 | cumulative_sum = 0 13 | counter = 0 14 | previously_seen = dict() 15 | for i in range(len(arr)): 16 | cumulative_sum += arr[i] 17 | if(cumulative_sum == k): 18 | counter += 1 19 | if(cumulative_sum-k in previously_seen): 20 | counter += previously_seen[cumulative_sum-k] 21 | if(cumulative_sum in previously_seen): 22 | previously_seen[cumulative_sum] += 1 23 | else: 24 | previously_seen[cumulative_sum] = 1 25 | return counter -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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') -------------------------------------------------------------------------------- /Backtracking/LetterCombinationsOfAPhoneNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> 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 | -------------------------------------------------------------------------------- /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") -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 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< 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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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;i 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=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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/NextGreaterElement3.py: -------------------------------------------------------------------------------- 1 | # LC 556 - M 2 | class Solution: 3 | def nextGreaterElement(self, n: int) -> 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 | -------------------------------------------------------------------------------- /Contests/Snackdown19_Online1A/TYPING.py: -------------------------------------------------------------------------------- 1 | def gettime(x): 2 | ans=2 3 | for i in range(1,len(x)): 4 | if x[i]=='j' or x[i]=='k': 5 | if x[i-1]=='d' or x[i-1]=='f': 6 | ans+=2 7 | else: 8 | ans+=4 9 | else: 10 | if x[i-1]=='j' or x[i-1]=='k': 11 | ans+=2 12 | else: 13 | ans+=4 14 | return ans 15 | for _ in range(int(input())): 16 | ar=[] 17 | count=[] 18 | n=int(input()) 19 | for i in range(n): 20 | x=input() 21 | if x in ar: 22 | count[ar.index(x)]+=1 23 | else: 24 | ar.append(x) 25 | count.append(1) 26 | #print(ar) 27 | #print(count) 28 | total=0 29 | for i in range(len(ar)): 30 | ans=gettime(ar[i]) 31 | #print(ans) 32 | c=((count[i]-1)/2)+1 33 | total+=ans*c 34 | print(int(total)) 35 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 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 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 | -------------------------------------------------------------------------------- /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("------------") -------------------------------------------------------------------------------- /Graphs/NumberOfClosedIslands.py: -------------------------------------------------------------------------------- 1 | # LC 1254 2 | # TC: O(mxn) 3 | 4 | class Solution: 5 | def closedIsland(self, grid: List[List[int]]) -> 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 st = new ArrayDeque<>(); //stack 7 | Map map = new HashMap<>(); //solution set 8 | st.push(0); // first index 9 | 10 | for (int i=1; i 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; i 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Dynamic Programming/HouseRobber2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def util(self, hval): 3 | n = len(hval) 4 | if n == 0: 5 | return 0 6 | if n == 1: 7 | return hval[0] 8 | if n == 2: 9 | return max(hval[0], hval[1]) 10 | 11 | # dp[i] represent the maximum value stolen so 12 | # for after reaching house i. 13 | dp = [0]*n 14 | 15 | # Initialize the dp[0] and dp[1] 16 | dp[0] = hval[0] 17 | dp[1] = max(hval[0], hval[1]) 18 | 19 | # Fill remaining positions 20 | for i in range(2, n): 21 | dp[i] = max(hval[i]+dp[i-2], dp[i-1]) 22 | 23 | return dp[-1] 24 | 25 | def rob(self, nums: List[int]) -> 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 | -------------------------------------------------------------------------------- /Contests/Chef_MARCH20B/ENGXOR.py: -------------------------------------------------------------------------------- 1 | def oddSetBits(n): 2 | # returns 1 if n has odd number of set bits, else 0 if n has even number of set bits 3 | if n == 0: 4 | return 0 5 | if n%2 == 0: 6 | return oddSetBits(n//2) 7 | if n%2 == 1: 8 | return 1 - oddSetBits(n//2) 9 | 10 | def checkOddSetBits(n): 11 | # this is O(set bits) time 12 | cnt = 0 13 | while n>0: 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 | -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /CS591/DynamicProgramming/FloydWarshall.c: -------------------------------------------------------------------------------- 1 | #include 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 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/Snackdown19_Qualifier/CHEFPRMS.py: -------------------------------------------------------------------------------- 1 | import math 2 | def square(n): 3 | tmp=round(math.sqrt(n)) 4 | if tmp*tmp==n: 5 | return False 6 | else: 7 | return True 8 | def semprime(n): 9 | ch = 0 10 | if square(n)==False: 11 | return False 12 | for i in range(2, int(math.sqrt(n)) + 1): 13 | while n%i==0: 14 | n//=i 15 | ch+=1 16 | if ch >= 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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Hashing/ValidSudoku.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of strings 3 | # @return an integer 4 | def isValidSudoku(self, A): 5 | # check repetitions in rows 6 | for row in A: 7 | row = list(row.replace('.', '')) # removing dots 8 | if len(row) != len(set(row)): 9 | return 0 # false 10 | 11 | # check repetitions in column 12 | for i in range(9): 13 | col = [A[j][i] for j in range(9) if A[j][i] != '.'] 14 | if len(col) != len(set(col)): 15 | return 0 # false 16 | 17 | # check boxes each of size 3*3 18 | for i in range(0,9,3): 19 | for j in range(0,9,3): 20 | box = set([]) 21 | for p in range(i, i+3): 22 | for q in range(j, j+3): 23 | if A[p][q] != '.' and A[p][q] not in box: 24 | box.add(A[p][q]) 25 | elif A[p][q] != '.' and A[p][q] in box: 26 | return 0 # false 27 | return 1 # true 28 | 29 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Stack_Queue/SlidingWindowMax_DequeBased.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | # @param A : tuple of integers 4 | # @param B : integer 5 | # @return a list of integers 6 | def slidingMaximum(self, nums, k): 7 | out=[] 8 | n=len(nums) 9 | if(n==0): 10 | return out 11 | q=[] #create the queue we need 12 | #initial addition to queue 13 | for i in range(k): 14 | while(len(q) and nums[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 | -------------------------------------------------------------------------------- /Dynamic Programming/GeeksSum.py: -------------------------------------------------------------------------------- 1 | print ("Hello") 2 | n=input("Press") 3 | print (n) 4 | '''# https://practice.geeksforgeeks.org/problems/geeks-sum/0 5 | #Fibo Seq Generator 6 | def fibonacci(n): 7 | Fib=[] 8 | a = 0 9 | b = 1 10 | if n < 0: 11 | print("Incorrect input") 12 | elif n == 0: 13 | Fib.append(0) 14 | return Fib 15 | elif n == 1: 16 | Fib.append(0) 17 | Fib.append(1) 18 | return Fib 19 | else: 20 | Fib.append(0) 21 | Fib.append(1) 22 | for i in range(2,n): 23 | c = a + b 24 | Fib.append(c) 25 | a = b 26 | b = c 27 | return Fib 28 | 29 | primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] 30 | sum=0 31 | 32 | t=int(input()) 33 | for _ in range(t): 34 | n=int(input()) 35 | fiboarray=fibonacci(n) 36 | l=len(fiboarray) 37 | s=0 38 | for i in range(l): 39 | if(i in primes): 40 | s+=fiboarray[i] 41 | print(*fiboarray) 42 | print(s)''' -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Searching_Sorting/BinarySearch/ShiftedSortedArray.py: -------------------------------------------------------------------------------- 1 | # LCM 33 2 | 3 | class Solution: 4 | def search(self, nums: List[int], target: int) -> 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Dynamic Programming/MaxSumWithoutAdjacentElements.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int adjacent(int[][] A) { 3 | ArrayList 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 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | ''' -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Dynamic Programming/EditDistance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. 3 | 4 | Insert 5 | Remove 6 | Replace 7 | All of the above operations are of equal cost. 8 | 9 | Source: Edit Distance | GFG 10 | Explanation: https://youtu.be/Thv3TfsZVpw 11 | ''' 12 | #import pprint #pretty printer to print the table in line 27 13 | def editDistance(str1,str2): 14 | m=len(str1) 15 | n=len(str2) 16 | table=[[0 for x in range(n+1)] for x in range(m+1)] 17 | for i in range(m+1): 18 | for j in range(n+1): 19 | if(i==0): 20 | table[i][j]=j 21 | elif(j==0): 22 | table[i][j]=i 23 | elif(str1[i-1]==str2[j-1]): 24 | table[i][j]=table[i-1][j-1] #diagonal value + 1, i.e replacing 25 | else: 26 | table[i][j]=1+min(table[i-1][j-1],table[i-1][j],table[i][j-1]) #replace,remove,insert 27 | #pprint.pprint(table) 28 | return table[m][n] 29 | 30 | str1=str(input().strip()) 31 | str2=str(input().strip()) 32 | print(editDistance(str1,str2),"OPERATIONS REQUIRED") --------------------------------------------------------------------------------