├── .gitignore ├── uva online judge ├── 10469 - To Carry or not to Carry.c ├── 10071 Back to High School Physics.cpp ├── 591-Box of Bricks.cpp ├── 11388 - GCD LCM.cpp ├── 10055-hashmat.c ├── 458 - The Decoder.c ├── 11150 - Cola.cpp ├── 374 - Big Mod.cpp ├── 12372 - Packing for Holiday.c ├── 11877 - The Coco-Cola Store.cpp ├── 10783-odd sum.cpp ├── 10079 - Pizza Cutting.java ├── 10127 - Ones.cpp ├── 10432-Polygon Inside A Circle.cpp ├── 11172 - Relational Operator.cpp ├── 11547 - Automatic Answer.cpp ├── 11689 - Soda Surpler.cpp ├── 11805 - Bafana Bafana.cpp ├── 594 One Little, Two Little, Three Little Endians.c ├── 10346 - Peter's Smokes.cpp ├── 10784- Diagonal.cpp ├── 10551 - Basic Remains.java ├── 424-Integer Inquiry.java ├── 10106 - Product JAVA.java ├── 579 - ClockHands.cpp ├── 10696-f91.cpp ├── 11417 GCD.cpp ├── 11854 - Egypt.cpp ├── 10334 - Ray Through Glasses JAVA.java ├── 11462-Age Sort.cpp ├── 11875 - Brick Game.cpp ├── 10940 - Throwing cards away II.cpp ├── 12279-Emoogle Balance.cpp ├── 10302 - Summation of Polynomials JAVA.java ├── 11479-Is this the easiest problem.c ├── 674 - Coin Change.cpp ├── 10451 - Ancient Village Sports.cpp ├── 10931-party.cpp ├── 500-factorial.java ├── 11879 - Multiple of 17.java ├── 10929 - You can say 11.cpp ├── 11332 - Summing Digits.java ├── 10370-Above Average.cpp ├── 100-The 3n+1 problem.cpp ├── 575-Skew Binary.cpp ├── 10107 - What is the Median.cpp ├── 11723 - Numbering Roads.cpp ├── 494-Kindergarten Counting Game.cpp ├── 10991 - Region.cpp ├── 11900 - Boiled Eggs.cpp ├── 136 - Ugly Numbers.cpp ├── 484 - The Department of Redundancy Department.cpp ├── 694 - The Collatz Sequence.java ├── 10473 - Simple Base Conversion.java ├── 10082 - WERTYU.java ├── 10327-Flip sort.cpp ├── 10298 - Power Strings.cpp └── 11137 - Ingenuous Cubrency.cpp ├── leetcode ├── _28_ImplementStrStr.java ├── _35_SearchInsertionPosition.java ├── _125_Palindrome.java ├── _2063_VowelsOfAllSubstrings.py ├── _537_ComplexNumberMultiplication.py ├── _1344_AngleBetweenHandsOfAClock.py ├── 2214. Minimum Health to Beat Game.py ├── _973_KClosestPointsToOrigin.py ├── _658_FindKClosestElements.py ├── 462. Minimum Moves to Equal Array Elements II.py ├── _126_DestroyingAsteroids.py ├── _1010_PairsOfSongsTotalDivisibleBy60.py ├── _190_ReverseBits.java ├── _901_OnlineStockSpan.py ├── 1846. Maximum Element After Decreasing and Rearranging.py ├── _1877_MinimizeMaximumPairSumInArray.py ├── _222_CountCompleteTreeNodes.java ├── _521_LongesUncommonSubsequenceI.java ├── _392_IsSubSequence.java ├── _509_FibonacciNumber.java ├── _921_MinimumAddToMakeParenthesesValid.py ├── _1823_FindTheWinnerOfTheCircularGame.py ├── 2221. Find Triangular Sum of an Array.py ├── _1963_MinimumNumberOfSwapsToMakeTheStringBalanced.py ├── 360. Sort Transformed Array.py ├── _528_RandomPickWithWeight.py ├── _56_MergeIntervals.py ├── _70_ClimbingStairs.java ├── _946_ValidateStackSequences.py ├── 172. Factorial Trailing Zeroes.py ├── _1218_LongestArithmeticSubsequenceOfGivenDifference.py ├── _1985_FindtheKthLargestIntegerInTheheArray.py ├── _451_SortCharactersByFrequency.py ├── _1_TwoSum.java ├── _53_MaximumSubArray.java ├── 390. Elimination Game.py ├── _1400_ConstructKPalindrome Strings.py ├── _1248_CountNumberOfNiceSubarrays.py ├── _2083_SubstringsThatBeginAndEndWithTheSameLetter.py ├── 1553. Minimum Number of Days to Eat N Oranges.py ├── 930. Binary Subarrays With Sum.py ├── _226_InvertBinaryTree.java ├── _1903_LargestOddNumberInString.java ├── _1953_MaximumNumberOfWeeksForWhichYouCanWork.py ├── _739_DailyTemperatures.py ├── 1338. Reduce Array Size to The Half.py ├── 1167. Minimum Cost to Connect Sticks.py ├── 325. Maximum Size Subarray Sum Equals k.py ├── _2186_MinimumNumberOfStepsToMakeAnagramII.py ├── _386_LexicographicalNumbers.py ├── _1673_FindTheMostCompetitiveSubsequence.py ├── _80_RemoveDuplicatesFromSortedArrayII.py ├── 370. Range Addition.py ├── 763. Partition Labels.py ├── _1347_MinimumNumberOfStepsToMakeAnagram.py ├── _791_CustomSortString.py ├── 560. Subarray Sum Equals K.py ├── _1366_RankTeamsByVotes.py ├── _1554_StringsDifferByOneCharacter.py ├── _2091_RemovingMinimumAndMaximumFromArray.py ├── 1762. Buildings With an Ocean View.py ├── 311. Sparse Matrix Multiplication.py ├── 1288. Remove Covered Intervals.py ├── Maximum Depth of Binary Tree.cpp ├── _1423_MaximumPointsYouCanObtainFromCards.py ├── _452_MinimumNumberOfArrowsToBurstBalloons.py ├── 523. Continuous Subarray Sum.py ├── 769. Max Chunks To Make Sorted.py ├── _2110_NumberOfSmoothDescentPeriodsOfAStock.py ├── _253_MeetingRoomsII.py ├── _398_RandomPickIndex.py ├── 1014. Best Sightseeing Pair.py ├── 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.py ├── _1781_SumOfBeautyOfAllSubstrings.py ├── _647_PalindromicSubstrings.py ├── 2268. Minimum Number of Keypresses.py ├── 503. Next Greater Element II.py ├── _1657_DetermineIfTwoStringsAreClose.py ├── _316_RemoveDuplicateLetters.py ├── _2178_MaximumSplitOfPositiveEvenIntegers.py ├── _435_NonOverlappingIntervals.py ├── _121_BestTimeToBuyAndSellStock.java ├── 525. Contiguous Array.py ├── _1492_TheKthFactorOfN.java ├── _954_ArrayOfDoubledPairs.py ├── 2090. K Radius Subarray Averages.py ├── 611. Valid Triangle Number.py ├── _1817_FindingTheUsersActiveMinutes.py ├── _853_CarFleet.py ├── 419. Battleships in a Board.py ├── 799. Champagne Tower.py ├── _1209_RemoveAllAdjacentDuplicatesInStringII.py ├── 1461. Check If a String Contains All Binary Codes of Size K.py ├── _2104_SumOfSubarrayRanges.py ├── _402_RemoveKDigits.py ├── _75_SortColors.java ├── 2128. Remove All Ones With Row and Column Flips.py ├── 915. Partition Array into Disjoint Intervals.py ├── Node.java ├── 1151. Minimum Swaps to Group All 1's Together.py ├── 1653. Minimum Deletions to Make String Balanced.py ├── _1509_MinimumDifferenceBetweenLargestAndSmallestValueInThreeMoves.py ├── _397_IntegerReplacement.java ├── 189. Rotate Array.py ├── 280. Wiggle Sort.py ├── _1277_CountSquareSubmatricesWithAllOnes.py ├── _2135_CountWordsObtainedAfterAddingALetter.py ├── _287_FindTheDuplicateNumber.java ├── 1650. Lowest Common Ancestor of a Binary Tree III.py ├── _116_PopulatingNextRightPointersInEachNode.java ├── _846_HandOfStraights.py ├── 120. Triangle.py ├── _1296_DivideArrayInSetsOfKConsecutiveNumbers.py ├── 1004. Max Consecutive Ones III.py ├── 974. Subarray Sums Divisible by K.py ├── _2208_MinimumOperationsToHalveArraySum.py ├── _539_MinimumTimeDifference.py ├── _825_FriendsOfAppropriateAges.py ├── 279. Perfect Squares.py ├── 354. Russian Doll Envelopes.py ├── 581. Shortest Unsorted Continuous Subarray.py ├── _198_HouseRobber.py ├── 582. Kill Process.py ├── _1053_PreviousPermutationWithOneSwap.py ├── _215_KthLargestElementInAnArray.java ├── _217_ContainsDuplicate.java ├── _670_MaximumSwap.py ├── 1679. Max Number of K-Sum Pairs.py ├── 841. Keys and Rooms.py ├── 2171. Removing Minimum Number of Magic Beans.py ├── 424. Longest Repeating Character Replacement.py ├── 60. Permutation Sequence.py ├── 1492. The kth Factor of n.py ├── 1387. Sort Integers by The Power Value.py ├── 2125. Number of Laser Beams in a Bank.py ├── 259. 3Sum Smaller.py ├── 264. Ugly Number II.py ├── 633. Sum of Square Numbers.py ├── 665. Non-decreasing Array.py ├── Same Tree.cpp ├── _26_RemoveDuplicateFromSortedArray.java ├── 881. Boats to Save People.py ├── _303_RangeSumQuery.java ├── 362. Design Hit Counter.py ├── Merge Sorted Array.cc ├── _1381_DesignAStackWithIncrementOperation.py ├── _1962_RemoveStonesToMinimizeTheTotal.py ├── 237. Delete Node in a Linked List.py ├── 795. Number of Subarrays with Bounded Maximum.py ├── 1506. Find Root of N-Ary Tree.py ├── 2134. Minimum Swaps to Group All 1's Together II.py ├── 540. Single Element in a Sorted Array.py ├── 852. Peak Index in a Mountain Array.py ├── _338_CountBits.java ├── _62_UniquePaths.java ├── 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.py ├── 1698. Number of Distinct Substrings in a String.py ├── 373. Find K Pairs with Smallest Sums.py ├── _1272_RemoveInterval.py ├── _1472_DesignBrowserHistory.py ├── _14_LongestCommonPrefix.java ├── _275_HIndexII.java ├── _986_IntervalListIntersections.py ├── 255. Verify Preorder Sequence in Binary Search Tree.py ├── _202_HappyNumber.java ├── _78_Subsets.java ├── 48. Rotate Image.py ├── 64. Minimum Path Sum.py ├── _1481_LeastNumberOfUniqueIntegersAfterKRemovals.py ├── _384_ShuffleAnArray.py ├── _939_MinimumAreaRectangle.py ├── 790. Domino and Tromino Tiling.py ├── _55_JumpGame.java ├── _729_MyCalendarI.java ├── _981_TimeBasedKeyValueStore.py ├── 487. Max Consecutive Ones II.py ├── Valid Palindrome.cc ├── _1518_WaterBottles.java ├── _802_FindEventualSafeStates.py ├── 1055. Shortest Way to Form String.py ├── 249. Group Shifted Strings.py ├── 948. Bag of Tokens.py ├── Binary Tree Postorder Traversal.cc ├── _1352_ProductOfTheLastKNumbers.py ├── _416_PartitionEqualSubsetSum.py ├── _811_SubdomainVisitCount.py ├── 1376. Time Needed to Inform All Employees.py ├── 159. Longest Substring with At Most Two Distinct Characters.py ├── Binary Tree Preorder Traversal.cc ├── 1143. Longest Common Subsequence.py ├── 1216. Valid Palindrome III.py ├── 1838. Frequency of the Most Frequent Element.py ├── 510. Inorder Successor in BST II.py ├── Binary Tree Inorder Traversal.cpp ├── Minimum Depth of Binary Tree.cc ├── _1081_SmallestSubsequenceOfDistinctCharacters.py ├── _2095_DeleteTheMiddleNodeOfALinkedList.java ├── _538_ConvertBstToGreaterTree.java ├── 1792. Maximum Average Pass Ratio.py ├── 663. Equal Tree Partition.py ├── _1642_FurthestBuildingYouCanReach.py ├── _388_LongestAbsoluteFilePath.py ├── _45_JumpGameII.java ├── 1641. Count Sorted Vowel Strings.py ├── _1048_LongestStringChain.py ├── _1510_StoneGameIV.py ├── 186. Reverse Words in a String II.py ├── _173_BinarySearchTreeIterator.py ├── _299_BullsAndCows.py ├── 1498. Number of Subsequences That Satisfy the Given Sum Condition.py ├── 155. Min Stack.py ├── 1855. Maximum Distance Between a Pair of Values.py ├── 2021. Brightest Position on Street.py ├── 845. Longest Mountain in Array.py ├── _1038_BinarySearchTreeToGreaterSumTree.java ├── 1312. Minimum Insertion Steps to Make a String Palindrome.py ├── 1395. Count Number of Teams.py ├── 777. Swap Adjacent in LR String.py ├── _1861_RotatingTheBox.py ├── _983_MinimumCostForTickets.py ├── 713. Subarray Product Less Than K.py ├── _1023_CamelcaseMatching.py ├── _152_MaximumProductSubarray.java ├── _230_KthSmallestElementInABST.py ├── _792_NumberOfMatchingSubsequences.py ├── 1570. Dot Product of Two Sparse Vectors.py ├── 1996. The Number of Weak Characters in the Game.py ├── _2116_CheckIfAParenthesesStringCanBeValid.py ├── 1525. Number of Good Ways to Split a String.py ├── 306. Additive Number.py ├── 328. Odd Even Linked List.py ├── 678. Valid Parenthesis String.py ├── _134_GasStation.java ├── _1647_MinimumDeletionsToMakeCharacterFrequenciesUnique.py ├── _200_NumberOfIslands.py ├── _2050_ParallelCoursesIII.py ├── _213_HouseRobberII.py ├── _498_DiagonalTraverse.py ├── 2250. Count Number of Rectangles Containing Each Point.py ├── 513. Find Bottom Left Tree Value.py ├── _66_PlusOne.java ├── 1428. Leftmost Column with at Least a One.py ├── 340. Longest Substring with At Most K Distinct Characters.py ├── 368. Largest Divisible Subset.py ├── 779. K-th Symbol in Grammar.py ├── _833_FindAndReplaceInString.py ├── 1060. Missing Element in Sorted Array.py └── 907. Sum of Subarray Minimums.py ├── lightoj ├── 1001 - Opposite Task.cpp ├── 1000 - Greetings from LightOJ.cpp ├── 1069 - Lift.cpp ├── 1182 - Parity.cpp ├── 1022 - Circle in Square.cpp ├── 1015 - Brush (I).cpp ├── 1216 - Juice in the Glass.cpp ├── 1241 - Pinocchio.cpp ├── 1107 - How Cow.cpp ├── 1305 - Area of a Parallelogram.cpp ├── 1225 - Palindromic Numbers (II).cpp ├── 1178 - Trapezium.cpp ├── 1227 - Boiled Eggs.cpp ├── 1387 - Setu.c ├── 1005 - Rooks.cpp └── 1053 - Higher Math.cpp ├── codejam ├── D1000000.py ├── Pancake Deque.py ├── PunchedCards.py └── 3DPrinting.py ├── README.md └── spoj ├── 1. Life, the Universe, and Everything.cpp └── 24. Small factorials.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | main.py 3 | *.iml -------------------------------------------------------------------------------- /uva online judge/10469 - To Carry or not to Carry.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | unsigned int a,b; 5 | while(scanf("%u%u", &a,&b)==2)printf("%u\n",a^b); 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /leetcode/_28_ImplementStrStr.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/23/2022 5 | **/ 6 | public class _28_ImplementStrStr { 7 | public int strStr(String haystack, String needle) { 8 | return haystack.indexOf(needle); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /uva online judge/10071 Back to High School Physics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int v,t; 8 | while(scanf("%d %d",&v,&t)==2){ 9 | cout<<(v*t*2)<= 0 ? pos : pos + 1); 8 | } 9 | } -------------------------------------------------------------------------------- /uva online judge/591-Box of Bricks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | char a[10]; 9 | cin>>a; 10 | puts(a); 11 | int x= atoi(a); 12 | cout< 2 | int main(){ 3 | int l,g,t; 4 | scanf("%d",&t); 5 | while(t--){ 6 | scanf("%d%d",&g,&l); 7 | if(l%g) 8 | printf("-1\n"); 9 | else printf("%d %d\n",g,l); 10 | } 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /leetcode/_125_Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | class _125_Palindrome { 3 | public boolean isPalindrome(int x) { 4 | if (x < 0) { 5 | return false; 6 | } else { 7 | return new StringBuilder().append(x).reverse().toString().equals(String.valueOf(x)); 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/_2063_VowelsOfAllSubstrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countVowels(self, word: str) -> int: 3 | nv = 0 4 | ans = 0 5 | for i, ch in enumerate(word): 6 | if ch in {'a', 'e', 'i', 'o', 'u'}: 7 | ans = ans + (i + 1) * (len(word) - i) 8 | return ans 9 | -------------------------------------------------------------------------------- /uva online judge/10055-hashmat.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | unsigned long int a,b; 4 | freopen("1.in","r",stdin); 5 | while(scanf("%lu %lu",&a,&b)==2){ 6 | if(a>b) 7 | printf("%lu\n",(a-b)); 8 | else 9 | printf("%lu\n",b-a); 10 | } 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /leetcode/_537_ComplexNumberMultiplication.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def complexNumberMultiply(self, num1, num2): 3 | x = [int(i) for i in num1[:-1].split('+')] 4 | y = [int(i) for i in num2[:-1].split('+')] 5 | return str(x[0] * y[0] - x[1] * y[1]) + '+' + str(x[0] * y[1] + x[1] * y[0]) + 'i' 6 | -------------------------------------------------------------------------------- /lightoj/1001 - Opposite Task.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int TC,n,r; 8 | cin >> TC; 9 | while(TC--) { 10 | cin >> n; 11 | r = n/2; 12 | cout << r << " " << n-r << endl; 13 | } 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/_1344_AngleBetweenHandsOfAClock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def angleClock(self, hour: int, minutes: int) -> float: 3 | x = (hour % 12) + minutes / 60 4 | y = minutes / 5 5 | if x > y: 6 | x, y = y, x 7 | diff = min(y - x, x + 12 - y) 8 | 9 | return (diff / 12) * 360 10 | -------------------------------------------------------------------------------- /leetcode/2214. Minimum Health to Beat Game.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minimumHealth(self, damage: List[int], armor: int) -> int: 6 | total_damage = sum(damage) 7 | max_armor_use = min(armor, max(damage)) 8 | 9 | return total_damage - max_armor_use + 1 10 | 11 | 12 | -------------------------------------------------------------------------------- /leetcode/_973_KClosestPointsToOrigin.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]: 3 | points.sort(key=lambda p: p[0] ** 2 + p[1] ** 2) 4 | closest_points = [] 5 | for i in range(k): 6 | closest_points.append(points[i]) 7 | return closest_points 8 | -------------------------------------------------------------------------------- /lightoj/1000 - Greetings from LightOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int TC,tc,a,b; 6 | scanf("%d",&TC); 7 | tc = 1; 8 | while(tc<=TC) { 9 | scanf("%d%d",&a,&b); 10 | printf("Case %d: %d\n",tc,(a+b)); 11 | tc++; 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /leetcode/_658_FindKClosestElements.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 6 | arr.sort(key=lambda a: [abs(a - x), a]) 7 | 8 | while len(arr) > k: 9 | arr.pop() 10 | arr.sort() 11 | return arr 12 | -------------------------------------------------------------------------------- /leetcode/462. Minimum Moves to Equal Array Elements II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minMoves2(self, nums: List[int]) -> int: 6 | nums.sort() 7 | avg = nums[len(nums) // 2] 8 | moves = 0 9 | for v in nums: 10 | moves += abs(v - avg) 11 | return moves 12 | -------------------------------------------------------------------------------- /leetcode/_126_DestroyingAsteroids.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool: 6 | asteroids.sort() 7 | for a in asteroids: 8 | if mass < a: 9 | return False 10 | mass += a 11 | return True 12 | -------------------------------------------------------------------------------- /uva online judge/458 - The Decoder.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | //freopen("input.txt","r",stdin); 5 | //freopen("output.txt","w",stdout); 6 | char ch; 7 | int t; 8 | while(scanf("%c",&ch)==1){ 9 | if(ch!='\n')printf("%c",ch-7); 10 | else printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /leetcode/_1010_PairsOfSongsTotalDivisibleBy60.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numPairsDivisibleBy60(self, time: list[int]) -> int: 3 | f = [0] * 60 4 | pt = 0 5 | for t in time: 6 | t = t % 60 7 | ct = (60 - t) % 60 8 | pt = pt + f[ct] 9 | f[t] = f[t] + 1 10 | return pt 11 | -------------------------------------------------------------------------------- /lightoj/1069 - Lift.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int T,t,me,li; 7 | cin>>T; 8 | t=1; 9 | while(T>=t) { 10 | cin>>me>>li; 11 | cout << "Case "< 2 | #include 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int n,con; 8 | float coca; 9 | while(scanf("%d",&n)==1){ 10 | coca=((float)n*3-1)/2; 11 | con=ceil(coca); 12 | cout< 2 | int mod(int b,int p,int m){ 3 | if(p==0)return 1; 4 | else if (p%2==0)return (mod(b,p/2,m)*mod(b,p/2,m))%m; 5 | else return ((b%m)*mod(b,p-1,m))%m; 6 | } 7 | int main(){ 8 | int b,p,m; 9 | while(scanf("%d%d%d",&b,&p,&m)==3) 10 | printf("%d\n",mod(b,p,m)); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /leetcode/_190_ReverseBits.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/24/2022 5 | **/ 6 | public class _190_ReverseBits { 7 | public int reverseBits(int n) { 8 | int r = 0; 9 | for (int i = 0; i < 32; i++) { 10 | r = (((n >> i) & 0x01) << (31 - i)) | r; 11 | } 12 | return r; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /leetcode/_901_OnlineStockSpan.py: -------------------------------------------------------------------------------- 1 | class StockSpanner: 2 | 3 | def __init__(self): 4 | self.stack = [] 5 | 6 | def next(self, price: int) -> int: 7 | l = 1 8 | while len(self.stack) >= l and self.stack[-l][0] <= price: 9 | l = l + self.stack[-l][1] 10 | self.stack.append((price, l)) 11 | return l 12 | -------------------------------------------------------------------------------- /leetcode/1846. Maximum Element After Decreasing and Rearranging.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: 6 | arr.sort() 7 | next_val = 0 8 | for v in arr: 9 | next_val = min(v, next_val + 1) 10 | return next_val 11 | 12 | -------------------------------------------------------------------------------- /leetcode/_1877_MinimizeMaximumPairSumInArray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minPairSum(self, nums: List[int]) -> int: 6 | nums.sort() 7 | max_pair_sum = 0 8 | for i in range(len(nums) // 2): 9 | max_pair_sum = max(max_pair_sum, nums[i] + nums[len(nums) - 1 - i]) 10 | return max_pair_sum 11 | -------------------------------------------------------------------------------- /leetcode/_222_CountCompleteTreeNodes.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/23/2022 5 | **/ 6 | public class _222_CountCompleteTreeNodes { 7 | public int countNodes(TreeNode root) { 8 | if (root == null) { 9 | return 0; 10 | } else return 1 + countNodes(root.left) + countNodes(root.right); 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode/_521_LongesUncommonSubsequenceI.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/28/2022 5 | **/ 6 | public class _521_LongesUncommonSubsequenceI { 7 | public int findLUSlength(String a, String b) { 8 | 9 | if (a.equals(b)) { 10 | return -1; 11 | } else return Math.max(a.length(), b.length()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode/_392_IsSubSequence.java: -------------------------------------------------------------------------------- 1 | 2 | class _392_IsSubSequence { 3 | public boolean isSubsequence(String s, String t) { 4 | int k = 0; 5 | for (int i = 0; i < t.length() && k < s.length(); i++) { 6 | if (t.charAt(i) == s.charAt(k)) k++; 7 | } 8 | if (k == s.length()) return true; 9 | else return false; 10 | 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/_509_FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | 2 | class _509_FibonacciNumber { 3 | static int[] fib = new int[31]; 4 | 5 | static { 6 | fib[0] = 0; 7 | fib[1] = 1; 8 | for (int i = 2; i < 31; i++) { 9 | fib[i] = fib[i - 2] + fib[i - 1]; 10 | } 11 | } 12 | 13 | public int fib(int n) { 14 | return fib[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/_921_MinimumAddToMakeParenthesesValid.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minAddToMakeValid(self, s: str) -> int: 3 | stack = [] 4 | ins = 0 5 | for p in s: 6 | if p == '(': 7 | stack.append(p) 8 | elif len(stack) == 0 or stack.pop() != '(': 9 | ins += 1 10 | return ins + len(stack) 11 | -------------------------------------------------------------------------------- /leetcode/_1823_FindTheWinnerOfTheCircularGame.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findTheWinner(self, n, k): 3 | circle = [i for i in range(1, n + 1)] 4 | p = 0 5 | while len(circle) > 1: 6 | p = (p + k - 1) % len(circle) 7 | circle.pop(p) 8 | if p == len(circle): 9 | p = 0 10 | return circle[0] 11 | -------------------------------------------------------------------------------- /leetcode/2221. Find Triangular Sum of an Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def triangularSum(self, nums: List[int]) -> int: 6 | dp = nums[:] 7 | for it in range(len(nums) - 1): 8 | for i in range(len(dp) - 1): 9 | dp[i] = (dp[i] + dp[i + 1]) % 10 10 | dp.pop() 11 | return dp[0] 12 | 13 | -------------------------------------------------------------------------------- /leetcode/_1963_MinimumNumberOfSwapsToMakeTheStringBalanced.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSwaps(self, s: str) -> int: 3 | stack = [] 4 | for b in s: 5 | if b == ']' and stack and stack[-1] == '[': 6 | stack.pop() 7 | else: 8 | stack.append(b) 9 | return len(stack) // 4 + (1 if len(stack) % 4 == 2 else 0) 10 | -------------------------------------------------------------------------------- /leetcode/360. Sort Transformed Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def sortTransformedArray(self, nums: List[int], a: int, b: int, c: int) -> List[int]: 6 | def f(x) -> int: 7 | return a * x ** 2 + b * x + c 8 | 9 | fx = [] 10 | for x in nums: 11 | fx.append(f(x)) 12 | fx.sort() 13 | return fx 14 | -------------------------------------------------------------------------------- /leetcode/_528_RandomPickWithWeight.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | from random import random 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | 8 | def __init__(self, w: List[int]): 9 | for i in range(1, len(w)): 10 | w[i] += w[i - 1] 11 | 12 | def pickIndex(self) -> int: 13 | r = random() * self.w[-1] 14 | return bisect.bisect_left(self.w, r) 15 | -------------------------------------------------------------------------------- /leetcode/_56_MergeIntervals.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def merge(self, intervals): 3 | intervals.sort(key=lambda x: x[0]) 4 | stack = [] 5 | for b in intervals: 6 | while stack and stack[-1][1] >= b[0]: 7 | a = stack.pop() 8 | b[0], b[1] = a[0], max(a[1], b[1]) 9 | stack.append(b) 10 | return stack 11 | -------------------------------------------------------------------------------- /leetcode/_70_ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | 2 | class _70_ClimbingStairs { 3 | static int [] ways = new int[46]; 4 | static { 5 | ways[0] = 0; 6 | ways[1] = 1; 7 | ways[2] = 2; 8 | for (int i = 3; i < 46; i++){ 9 | ways[i] = ways[i-2] + ways[i-1]; 10 | } 11 | } 12 | public int climbStairs(int n) { 13 | return ways[n]; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/_946_ValidateStackSequences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validateStackSequences(self, pushed, popped): 3 | stack = [] 4 | popped.reverse() 5 | for v in pushed: 6 | stack.append(v) 7 | while stack and popped and stack[-1] == popped[-1]: 8 | popped.pop() 9 | stack.pop() 10 | return len(stack) == 0 -------------------------------------------------------------------------------- /uva online judge/12372 - Packing for Holiday.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int test,cs=0,a,b,c; 7 | scanf("%d",&test); 8 | while(test--){ 9 | scanf("%d %d %d",&a,&b,&c); 10 | if(a<21&&b<21&&c<21)printf("Case %d: good\n",++cs); 11 | else 12 | printf("Case %d: bad\n",++cs); 13 | } 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/172. Factorial Trailing Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trailingZeroes(self, n: int) -> int: 3 | twos = fives = 0 4 | for x in range(2, n + 1): 5 | while x % 2 == 0: 6 | x = x // 2 7 | twos += 1 8 | while x % 5 == 0: 9 | x = x // 5 10 | fives += 1 11 | return min(twos, fives) 12 | 13 | -------------------------------------------------------------------------------- /leetcode/_1218_LongestArithmeticSubsequenceOfGivenDifference.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def longestSubsequence(self, arr: List[int], difference: int) -> int: 7 | sl = collections.defaultdict(int) 8 | for b in arr: 9 | a = b - difference 10 | sl[b] = max(sl[b], sl[a] + 1) 11 | return max(sl.values()) 12 | -------------------------------------------------------------------------------- /leetcode/_1985_FindtheKthLargestIntegerInTheheArray.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def kthLargestNumber(self, nums: List[str], k: int) -> str: 7 | mq = [] 8 | for n in nums: 9 | heappush(mq, (len(n),n)) 10 | if len(mq) > k: 11 | heappop(mq) 12 | return heappop(mq)[1] 13 | -------------------------------------------------------------------------------- /leetcode/_451_SortCharactersByFrequency.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def frequencySort(self, s: str) -> str: 3 | fc = {} 4 | for ch in s: 5 | fc[ch] = fc.get(ch, 0) + 1 6 | cat_list = [] 7 | for ch, n in sorted([(k, v) for k, v in fc.items()], key=lambda x: x[1], reverse=True): 8 | cat_list.append(''.ljust(n, ch)) 9 | return ''.join(cat_list) 10 | -------------------------------------------------------------------------------- /uva online judge/11877 - The Coco-Cola Store.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int n,con; 8 | float coca; 9 | while(1){ 10 | scanf("%d",&n); 11 | if(n==EOF)break; 12 | coca=((float)n*3-1)/2; 13 | con=ceil(coca); 14 | cout< 2 | #include 3 | using namespace std; 4 | int main() { 5 | int TC,tc,n; 6 | tc = 1; 7 | cin >> TC; 8 | while(tc<=TC) { 9 | cin >> n; 10 | if(__builtin_popcount(n)%2==0) 11 | printf("Case %d: even\n",tc); 12 | else printf("Case %d: odd\n",tc); 13 | tc = tc + 1; 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /uva online judge/10783-odd sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t,a,p,s,i; 8 | cin>>t; 9 | 10 | i=1; 11 | while(t>0){ 12 | cin>>a>>p; 13 | if(a%2==0)a=a+1; 14 | if(p%2==0)p=p-1; 15 | s=(2*a+2*p+p*p-a*a)/4; 16 | cout<<"Case "<=0){ 13 | System.out.println(n*(n+1)/2+1); 14 | n =sc.nextLong(); 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /uva online judge/10127 - Ones.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n,ones,c; 8 | 9 | while(scanf("%d",&n)==1){ 10 | ones = 0; 11 | c =0; 12 | do{ 13 | 14 | c = (c*10+1)%n; 15 | ones ++; 16 | } 17 | while(c!=0); 18 | printf("%d\n",ones); 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /uva online judge/10432-Polygon Inside A Circle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | 9 | double PI,r,n,a,b,w; 10 | PI=2*acos(0.0); 11 | while(scanf("%lf%lf",&r,&n)==2) 12 | { 13 | w=PI/n; 14 | a=r*cos(w); 15 | b=r*sin(w); 16 | printf("%.3lf\n",n*a*b); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /codejam/D1000000.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ == '__main__': 4 | T = int(sys.stdin.readline()) 5 | for tc in range(1, T + 1, 1): 6 | N = int(sys.stdin.readline()) 7 | a = list(map(int, sys.stdin.readline().split(' '))) 8 | a.sort() 9 | c = 0 10 | for v in a: 11 | if c + 1 <= v: 12 | c += 1 13 | print('Case #' + str(tc) + ': ' + str(c)) 14 | -------------------------------------------------------------------------------- /uva online judge/11172 - Relational Operator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t,a,b,i; 8 | cin>>t; 9 | i=0; 10 | while(i>a>>b; 13 | if(a==b)cout<<"="<"< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t,n,i; 7 | cin>>t; 8 | i=0; 9 | while(i>n; 12 | n=(n*63+7492)*5-498; 13 | n=(n/10)%10; 14 | if(n<0)n=n*(-1); 15 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | float c,e,f,n; 9 | int t; 10 | scanf("%d",&t); 11 | while(t--){ 12 | scanf("%f%f%f",&e,&f,&c); 13 | n = ((e+f)/(c-1))-1; 14 | if(n<=0)cout<<0< int: 3 | def f(x: int, from_left: bool) -> int: 4 | if x == 1: 5 | return 1 6 | elif x % 2 == 0 and not from_left: 7 | return 2 * f(x // 2, not from_left) - 1 8 | else: 9 | return 2 * f(x // 2, not from_left) 10 | 11 | return f(n, True) 12 | -------------------------------------------------------------------------------- /lightoj/1022 - Circle in Square.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | double a,r,pi; 8 | pi = 2*acos(0); 9 | int TC,tc; 10 | tc = 1; 11 | cin >> TC; 12 | while(tc<=TC) { 13 | cin >> r; 14 | a = r+r; 15 | printf("Case %d: %.2lf\n",tc,((a*a)-(pi*r*r))); 16 | tc ++; 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/_1400_ConstructKPalindrome Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canConstruct(self, s: str, k: int) -> bool: 3 | if len(s) < k: 4 | return False 5 | f = {} 6 | for ch in s: 7 | f[ch] = f.get(ch, 0) + 1 8 | odd_fc_count = 0 9 | for v in f.values(): 10 | if v % 2 != 0: 11 | odd_fc_count = odd_fc_count + 1 12 | return odd_fc_count <= k 13 | -------------------------------------------------------------------------------- /leetcode/_1248_CountNumberOfNiceSubarrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from collections import defaultdict 3 | 4 | 5 | class Solution: 6 | def numberOfSubarrays(self, nums: List[int], k: int) -> int: 7 | fc = defaultdict(int) 8 | fc[0] += 1 9 | ps = 0 10 | sc = 0 11 | for v in nums: 12 | ps += v % 2 13 | sc += fc[ps - k] 14 | fc[ps] += 1 15 | return sc 16 | -------------------------------------------------------------------------------- /leetcode/_2083_SubstringsThatBeginAndEndWithTheSameLetter.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSubstrings(self, s: str) -> int: 3 | f = [0] * 26 4 | for c in s: 5 | c_val = ord(c) - ord('a') 6 | f[c_val] += 1 7 | msc = 0 8 | for c in s: 9 | c_val = ord(c) - ord('a') 10 | n = f[c_val] 11 | msc = msc + n 12 | f[c_val] -= 1 13 | return msc -------------------------------------------------------------------------------- /uva online judge/11805 - Bafana Bafana.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t,n,k,p,i,out; 8 | cin>>t; 9 | i=1; 10 | while(i<=t) 11 | { 12 | cin>>n>>k>>p; 13 | out=(k+p)%n; 14 | if(out!=0)cout<<"Case "< int: 3 | dp = {0: 0, 1: 1} 4 | 5 | def find_min_days(r: int) -> int: 6 | if r not in dp: 7 | x = 1 + (r % 2) + find_min_days(r // 2) 8 | y = 1 + (r % 3) + find_min_days(r // 3) 9 | dp[r] = min(x, y) 10 | return dp[r] 11 | 12 | return find_min_days(n) -------------------------------------------------------------------------------- /lightoj/1015 - Brush (I).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int T,t,x,n,i; 7 | unsigned long long int s; 8 | cin>>T; 9 | t=1; 10 | while(t<=T) { 11 | s=0; 12 | cin>>n; 13 | for(i=0; i>x; 15 | if(x>=0)s+=x; 16 | } 17 | cout<<"Case "< 2 | #include 3 | 4 | int main(){ 5 | int i, ans; 6 | while(scanf("%d", &i) == 1){ 7 | ans = 0; 8 | ans |= (i << 24); 9 | ans |= ((i & 0x0000FF00) << 8); 10 | ans |= ((i & 0x00FF0000) >> 8); 11 | ans |= (i >> 24); 12 | printf("%d converts to %d\n", i, ans); 13 | } 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## About Code 2 | Problem solutions with DSA(Data Structure and Algorithm) 3 | ## Online problem solving platforms 4 | - [LeetCode](https://github.com/shahidul2k9/problem-solution/tree/master/leetcode) 5 | - [UVA](https://github.com/shahidul2k9/problem-solution/tree/master/uva%20online%20judge) 6 | - [LightOj](https://github.com/shahidul2k9/problem-solution/tree/master/lightoj) 7 | - [Spoj](https://github.com/shahidul2k9/problem-solution/tree/master/spoj) 8 | -------------------------------------------------------------------------------- /leetcode/930. Binary Subarrays With Sum.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: 7 | psf = collections.defaultdict(int) 8 | psf[0] = 1 9 | subarrays = 0 10 | s = 0 11 | for v in nums: 12 | s += v 13 | subarrays += psf[s-goal] 14 | psf[s] += 1 15 | return subarrays -------------------------------------------------------------------------------- /leetcode/_226_InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | 2 | class _226_InvertBinaryTree { 3 | public TreeNode invertTree(TreeNode root) { 4 | if (root == null){ 5 | return root; 6 | }else { 7 | invertTree(root.left); 8 | invertTree(root.right); 9 | TreeNode left = root.left; 10 | root.left = root.right; 11 | root.right = left; 12 | return root; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/_1903_LargestOddNumberInString.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/31/2022 5 | **/ 6 | public class _1903_LargestOddNumberInString { 7 | public String largestOddNumber(String num) { 8 | for (int i = num.length() - 1; i >= 0; i--) { 9 | if (num.charAt(i) % 2 == 1) { 10 | return num.substring(0, i + 1); 11 | } 12 | 13 | } 14 | return ""; 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/_1953_MaximumNumberOfWeeksForWhichYouCanWork.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numberOfWeeks(self, milestones: List[int]) -> int: 6 | wrapper_max = max(milestones) 7 | total = sum(milestones) 8 | in_between_scattered = total - wrapper_max 9 | if in_between_scattered >= wrapper_max: 10 | return total 11 | else: 12 | return 2 * in_between_scattered + 1 13 | -------------------------------------------------------------------------------- /leetcode/_739_DailyTemperatures.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 6 | n = len(temperatures) 7 | w = [0] * n 8 | s = [] 9 | for i, v in enumerate(temperatures): 10 | while s and temperatures[s[-1]] < v: 11 | pi = s.pop() 12 | w[pi] = i - pi 13 | s.append(i) 14 | return w 15 | -------------------------------------------------------------------------------- /uva online judge/10346 - Peter's Smokes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int n,k,div,ciga,mod,i; 7 | while(scanf("%d%d",&n,&k)==2){ 8 | ciga=n; 9 | for(i=0;n>=k;i++) 10 | { 11 | div=n/k; 12 | mod=n%k; 13 | ciga=ciga+div; 14 | n=div+mod; 15 | } 16 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int cerial,con; 8 | double N,n; 9 | cerial=1; 10 | while(1) 11 | { 12 | cin>>N; 13 | if(N==0)break; 14 | N=(3+sqrt(9+8*N))/2; 15 | con=ceil(N); 16 | cout<<"Case "< int: 7 | frequency = collections.Counter(arr) 8 | removed = 0 9 | for i, fc in enumerate(sorted(frequency.values(), reverse=True)): 10 | removed += fc 11 | if removed * 2 >= len(arr): 12 | return i + 1 13 | return -1 14 | 15 | -------------------------------------------------------------------------------- /leetcode/1167. Minimum Cost to Connect Sticks.py: -------------------------------------------------------------------------------- 1 | from heapq import heappop, heappush 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def connectSticks(self, sticks: List[int]) -> int: 7 | hq = [] 8 | for sl in sticks: 9 | heappush(hq, sl) 10 | cost = 0 11 | while len(hq) >= 2: 12 | sl = heappop(hq) + heappop(hq) 13 | heappush(hq, sl) 14 | cost += sl 15 | return cost 16 | -------------------------------------------------------------------------------- /leetcode/325. Maximum Size Subarray Sum Equals k.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxSubArrayLen(self, nums: List[int], k: int) -> int: 6 | ps = {0: -1} 7 | s = 0 8 | ans = 0 9 | for i, v in enumerate(nums): 10 | s += v 11 | if s - k in ps: 12 | ans = max(ans, i - ps[s - k]) 13 | if s not in ps: 14 | ps[s] = i 15 | return ans 16 | -------------------------------------------------------------------------------- /leetcode/_2186_MinimumNumberOfStepsToMakeAnagramII.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSteps(self, s: str, t: str) -> int: 3 | f = {} 4 | for c in s: 5 | c1, c2 = f.get(c, (0, 0)) 6 | f[c] = (c1 + 1, c2) 7 | 8 | for c in t: 9 | c1, c2 = f.get(c, (0, 0)) 10 | f[c] = (c1, c2 + 1) 11 | 12 | cn = 0 13 | for c1, c2 in f.values(): 14 | cn += abs(c1 - c2) 15 | return cn 16 | -------------------------------------------------------------------------------- /leetcode/_386_LexicographicalNumbers.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def lexicalOrder(self, n: int) -> List[int]: 4 | ln = [] 5 | def generate(x): 6 | for i in range(0, 10, 1): 7 | if x != 0 or i != 0: 8 | v = x * 10 + i 9 | if v <= n: 10 | ln.append(v) 11 | generate(v) 12 | generate(0) 13 | return ln 14 | -------------------------------------------------------------------------------- /leetcode/_1673_FindTheMostCompetitiveSubsequence.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def mostCompetitive(self, nums: List[int], k: int) -> List[int]: 6 | stack = [] 7 | n = len(nums) 8 | for i, v in enumerate(nums): 9 | while stack and stack[-1] > v and len(stack) + (n - i) > k: 10 | stack.pop() 11 | if len(stack) < k: 12 | stack.append(v) 13 | return stack 14 | -------------------------------------------------------------------------------- /leetcode/_80_RemoveDuplicatesFromSortedArrayII.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def removeDuplicates(self, nums: List[int]) -> int: 6 | s = 1 7 | k = 0 8 | for i in range(1, len(nums)): 9 | if nums[k] == nums[i]: 10 | s += 1 11 | else: 12 | s = 1 13 | if s <= 2: 14 | k += 1 15 | nums[k] = nums[i] 16 | return k + 1 17 | -------------------------------------------------------------------------------- /leetcode/370. Range Addition.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: 6 | arr = [0] * length 7 | for a, b, val in updates: 8 | arr[a] += val 9 | if b + 1 < length: 10 | arr[b + 1] -= val 11 | s = 0 12 | for i in range(length): 13 | s += arr[i] 14 | arr[i] = s 15 | return arr 16 | -------------------------------------------------------------------------------- /leetcode/763. Partition Labels.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partitionLabels(self, s: str) -> List[int]: 3 | occ = {ch : i for i, ch in enumerate(s)} 4 | parts = [] 5 | i = left = 0 6 | while i < len(s): 7 | left = i 8 | right = occ[s[i]] 9 | while i <= right: 10 | right = max(right, occ[s[i]]) 11 | i += 1 12 | parts.append(right - left + 1) 13 | return parts 14 | -------------------------------------------------------------------------------- /leetcode/_1347_MinimumNumberOfStepsToMakeAnagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSteps(self, s: str, t: str) -> int: 3 | f = {} 4 | for c in s: 5 | c1, c2 = f.get(c, (0, 0)) 6 | f[c] = (c1 + 1, c2) 7 | 8 | for c in t: 9 | c1, c2 = f.get(c, (0, 0)) 10 | f[c] = (c1, c2 + 1) 11 | 12 | cn = 0 13 | for c1, c2 in f.values(): 14 | cn += abs(c1 - c2) 15 | return int(cn / 2) 16 | -------------------------------------------------------------------------------- /leetcode/_791_CustomSortString.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def customSortString(self, order: str, s: str) -> str: 3 | order_index_map = {c: i for i, c in enumerate(order)} 4 | for i in range(ord('a'), ord('z') + 1): 5 | c = chr(i) 6 | if c not in order_index_map: 7 | order_index_map[c] = float('inf') 8 | s_seq = [c for c in s] 9 | s_seq.sort(key=lambda x: order_index_map[x]) 10 | return ''.join(s_seq) 11 | -------------------------------------------------------------------------------- /uva online judge/10551 - Basic Remains.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | public class Main { 4 | public static void main(String[] args) { 5 | int b; 6 | BigInteger p,m; 7 | Scanner sc = new Scanner(System.in); 8 | while(true){ 9 | b = sc.nextInt(); 10 | if(b==0)break; 11 | p = sc.nextBigInteger(b); 12 | m = sc.nextBigInteger(b); 13 | System.out.println(p.mod(m).toString(b)); 14 | 15 | } 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /uva online judge/424-Integer Inquiry.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.math.BigInteger; 3 | 4 | public class BigSum { 5 | public static void main(String args[]){ 6 | BigInteger temp; 7 | BigInteger sum = new BigInteger("0"); 8 | Scanner sc = new Scanner(System.in); 9 | 10 | while(true){ 11 | temp = sc.nextBigInteger(); 12 | if(temp.compareTo(BigInteger.valueOf(0))==0)break; 13 | sum = sum.add(temp); 14 | } 15 | System.out.println(sum); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/560. Subarray Sum Equals K.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def subarraySum(self, nums: List[int], k: int) -> int: 7 | fc = collections.defaultdict(int) 8 | fc[0] = 1 9 | cs = 0 10 | ans = 0 11 | for v in nums: 12 | cs += v 13 | fc[cs] += 1 14 | if k == 0: 15 | ans -= 1 16 | ans += fc[cs - k] 17 | return ans 18 | -------------------------------------------------------------------------------- /leetcode/_1366_RankTeamsByVotes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rankTeams(self, votes: list[str]) -> str: 3 | ln = len(votes[0]) 4 | vc = {} 5 | for v in votes: 6 | for i, c in enumerate(v): 7 | vc.setdefault(c, [0] * ln) 8 | vc[c][i] += 1 9 | 10 | return ''.join(sorted(vc.keys(), key=lambda x: (vc[x], -ord(x)), reverse=True)) 11 | 12 | 13 | print(Solution().rankTeams(["ABC", "ACB", "ABC", "ACB", "ACB"])) 14 | -------------------------------------------------------------------------------- /leetcode/_1554_StringsDifferByOneCharacter.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def differByOne(self, dict: List[str]) -> bool: 6 | 7 | for i in range(len(dict[0])): 8 | word_set = set() 9 | for w in dict: 10 | mw = w[:i] + '*' + w[i + 1:] 11 | if mw in word_set: 12 | return True 13 | else: 14 | word_set.add(mw) 15 | return False 16 | -------------------------------------------------------------------------------- /leetcode/_2091_RemovingMinimumAndMaximumFromArray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minimumDeletions(self, nums: List[int]) -> int: 6 | x, y = 0, 0 7 | n = len(nums) 8 | for i, v in enumerate(nums): 9 | if v < nums[x]: 10 | x = i 11 | if v > nums[y]: 12 | y = i 13 | if x > y: 14 | x, y = y, x 15 | 16 | return min(x + 1 + n - y, y + 1, n - x) 17 | -------------------------------------------------------------------------------- /leetcode/1762. Buildings With an Ocean View.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findBuildings(self, heights: List[int]) -> List[int]: 6 | max_right = 0 7 | ocean_view_buildings = [] 8 | for ri in range(len(heights) - 1, -1, -1): 9 | if heights[ri] > max_right: 10 | ocean_view_buildings.append(ri) 11 | max_right = max(max_right, heights[ri]) 12 | return ocean_view_buildings[::-1] 13 | 14 | -------------------------------------------------------------------------------- /leetcode/311. Sparse Matrix Multiplication.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: 6 | m, k, n = len(mat1), len(mat1[0]), len(mat2[0]) 7 | pm = [[0] * n for _ in range(m)] 8 | for r in range(m): 9 | for c in range(n): 10 | for i in range(k): 11 | pm[r][c] += mat1[r][i] * mat2[i][c] 12 | return pm 13 | 14 | -------------------------------------------------------------------------------- /leetcode/1288. Remove Covered Intervals.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: 6 | intervals.sort(key=lambda iv: (iv[0], -iv[1])) 7 | removed = 0 8 | for i, (a, b) in enumerate(intervals): 9 | if i == 0 or not (c <= a and b <= d): 10 | c, d = a, b 11 | else: 12 | removed += 1 13 | return len(intervals) - removed 14 | -------------------------------------------------------------------------------- /leetcode/Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | struct TreeNode { 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | int maxDepth(TreeNode *root) { 16 | if(root == NULL) return 0; 17 | return 1 + max(maxDepth(root->left), maxDepth(root->right)); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/_1423_MaximumPointsYouCanObtainFromCards.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxScore(self, cardPoints: List[int], k: int) -> int: 6 | cpn = len(cardPoints) 7 | ps = [0] * (cpn + 1) 8 | for i in range(1, len(ps)): 9 | ps[i] = ps[i - 1] + cardPoints[i - 1] 10 | 11 | mx = float('-inf') 12 | for i in range(k + 1): 13 | mx = max(mx, ps[i] + ps[cpn] - ps[cpn - (k - i)]) 14 | return mx 15 | -------------------------------------------------------------------------------- /leetcode/_452_MinimumNumberOfArrowsToBurstBalloons.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findMinArrowShots(self, points: List[List[int]]) -> int: 6 | points.sort() 7 | minimum_arrays = 1 8 | a, b = points[0] 9 | for c, d in points: 10 | if b >= c: 11 | a, b = max(a, c), min(b, d) 12 | else: 13 | a, b = c, d 14 | minimum_arrays += 1 15 | return minimum_arrays -------------------------------------------------------------------------------- /uva online judge/10106 - Product JAVA.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | public class Main { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | BigInteger x,y; 11 | Scanner sc = new Scanner(System.in); 12 | while(sc.hasNext()){ 13 | x = sc.nextBigInteger(); 14 | y = sc.nextBigInteger(); 15 | System.out.println(x.multiply(y)); 16 | } 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /uva online judge/579 - ClockHands.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | float h,m,dh,dm,deg; 8 | while(1){ 9 | scanf("%f:%f",&h,&m); 10 | if(h==0&&m==0)break; 11 | dm = 6*m; 12 | dh = 30*(h+(dm/360)); 13 | if(dm>dh) deg = dm-dh; 14 | else deg = dh-dm; 15 | if(deg>180)printf("%.3f\n",360-deg); 16 | else printf("%.3f\n",deg); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/523. Continuous Subarray Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def checkSubarraySum(self, nums: List[int], k: int) -> bool: 6 | ps = 0 7 | remainders = {} 8 | for i, v in enumerate(nums): 9 | ps = (ps + v) % k 10 | if ps in remainders and i - remainders[ps] > 1 or (ps == 0 and i > 0): 11 | return True 12 | if ps not in remainders: 13 | remainders[ps] = i 14 | return False -------------------------------------------------------------------------------- /leetcode/769. Max Chunks To Make Sorted.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxChunksToSorted(self, arr: List[int]) -> int: 6 | left = i = 0 7 | right = arr[i] 8 | chunks = 0 9 | while i < len(arr): 10 | if i == right: 11 | chunks += 1 12 | left = right + 1 13 | 14 | i += 1 15 | if i < len(arr): 16 | right = max(right, arr[i]) 17 | return chunks 18 | -------------------------------------------------------------------------------- /leetcode/_2110_NumberOfSmoothDescentPeriodsOfAStock.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def getDescentPeriods(self, prices: List[int]) -> int: 6 | previous_price = float('-inf') 7 | steak = 0 8 | sdp = 0 9 | for p in prices: 10 | if previous_price == p + 1: 11 | steak += 1 12 | else: 13 | steak = 1 14 | sdp += steak 15 | previous_price = p 16 | return sdp 17 | -------------------------------------------------------------------------------- /leetcode/_253_MeetingRoomsII.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from heapq import heappop, heappush 3 | 4 | 5 | class Solution: 6 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 7 | hq = [] 8 | for a, b in intervals: 9 | heappush(hq, [a, 1]) 10 | heappush(hq, [b, -1]) 11 | s = 0 12 | ans = 0 13 | while hq: 14 | _, v = heappop(hq) 15 | s += v 16 | ans = max(ans, s) 17 | return ans 18 | -------------------------------------------------------------------------------- /leetcode/_398_RandomPickIndex.py: -------------------------------------------------------------------------------- 1 | import random 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | 7 | def __init__(self, nums: List[int]): 8 | self.nums = nums 9 | 10 | def pick(self, target: int) -> int: 11 | c = 0 12 | rIndex = -1 13 | for i in range(len(self.nums)): 14 | if self.nums[i] == target: 15 | c += 1 16 | if random.randint(1, c) == c: 17 | rIndex = i 18 | return rIndex 19 | -------------------------------------------------------------------------------- /lightoj/1216 - Juice in the Glass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | double r1,r2,h,p,r,k,pi,juice; 8 | pi=2*acos(0.0); 9 | int T,t=1; 10 | cin>>T; 11 | while(t<=T) { 12 | cin>>r1>>r2>>h>>p; 13 | k=h/(r1/r2-1); 14 | r=((k+p)/k)*r2; 15 | juice=(pi*(r*r*(p+k)-r2*r2*k))/3; 16 | printf("Case %d: %.9lf\n",t,juice); 17 | t++; 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /lightoj/1241 - Pinocchio.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() { 4 | int T,n,lie,i,a[12],t=0; 5 | a[0]=2; 6 | scanf("%d",&T); 7 | while(T--) { 8 | scanf("%d",&n); 9 | for(i=1; i<=n; i++) { 10 | scanf("%d",&a[i]); 11 | } 12 | for(i=0,lie=0; ia[i])lie+=ceil(((double)a[i+1]-a[i])/5); 14 | } 15 | printf("Case %d: %d\n",++t,lie); 16 | } 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/1014. Best Sightseeing Pair.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxScoreSightseeingPair(self, values: List[int]) -> int: 6 | n = len(values) 7 | dragged_values = values[:] 8 | for i in range(n - 2, -1, -1): 9 | dragged_values[i] = max(dragged_values[i + 1] - 1, dragged_values[i]) 10 | ans = 0 11 | for i in range(n - 1): 12 | ans = max(ans, values[i] + dragged_values[i + 1] - 1) 13 | return ans 14 | -------------------------------------------------------------------------------- /leetcode/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinFibonacciNumbers(self, k: int) -> int: 3 | fb = [1, 1] 4 | while fb[-1] < 10 ** 9: 5 | fb.append(fb[-2] + fb[-1]) 6 | 7 | count = 0 8 | idx = len(fb) - 1 9 | while k > 0: 10 | if fb[idx] > k: 11 | idx -= 1 12 | else: 13 | k -= fb[idx] 14 | count += 1 15 | return count 16 | -------------------------------------------------------------------------------- /leetcode/_1781_SumOfBeautyOfAllSubstrings.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | def beautySum(self, s: str) -> int: 4 | beauty = 0 5 | for left in range(len(s)): 6 | fc = defaultdict(int) 7 | max_f = 0 8 | for right in range(left, len(s)): 9 | ch = s[right] 10 | fc[ch] += 1 11 | max_f = max(max_f, fc[ch]) 12 | beauty += (max_f - min(fc.values())) 13 | return beauty -------------------------------------------------------------------------------- /leetcode/_647_PalindromicSubstrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | n = len(s) 4 | p = [[False] * n for _ in range(n)] 5 | for i in range(n): 6 | p[i][i] = True 7 | pnc = n 8 | for d in range(1, n): 9 | for i in range(0, n - d): 10 | if s[i] == s[i + d] and (d < 2 or p[i + 1][i + d - 1]): 11 | p[i][i + d] = True 12 | pnc += 1 13 | return pnc 14 | -------------------------------------------------------------------------------- /uva online judge/10696-f91.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int function(int n){ 5 | n=n+1; 6 | if(n<=100){return(function(n));} 7 | else return n; 8 | } 9 | int main() 10 | { 11 | int n,x; 12 | scanf("%d",&n); 13 | while(1){ 14 | if(n==0)break; 15 | x=n; 16 | if(n<=100){n=function(n);} 17 | n=n-10; 18 | cout<<"f91("< int: 6 | frequency = Counter(s) 7 | press_count = 0 8 | index = 0 9 | for ch, f in sorted(frequency.items(), key=lambda x: x[1], reverse=True): 10 | press = 1 if index < 9 else (2 if index < 18 else 3) 11 | press_count += f * press 12 | index += 1 13 | return press_count 14 | 15 | 16 | -------------------------------------------------------------------------------- /leetcode/503. Next Greater Element II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def nextGreaterElements(self, nums: List[int]) -> List[int]: 6 | n = len(nums) 7 | gt = [-1] * n 8 | 9 | stack = [] 10 | for i, v in enumerate(nums + nums): 11 | while stack and stack[-1][1] < v: 12 | pos, _ = stack.pop() 13 | gt[pos] = v 14 | if i < n: 15 | stack.append([i, v]) 16 | 17 | return gt 18 | -------------------------------------------------------------------------------- /leetcode/_1657_DetermineIfTwoStringsAreClose.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from itertools import zip_longest 3 | 4 | 5 | class Solution: 6 | def closeStrings(self, word1: str, word2: str) -> bool: 7 | w1fc = Counter(word1) 8 | w2fc = Counter(word2) 9 | return set(w1fc.keys()) == set(w2fc.keys()) and \ 10 | all(x == y for x, y in 11 | zip_longest(sorted(w1fc.values()), sorted(w2fc.values()), 12 | fillvalue=0)) 13 | -------------------------------------------------------------------------------- /leetcode/_316_RemoveDuplicateLetters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicateLetters(self, s: str) -> str: 3 | stack = [] 4 | lc = {k: v for k, v in enumerate(s)} 5 | picked = set() 6 | for i, c in enumerate(s): 7 | if c not in picked: 8 | while stack and stack[-1] > c and lc[stack[-1]] > i: 9 | picked.remove(stack.pop()) 10 | stack.append(c) 11 | picked.add(c) 12 | return ''.join(stack) 13 | -------------------------------------------------------------------------------- /lightoj/1107 - How Cow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int T,t,m,x,y,x1,x2,y1,y2,i; 7 | cin>>T; 8 | t=1; 9 | while(t<=T) { 10 | cout<<"Case "<>x1>>y1>>x2>>y2; 12 | cin>>m; 13 | for(i=0; i>x>>y; 15 | if(x>x1&&xy1&&y 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int ax,ay,bx,by,cx,cy,dx,dy,area; 7 | int T,t=1; 8 | cin>>T; 9 | while(T>=t) { 10 | cin>>ax>>ay>>bx>>by>>cx>>cy; 11 | area = (ax*(by-cy)+bx*(cy-ay)+cx*(ay-by)); 12 | dx=ax+cx-bx; 13 | dy=ay+cy-by; 14 | cout<<"Case "< 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | int main(){ 12 | int x; 13 | bool ok = true; 14 | while(scanf("%d", &x) == 1){ 15 | if(ok){ 16 | if(x == 42) ok = false; 17 | else printf("%d\n", x); 18 | } 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/_2178_MaximumSplitOfPositiveEvenIntegers.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maximumEvenSplit(self, finalSum: int) -> List[int]: 6 | even_nums = [] 7 | if finalSum & 1 == 0: 8 | c = 2 9 | while finalSum > 0 and finalSum - c > c: 10 | even_nums.append(c) 11 | finalSum -= c 12 | c += 2 13 | if finalSum: 14 | even_nums.append(finalSum) 15 | return even_nums 16 | -------------------------------------------------------------------------------- /leetcode/_435_NonOverlappingIntervals.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 6 | intervals.sort(key=lambda x: x[1]) 7 | minimum_removal = 0 8 | a, b = intervals[0] 9 | for i in range(1,len(intervals)): 10 | c,d = intervals[i] 11 | if b > c: 12 | minimum_removal += 1 13 | else: 14 | a,b = c,d 15 | return minimum_removal 16 | -------------------------------------------------------------------------------- /leetcode/_121_BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | 2 | class _121_BestTimeToBuyAndSellStock { 3 | public int maxProfit(int[] prices) { 4 | int minPrice, sellingPrice, localProfit, globalProfit; 5 | minPrice = prices[0]; 6 | globalProfit = 0; 7 | for (int i = 1; i < prices.length;i++){ 8 | globalProfit = Math.max(prices[i] - minPrice, globalProfit); 9 | minPrice = Math.min(minPrice, prices[i]); 10 | } 11 | return globalProfit; 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/525. Contiguous Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findMaxLength(self, nums: List[int]) -> int: 6 | fi = dict() 7 | fi[0] = -1 8 | n = 0 9 | ans = 0 10 | for i, b in enumerate(nums): 11 | if b == 0: 12 | n -= 1 13 | else: 14 | n += 1 15 | if n in fi: 16 | ans = max(ans, i - fi[n]) 17 | else: 18 | fi[n] = i 19 | return ans 20 | -------------------------------------------------------------------------------- /leetcode/_1492_TheKthFactorOfN.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/26/2022 5 | **/ 6 | public class _1492_TheKthFactorOfN { 7 | private static boolean[] prime = new boolean[1000 + 1]; 8 | 9 | int kthFactor(int n, int k) { 10 | 11 | for (int i = 1; i <= n; i++) { 12 | if (n % i == 0) { 13 | k--; 14 | if (k == 0) { 15 | return i; 16 | } 17 | } 18 | } 19 | return -1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/_954_ArrayOfDoubledPairs.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def canReorderDoubled(self, arr: List[int]) -> bool: 7 | fc = collections.Counter(arr) 8 | arr.sort(key= lambda x : abs(x)) 9 | for v in arr: 10 | if fc[v] > 0: 11 | if fc.get(2 * v, 0) < 1: 12 | return False 13 | else: 14 | fc[v] -= 1 15 | fc[2 * v] -= 1 16 | return True 17 | -------------------------------------------------------------------------------- /leetcode/2090. K Radius Subarray Averages.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def getAverages(self, nums: List[int], k: int) -> List[int]: 6 | n = len(nums) 7 | prefix_sum = [0] * (n + 1) 8 | for i in range(1, n + 1): 9 | prefix_sum[i] += prefix_sum[i - 1] + nums[i - 1] 10 | average = [-1] * n 11 | for i in range(k + 1, n + 1 - k): 12 | average[i - 1] = (prefix_sum[i + k] - prefix_sum[i - k - 1]) // (2 * k + 1) 13 | return average 14 | -------------------------------------------------------------------------------- /leetcode/611. Valid Triangle Number.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def triangleNumber(self, nums: List[int]) -> int: 6 | nums.sort() 7 | n = len(nums) 8 | triplets = 0 9 | for i in range(n): 10 | k = i + 2 11 | for j in range(i + 1, n): 12 | while k < n and nums[i] + nums[j] > nums[k]: 13 | k += 1 14 | k = max(k, j + 1) 15 | triplets += k - (j + 1) 16 | return triplets 17 | -------------------------------------------------------------------------------- /leetcode/_1817_FindingTheUsersActiveMinutes.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: 7 | active_minute_count = collections.defaultdict(set) 8 | for id, t in logs: 9 | active_minute_count[id].add(t) 10 | 11 | uam = [0] * k 12 | for v in active_minute_count.values(): 13 | if len(v) <= k: 14 | uam[len(v) - 1] += 1 15 | return uam 16 | -------------------------------------------------------------------------------- /uva online judge/11417 GCD.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int GCD(int x,int y){ 5 | int mod; 6 | while(1){ 7 | mod=y%x; 8 | if(mod==0)return x; 9 | y=x; 10 | x=mod; 11 | } 12 | } 13 | int main() 14 | { 15 | int N,G,i,j; 16 | scanf("%d",&N); 17 | while(N){ 18 | G=0; 19 | for(i=1;i 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a,b,c,asqure,bsqure,csqure; 8 | while(1){ 9 | scanf("%d%d%d",&a,&b,&c); 10 | if(a==0&&b==0&&c==0)break; 11 | asqure = a*a; 12 | bsqure =b*b; 13 | csqure =c*c; 14 | if((asqure+bsqure==csqure)||(bsqure+csqure==asqure)||(csqure+asqure==bsqure)) 15 | printf("right\n"); 16 | else printf("wrong\n"); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/_853_CarFleet.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: 6 | fleet_count = 0 7 | ps = [[position[i], speed[i]] for i in range(len(position))] 8 | ps.sort(reverse=True) 9 | 10 | clock = float('-inf') 11 | for p, s in ps: 12 | d = target - p 13 | if d / s > clock: 14 | clock = d / s 15 | fleet_count += 1 16 | return fleet_count 17 | -------------------------------------------------------------------------------- /uva online judge/10334 - Ray Through Glasses JAVA.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | public class Main { 4 | public static void main(String args[]){ 5 | Scanner sc = new Scanner(System.in); 6 | int i,index; 7 | BigInteger ob[] = new BigInteger[1001]; 8 | ob[0] = BigInteger.ONE; 9 | ob[1] = BigInteger.ONE.add(BigInteger.ONE); 10 | for(i=2;i<1001;i++)ob[i] = ob[i-1].add(ob[i-2]); 11 | while(sc.hasNextInt()){ 12 | index = sc.nextInt(); 13 | System.out.println(ob[index]); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/419. Battleships in a Board.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def countBattleships(self, board: List[List[str]]) -> int: 6 | m, n = len(board), len(board[0]) 7 | battle_ships = 0 8 | for r in range(m): 9 | for c in range(n): 10 | if board[r][c] == 'X': 11 | if not (r - 1 >= 0 and board[r - 1][c] == 'X') and not (c - 1 >= 0 and board[r][c - 1] == 'X'): 12 | battle_ships += 1 13 | return battle_ships 14 | -------------------------------------------------------------------------------- /leetcode/799. Champagne Tower.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 3 | glasses_up = [poured] 4 | for row in range(0, query_row): 5 | glasses_down = [0] 6 | for i, cp in enumerate(glasses_up): 7 | half = max(cp - 1, 0) / 2 8 | glasses_down[-1] += half 9 | glasses_down.append(half) 10 | glasses_up = glasses_down 11 | return min(glasses_up[query_glass], 1) 12 | 13 | 14 | -------------------------------------------------------------------------------- /leetcode/_1209_RemoveAllAdjacentDuplicatesInStringII.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, s: str, k: int) -> str: 3 | stack = [] 4 | for c in s: 5 | if stack and stack[-1][0] == c: 6 | if stack[-1][1] + 1 == k: 7 | stack.pop() 8 | else: 9 | _, pc = stack.pop() 10 | stack.append((c, pc + 1)) 11 | else: 12 | stack.append((c, 1)) 13 | return ''.join([c * n for c, n in stack]) 14 | -------------------------------------------------------------------------------- /uva online judge/11462-Age Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int age[200],p,i; 9 | freopen("input.txt","r",stdin); 10 | scanf("%d",&p); 11 | while(p!=0) 12 | { 13 | for(i=0;i bool: 3 | val = 0 4 | val_set = set() 5 | for i in range(len(s)): 6 | ith_bit = ord(s[i]) - ord('0') 7 | if i + 1 < k: 8 | val += (ith_bit << i) 9 | else: 10 | val += (ith_bit << k - 1) 11 | val_set.add(val) 12 | val = val >> 1 13 | return len(val_set) == (1 << k) 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /leetcode/_2104_SumOfSubarrayRanges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subArrayRanges(self, nums: list[int]) -> int: 3 | n = len(nums) 4 | low = [x for x in nums] 5 | high = [x for x in nums] 6 | sum = 0 7 | for d in range(1, n, 1): 8 | for i in range(0, n - d): 9 | low[i] = min(low[i], nums[i + d]) 10 | high[i] = max(high[i], nums[i + d]) 11 | sum = sum + high[i] - low[i] 12 | 13 | return sum 14 | #print(Solution().subArrayRanges([1, 2, 3])) 15 | -------------------------------------------------------------------------------- /leetcode/_402_RemoveKDigits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeKdigits(self, num: str, k: int) -> str: 3 | stack = [] 4 | dc = 0 5 | for d in num: 6 | while stack and stack[-1] > d and dc < k: 7 | stack.pop() 8 | dc = dc + 1 9 | if stack or d > '0': 10 | stack.append(d) 11 | while stack and k > 0: 12 | stack.pop() 13 | if len(stack) <= k: 14 | return '0' 15 | else: 16 | return ''.join(stack) 17 | -------------------------------------------------------------------------------- /leetcode/_75_SortColors.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/5/2022 5 | **/ 6 | public class _75_SortColors { 7 | public void sortColors(int[] nums) { 8 | int n = nums.length; 9 | for (int i = 0; i < n; i++) { 10 | for (int j = i + 1; j < n; j++) { 11 | if (nums[i] > nums[j]) { 12 | int tmp = nums[i]; 13 | nums[i] = nums[j]; 14 | nums[j] = tmp; 15 | } 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /uva online judge/11875 - Brick Game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector v; 9 | int t,intot,age,ct=1; 10 | scanf("%d",&t); 11 | while(ct<=t){ 12 | scanf("%d",&intot); 13 | for(int i =0;i bool: 6 | m, n = len(grid), len(grid[0]) 7 | for c in range(n): 8 | if grid[0][c] == 1: 9 | for r in range(m): 10 | grid[r][c] = 1 - grid[r][c] 11 | for r in range(1, m): 12 | row_sum = sum(grid[r]) 13 | if row_sum != 0 and row_sum != n: 14 | return False 15 | return True -------------------------------------------------------------------------------- /leetcode/915. Partition Array into Disjoint Intervals.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def partitionDisjoint(self, nums: List[int]) -> int: 6 | n = len(nums) 7 | min_num = nums[:] 8 | for i in range(n-2, -1, -1): 9 | min_num[i] = min(min_num[i+1], min_num[i]) 10 | max_val = nums[0] 11 | for i in range(1, n): 12 | if max_val <= min_num[i]: 13 | return i 14 | else: 15 | max_val = max(max_val, nums[i]) 16 | return -1 -------------------------------------------------------------------------------- /leetcode/Node.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.List; 3 | 4 | public class Node { 5 | public int val; 6 | public Node left; 7 | public Node right; 8 | public Node next; 9 | public Node random; 10 | public List neighbors; 11 | 12 | public Node() {} 13 | 14 | public Node(int _val) { 15 | val = _val; 16 | } 17 | 18 | public Node(int _val, Node _left, Node _right, Node _next) { 19 | val = _val; 20 | left = _left; 21 | right = _right; 22 | next = _next; 23 | } 24 | 25 | }; -------------------------------------------------------------------------------- /leetcode/1151. Minimum Swaps to Group All 1's Together.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minSwaps(self, data: List[int]) -> int: 6 | w = sum(data) 7 | left = right = 0 8 | s = 0 9 | max_ones = 0 10 | while right < len(data): 11 | s += data[right] 12 | right += 1 13 | if right - left == w: 14 | max_ones = max(max_ones, s) 15 | s -= data[left] 16 | left += 1 17 | return w - max_ones 18 | 19 | 20 | -------------------------------------------------------------------------------- /leetcode/1653. Minimum Deletions to Make String Balanced.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Solution: 5 | def minimumDeletions(self, s: str) -> int: 6 | f = collections.Counter(s) 7 | left_b = 0 8 | right_a = f['a'] 9 | ans = len(s) 10 | for i in range(0, len(s) + 1): 11 | ans = min(left_b + right_a, ans) 12 | if i < len(s): 13 | if s[i] == 'b': 14 | left_b += 1 15 | else: 16 | right_a -= 1 17 | 18 | return ans -------------------------------------------------------------------------------- /leetcode/_1509_MinimumDifferenceBetweenLargestAndSmallestValueInThreeMoves.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minDifference(self, nums: List[int]) -> int: 6 | n = len(nums) 7 | if n <= 4: 8 | return 0 9 | else: 10 | nums.sort() 11 | minimum_diff = float('inf') 12 | for remove_at_beginning in range(4): 13 | minimum_diff = min(minimum_diff, nums[n - 4 + remove_at_beginning] - nums[remove_at_beginning]) 14 | return minimum_diff 15 | -------------------------------------------------------------------------------- /leetcode/_397_IntegerReplacement.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/19/2022 5 | **/ 6 | public class _397_IntegerReplacement { 7 | public int integerReplacement(int n) { 8 | return (int) findMinOperation(n); 9 | } 10 | 11 | private long findMinOperation(long n) { 12 | if (n == 1) 13 | return 0; 14 | else if ((n & 1) == 0) { 15 | return 1 + findMinOperation(n >> 1); 16 | } else return 1 + Math.min(findMinOperation(n + 1), findMinOperation(n - 1)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /uva online judge/10940 - Throwing cards away II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int fun(int n){ 5 | if(n ==1)return 1; 6 | else if(n%2==0)return (2*fun(n/2)-1); 7 | else return (2*fun(n/2)+1); 8 | } 9 | int main() 10 | { 11 | int n,m; 12 | cin>>n; 13 | while(n>0){ 14 | if(n==1){cout<<1<>n;continue;} 15 | m = fun(n); 16 | 17 | if(m == 1)cout<>n; 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /uva online judge/12279-Emoogle Balance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n,x[1000],testcase,count,i; 8 | testcase=1; 9 | scanf("%d",&n); 10 | while(n>0) 11 | { 12 | count=0; 13 | for(i=0;i None: 6 | """ 7 | Do not return anything, modify nums in-place instead. 8 | """ 9 | n = len(nums) 10 | k %= n 11 | 12 | def reverse(a, b): 13 | while a < b: 14 | nums[a], nums[b] = nums[b], nums[a] 15 | a += 1 16 | b -= 1 17 | 18 | reverse(0, n - 1) 19 | reverse(0, k - 1) 20 | reverse(k, n - 1) 21 | -------------------------------------------------------------------------------- /leetcode/280. Wiggle Sort.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def wiggleSort(self, nums: List[int]) -> None: 6 | """ 7 | Do not return anything, modify nums in-place instead. 8 | """ 9 | for i in range(1, len(nums)): 10 | if i & 1: 11 | if nums[i - 1] > nums[i]: 12 | nums[i - 1], nums[i] = nums[i], nums[i - 1] 13 | else: 14 | if nums[i - 1] < nums[i]: 15 | nums[i - 1], nums[i] = nums[i], nums[i - 1] 16 | 17 | -------------------------------------------------------------------------------- /leetcode/_1277_CountSquareSubmatricesWithAllOnes.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def countSquares(self, matrix: List[List[int]]) -> int: 6 | R, C = len(matrix), len(matrix[0]) 7 | ones_square = 0 8 | for r in range(0, R): 9 | for c in range(0, C): 10 | if r != 0 and c != 0 and matrix[r][c] != 0: 11 | matrix[r][c] = min(matrix[r - 1][c], matrix[r][c - 1], matrix[r - 1][c - 1]) + 1 12 | ones_square += matrix[r][c] 13 | return ones_square 14 | -------------------------------------------------------------------------------- /leetcode/_2135_CountWordsObtainedAfterAddingALetter.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: 6 | start_word_set = {frozenset(w) for w in startWords} 7 | match_count = 0 8 | for tw in targetWords: 9 | for i in range(len(tw)): 10 | psw = tw[:i] + tw[i + 1:] 11 | if frozenset(psw) in start_word_set: 12 | match_count += 1 13 | break 14 | return match_count 15 | -------------------------------------------------------------------------------- /leetcode/_287_FindTheDuplicateNumber.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/5/2022 5 | **/ 6 | public class _287_FindTheDuplicateNumber { 7 | 8 | public int findDuplicate(int[] nums) { 9 | int t, h; 10 | t = h = nums[0]; 11 | while (true){ 12 | t = nums[nums[t]]; 13 | h = nums[h]; 14 | if (t == h)break; 15 | } 16 | 17 | t = nums[0]; 18 | while (t != h){ 19 | t = nums[t]; 20 | h = nums[h]; 21 | } 22 | return h; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /uva online judge/10302 - Summation of Polynomials JAVA.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.math.BigInteger;; 3 | public class Main { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | Scanner sc = new Scanner(System.in); 11 | BigInteger n; 12 | while(sc.hasNextBigInteger()){ 13 | n = sc.nextBigInteger(); 14 | n = n.multiply(n.add(BigInteger.ONE)).divide(BigInteger.valueOf(2)); 15 | System.out.println(n.multiply(n)); 16 | } 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/1650. Lowest Common Ancestor of a Binary Tree III.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left = None 7 | self.right = None 8 | self.parent = None 9 | """ 10 | 11 | 12 | class Solution: 13 | def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node': 14 | path = set() 15 | while p: 16 | path.add(p) 17 | p = p.parent 18 | while q not in path: 19 | q = q.parent 20 | return q 21 | 22 | -------------------------------------------------------------------------------- /leetcode/_116_PopulatingNextRightPointersInEachNode.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/23/2022 5 | **/ 6 | public class _116_PopulatingNextRightPointersInEachNode { 7 | public Node connect(Node root) { 8 | if (root == null || root.left == null) 9 | return root; 10 | root.left.next = root.right; 11 | if (root.next != null) { 12 | root.right.next = root.next.left; 13 | } 14 | connect(root.left); 15 | connect(root.right); 16 | return root; 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/_846_HandOfStraights.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: 7 | hand.sort() 8 | s = Counter(hand) 9 | for v in hand: 10 | if s[v] > 0: 11 | ck = 0 12 | while ck < groupSize and s[v + ck] > 0: 13 | s[v + ck] -= 1 14 | ck += 1 15 | if ck < groupSize: 16 | return False 17 | return True 18 | -------------------------------------------------------------------------------- /lightoj/1225 - Palindromic Numbers (II).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() { 8 | int TC,tc=1; 9 | string str,rev; 10 | cin >> TC; 11 | 12 | while(tc<=TC) { 13 | cin >>str; 14 | 15 | rev = str; 16 | reverse(rev.begin(),rev.end()); 17 | if(str==rev) { 18 | cout << "Case "< 2 | #include 3 | 4 | int main() 5 | { 6 | int test,cs=0; 7 | long long int a,b,c; 8 | scanf("%d",&test); 9 | while(test--){ 10 | 11 | scanf("%lld %lld %lld",&a,&b,&c); 12 | printf("Case %d: ",++cs); 13 | if(a+b<=c||b+c<=a||c+a<=b)printf("Invalid\n"); 14 | else if(a==b&&b==c)printf("Equilateral\n"); 15 | else if(a==b||b==c||c==a)printf("Isosceles\n"); 16 | else printf("Scalene\n"); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/120. Triangle.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minimumTotal(self, triangle: List[List[int]]) -> int: 6 | mp = [[0] * len(triangle[r]) for r in range(len(triangle))] 7 | 8 | mp[0][:] = triangle[0][:] 9 | for r in range(1, len(triangle)): 10 | for c in range(len(triangle[r])): 11 | mp[r][c] = min(mp[r - 1][c] if c < len(triangle[r - 1]) else float('inf'), 12 | mp[r - 1][c - 1] if c > 0 else float('inf')) + triangle[r][c] 13 | return min(mp[-1]) -------------------------------------------------------------------------------- /leetcode/_1296_DivideArrayInSetsOfKConsecutiveNumbers.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from collections import Counter 3 | 4 | 5 | class Solution: 6 | def isPossibleDivide(self, nums: List[int], k: int) -> bool: 7 | s = Counter(nums) 8 | nums.sort() 9 | for v in nums: 10 | if s[v] > 0: 11 | ck = 0 12 | while ck < k and s[v + ck] > 0: 13 | s[v + ck] -= 1 14 | ck += 1 15 | if ck < k: 16 | return False 17 | return True 18 | -------------------------------------------------------------------------------- /leetcode/1004. Max Consecutive Ones III.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import collections 3 | 4 | 5 | class Solution: 6 | def longestOnes(self, nums: List[int], k: int) -> int: 7 | left = 0 8 | right = 0 9 | ans = 0 10 | zq = collections.deque() 11 | while right < len(nums): 12 | if nums[right] == 0: 13 | zq.append(right) 14 | if len(zq) > k: 15 | left = zq.popleft() + 1 16 | right += 1 17 | ans = max(ans, right - left) 18 | return ans 19 | -------------------------------------------------------------------------------- /leetcode/974. Subarray Sums Divisible by K.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def subarraysDivByK(self, nums: List[int], k: int) -> int: 7 | frequency = Counter() 8 | prefix_sum = 0 9 | count = 0 10 | for v in nums: 11 | prefix_sum += v 12 | if prefix_sum % k == 0: 13 | count += 1 14 | prefix_sum %= k 15 | 16 | count += frequency[prefix_sum] 17 | 18 | frequency[prefix_sum] += 1 19 | return count 20 | -------------------------------------------------------------------------------- /leetcode/_2208_MinimumOperationsToHalveArraySum.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def halveArray(self, nums: List[int]) -> int: 7 | pq = [] 8 | for v in nums: 9 | heappush(pq, -v) 10 | half = sum(nums) / 2 11 | removed = 0 12 | min_operation = 0 13 | while removed < half: 14 | h = heappop(pq) / 2 15 | removed = removed - h 16 | heappush(pq, h) 17 | min_operation += 1 18 | return min_operation 19 | -------------------------------------------------------------------------------- /leetcode/_539_MinimumTimeDifference.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findMinDifference(self, timePoints: List[str]) -> int: 6 | minute_seq = [int(hhmm[:2]) * 60 + int(hhmm[3:]) for 7 | hhmm in timePoints] 8 | minute_seq.sort() 9 | minute_seq.append(minute_seq[0] + 1440) 10 | min_dif = float('inf') 11 | for i in range(len(minute_seq) - 1): 12 | min_dif = min(min_dif, minute_seq[i + 1] - minute_seq[i], 1440 + minute_seq[i] - minute_seq[i + 1]) 13 | return min_dif 14 | -------------------------------------------------------------------------------- /leetcode/_825_FriendsOfAppropriateAges.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def numFriendRequests(self, ages: List[int]) -> int: 7 | age_group = collections.Counter(ages) 8 | friend_request = 0 9 | for x, xn in age_group.items(): 10 | for y, yn in age_group.items(): 11 | if not (y <= 0.5 * x + 7 or y > x): 12 | friend_request += xn * yn 13 | if x == y: 14 | friend_request -= xn 15 | return friend_request 16 | -------------------------------------------------------------------------------- /spoj/24. Small factorials.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.math.BigInteger; 3 | public class Main{ 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n,test,cs=1; 7 | test = sc.nextInt(); 8 | while(test>=cs){ 9 | n = sc.nextInt(); 10 | 11 | BigInteger factorial = BigInteger.ONE; 12 | 13 | for (int i=1; i<=n; i++) { 14 | factorial = factorial.multiply(BigInteger.valueOf(i)); 15 | } 16 | System.out.println(factorial); 17 | cs=cs+1; 18 | } 19 | 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/279. Perfect Squares.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | def numSquares(self, n: int) -> int: 6 | squared = [] 7 | i = 1 8 | while i * i <= n: 9 | squared.append(i * i) 10 | i += 1 11 | 12 | dp = [n] * (n + 1) 13 | dp[0] = 0 14 | for val in range(1, n + 1): 15 | for x in squared: 16 | if x > val: 17 | break 18 | else: 19 | dp[val] = min(dp[val], dp[val - x] + 1) 20 | return dp[n] -------------------------------------------------------------------------------- /leetcode/354. Russian Doll Envelopes.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import bisect 3 | class Solution: 4 | def maxEnvelopes(self, envelopes: List[List[int]]) -> int: 5 | envelopes.sort(key = lambda x : (x[0], -x[1])) 6 | dp = [] 7 | lis = 0 8 | for (a, b) in envelopes: 9 | insertion_index = bisect.bisect_left(dp, b) 10 | if insertion_index == len(dp): 11 | dp.append(b) 12 | else: 13 | dp[insertion_index] = b 14 | lis = max(lis, insertion_index + 1) 15 | return lis -------------------------------------------------------------------------------- /leetcode/581. Shortest Unsorted Continuous Subarray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findUnsortedSubarray(self, nums: List[int]) -> int: 6 | sorted_nums = nums[:] 7 | sorted_nums.sort() 8 | i = 0 9 | j = len(nums) - 1 10 | while i <= j: 11 | if nums[i] == sorted_nums[i]: 12 | i += 1 13 | elif nums[j] == sorted_nums[j]: 14 | j -= 1 15 | else: 16 | break 17 | else: 18 | return 0 19 | return j - i + 1 20 | -------------------------------------------------------------------------------- /leetcode/_198_HouseRobber.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def rob(self, nums: List[int]) -> int: 7 | @lru_cache 8 | def fin_max(s, including): 9 | if s >= len(nums): 10 | return 0 11 | else: 12 | if including: 13 | return nums[s] + fin_max(s + 1, False) 14 | else: 15 | return max(fin_max(s + 1, True), fin_max(s + 1, False)) 16 | 17 | return max(fin_max(0, True), fin_max(0, False)) 18 | -------------------------------------------------------------------------------- /uva online judge/674 - Coin Change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef unsigned long long u64; 7 | int coin[] = {0000, 1, 5, 10, 25 , 50}; 8 | u64 C[7489+10]; 9 | int W; 10 | u64 countWays(){ 11 | for(int i = 1; i <= W; i++)C[i] = 0; 12 | C[0] = 1; 13 | for(int i = 1; i <= 5; i++) 14 | for(int j = coin[i]; j <= W; j++) 15 | C[j] = C[j] + C[j - coin[i]]; 16 | return C[W]; 17 | } 18 | int main() 19 | { 20 | while(scanf("%d", &W)==1)printf("%llu\n", countWays()); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/582. Kill Process.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: 7 | g = collections.defaultdict(set) 8 | for u, v in zip(ppid, pid): 9 | g[u].add(v) 10 | 11 | killed_process = [] 12 | 13 | def kill_process(u, killed): 14 | killed.append(u) 15 | for v in g[u]: 16 | kill_process(v, killed) 17 | 18 | kill_process(kill, killed_process) 19 | return killed_process 20 | -------------------------------------------------------------------------------- /leetcode/_1053_PreviousPermutationWithOneSwap.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def prevPermOpt1(self, arr: List[int]) -> List[int]: 6 | for i in range(len(arr) - 2, -1, -1): 7 | if arr[i] > arr[i + 1]: 8 | max_val_index = i + 1 9 | for k in range(i + 1, len(arr)): 10 | if arr[max_val_index] < arr[k] < arr[i]: 11 | max_val_index = k 12 | arr[i], arr[max_val_index] = arr[max_val_index], arr[i] 13 | return arr 14 | return arr 15 | -------------------------------------------------------------------------------- /uva online judge/10451 - Ancient Village Sports.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | double n,area,rin,rout,pi,rinsqure; 9 | int t = 1; 10 | pi =2*acos(0); 11 | while(1){ 12 | scanf("%lf%lf",&n,&area); 13 | if(n<3)break; 14 | rinsqure =area/(n*tan(pi/n)); 15 | rin =sqrt(rinsqure); 16 | rout = rin /cos(pi/n); 17 | printf("Case %d: %.5lf %.5lf\n",t,(pi*rout*rout-area),(area-pi*rin*rin)); 18 | t++; 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/_215_KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Comparator; 3 | import java.util.PriorityQueue; 4 | 5 | /** 6 | * @author Shahidul Islam 7 | * @date 2/13/2022 8 | **/ 9 | public class _215_KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); 12 | for (int num : nums) { 13 | pq.offer(num); 14 | } 15 | for (int i = 0; i < k - 1; i++) 16 | pq.poll(); 17 | return pq.peek(); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/_217_ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | /** 6 | * @author Shahidul Islam 7 | * @date 1/23/2022 8 | **/ 9 | public class _217_ContainsDuplicate { 10 | public boolean containsDuplicate(int[] nums) { 11 | Map countMap = new HashMap<>(); 12 | for (int x : nums) { 13 | if (countMap.containsKey(x)) { 14 | return true; 15 | } else { 16 | countMap.put(x, x); 17 | } 18 | } 19 | return false; 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/_670_MaximumSwap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumSwap(self, num: int) -> int: 3 | digits = [d for d in str(num)] 4 | for i in range(len(digits) - 1): 5 | max_digit_index = i 6 | for k in range(i + 1, len(digits)): 7 | if digits[max_digit_index] <= digits[k]: 8 | max_digit_index = k 9 | if digits[max_digit_index] > digits[i]: 10 | digits[i], digits[max_digit_index] = digits[max_digit_index], digits[i] 11 | return int(''.join(digits)) 12 | return num 13 | -------------------------------------------------------------------------------- /uva online judge/10931-party.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int i,k,n; 7 | int ar[64]; 8 | 9 | while(1){ 10 | cin>>i; 11 | if(i==0)break; 12 | n=0; 13 | for(k=0;i>0;k++){ 14 | ar[k]=i%2; 15 | if(ar[k]==1)n++; 16 | i=i/2; 17 | } 18 | cout<<"The parity of "; 19 | for(k=k-1;k>=0;k--)printf("%d",ar[k]); 20 | cout<<" is "< int: 7 | frequency = Counter(nums) 8 | max_ops = 0 9 | for x in nums: 10 | y = k - x 11 | fx = frequency[x] 12 | fy = frequency[y] 13 | if (x != y and (fx > 0 and fy > 0)) or (x == y and fx > 1): 14 | frequency[x] -= 1 15 | frequency[y] -= 1 16 | max_ops += 1 17 | return max_ops 18 | -------------------------------------------------------------------------------- /leetcode/841. Keys and Rooms.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 7 | visited = set() 8 | cq = deque([0]) 9 | while cq: 10 | if len(visited) == len(rooms): 11 | return True 12 | rn = cq.popleft() 13 | if rn not in visited: 14 | visited.add(rn) 15 | for k in rooms[rn]: 16 | cq.append(k) 17 | return len(rooms) == len(visited) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /leetcode/2171. Removing Minimum Number of Magic Beans.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minimumRemoval(self, beans: List[int]) -> int: 6 | n = len(beans) 7 | beans.sort() 8 | prefix_total = min_operations = sum(beans) 9 | suffix_total = 0 10 | for index in range(n - 1, -1, -1): 11 | val = beans[index] 12 | prefix_total -= val 13 | suffix_total += val 14 | min_operations = min(suffix_total - (n - index) * val + prefix_total, min_operations) 15 | return min_operations 16 | 17 | -------------------------------------------------------------------------------- /leetcode/424. Longest Repeating Character Replacement.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Solution: 5 | def characterReplacement(self, s: str, k: int) -> int: 6 | fc = collections.defaultdict(int) 7 | left = right = ans = 0 8 | while right < len(s): 9 | rch = s[right] 10 | fc[rch] += 1 11 | while (right - left + 1 - max(fc.values())) > k: 12 | lch = s[left] 13 | fc[lch] -= 1 14 | left += 1 15 | ans = max(ans, right - left + 1) 16 | right += 1 17 | return ans -------------------------------------------------------------------------------- /leetcode/60. Permutation Sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getPermutation(self, n: int, k: int) -> str: 3 | factorial = [1] 4 | sequence = [str(i) for i in range(1, n+1)] 5 | for i in range(1, n): 6 | factorial.append(i * factorial[i-1]) 7 | permuation = [] 8 | k -= 1 9 | for i in range(n-1, -1, -1): 10 | digit_index = k // factorial[i] 11 | k -= digit_index * factorial[i] 12 | permuation.append(sequence[digit_index]) 13 | del sequence[digit_index] 14 | return ''.join(permuation) 15 | -------------------------------------------------------------------------------- /uva online judge/11879 - Multiple of 17.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import static java.math.BigInteger.*; 3 | import java.util.Scanner; 4 | public class Main { 5 | 6 | /** 7 | * @param args 8 | */ 9 | public static void main(String[] args) { 10 | // TODO Auto-generated method stub 11 | Scanner sc = new Scanner(System.in); 12 | BigInteger n ,d17; 13 | d17 = TEN.add(valueOf(7)); 14 | while(true){ 15 | n = sc.nextBigInteger(); 16 | if(n.equals(ZERO))break; 17 | if(n.mod(d17)==ZERO)System.out.println(1); 18 | else System.out.println(0); 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/1492. The kth Factor of n.py: -------------------------------------------------------------------------------- 1 | import math 2 | from heapq import heappush, heappop 3 | 4 | 5 | class Solution: 6 | def kthFactor(self, n: int, k: int) -> int: 7 | hq = [] 8 | for i in range(1, math.floor(math.sqrt(n)) + 1): 9 | if n % i == 0: 10 | heappush(hq, -i) 11 | cmp = n // i 12 | if cmp != i: 13 | heappush(hq, -cmp) 14 | while len(hq) > k: 15 | heappop(hq) 16 | if len(hq) < k: 17 | return -1 18 | else: 19 | return hq[0] * -1 20 | -------------------------------------------------------------------------------- /leetcode/1387. Sort Integers by The Power Value.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getKth(self, lo: int, hi: int, k: int) -> int: 3 | dp = {1: 0} 4 | 5 | def find_power(x) -> int: 6 | if x not in dp: 7 | if x & 1: 8 | dp[x] = 1 + find_power(3 * x + 1) 9 | else: 10 | dp[x] = 1 + find_power(x // 2) 11 | return dp[x] 12 | 13 | powers = [] 14 | for x in range(lo, hi + 1): 15 | powers.append([find_power(x), x]) 16 | powers.sort() 17 | return powers[k - 1][1] 18 | 19 | -------------------------------------------------------------------------------- /leetcode/2125. Number of Laser Beams in a Bank.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numberOfBeams(self, bank: List[str]) -> int: 6 | security_devices = [row.count('1') for row in bank] 7 | 8 | lager_count = 0 9 | for r1 in range(len(security_devices)): 10 | for r2 in range(r1 + 1, len(security_devices)): 11 | n1 = security_devices[r1] 12 | n2 = security_devices[r2] 13 | if n2 > 0: 14 | lager_count += (n1 * n2) 15 | break 16 | return lager_count 17 | 18 | -------------------------------------------------------------------------------- /leetcode/259. 3Sum Smaller.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def threeSumSmaller(self, nums: List[int], target: int) -> int: 6 | nums.sort() 7 | n = len(nums) 8 | triplets = 0 9 | for i in range(n - 2): 10 | left = i + 1 11 | right = n - 1 12 | while left < right: 13 | if nums[i] + nums[left] + nums[right] < target: 14 | triplets += right - left 15 | left += 1 16 | else: 17 | right -= 1 18 | return triplets 19 | 20 | -------------------------------------------------------------------------------- /leetcode/264. Ugly Number II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.ugly_nums = [] 4 | heap = [1] 5 | seen = {1} 6 | while len(self.ugly_nums) < 1690: 7 | ugly_one = heappop(heap) 8 | self.ugly_nums.append(ugly_one) 9 | for factor in [2, 3, 5]: 10 | next_one = ugly_one * factor 11 | if next_one not in seen: 12 | seen.add(next_one) 13 | heappush(heap, next_one) 14 | 15 | def nthUglyNumber(self, n: int) -> int: 16 | return self.ugly_nums[n - 1] 17 | -------------------------------------------------------------------------------- /leetcode/633. Sum of Square Numbers.py: -------------------------------------------------------------------------------- 1 | from math import ceil, sqrt 2 | 3 | 4 | class Solution: 5 | def judgeSquareSum(self, c: int) -> bool: 6 | squared = set() 7 | squared_seq = [] 8 | for n in range(0, ceil(sqrt((1 << 31) - 1))): 9 | v = n * n 10 | squared.add(v) 11 | squared_seq.append(v) 12 | for a_squared in squared_seq: 13 | if a_squared <= c: 14 | if (c - a_squared) in squared: 15 | return True 16 | else: 17 | return False 18 | return False 19 | 20 | -------------------------------------------------------------------------------- /leetcode/665. Non-decreasing Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def checkPossibility(self, nums: List[int]) -> bool: 6 | anomaly_count = 0 7 | max_val = nums[0] 8 | for i in range(len(nums) - 1): 9 | if nums[i + 1] < nums[i]: 10 | anomaly_count += 1 11 | if i == 0 or nums[i - 1] <= nums[i + 1]: 12 | nums[i] = nums[i + 1] 13 | else: 14 | nums[i + 1] = nums[i] 15 | if anomaly_count > 1: 16 | return False 17 | return True 18 | -------------------------------------------------------------------------------- /leetcode/Same Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | 12 | class Solution { 13 | public: 14 | bool isSameTree(TreeNode *p, TreeNode *q) { 15 | if(p == NULL && q == NULL) return true; 16 | if(p == NULL || q == NULL) return false; 17 | if(p->val != q->val) return false; 18 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /leetcode/_26_RemoveDuplicateFromSortedArray.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | class _26_RemoveDuplicateFromSortedArray { 5 | public int removeDuplicates(int[] nums) { 6 | int n; 7 | if (nums.length > 0){ 8 | n = 1; 9 | int val; 10 | for (int i = 1; i < nums.length;i++){ 11 | val = nums[i]; 12 | if (Arrays.binarySearch(nums, 0, n, val) < 0){ 13 | nums[n++] = val; 14 | } 15 | } 16 | }else { 17 | n = 0; 18 | } 19 | return n; 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/881. Boats to Save People.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numRescueBoats(self, people: List[int], limit: int) -> int: 6 | people.sort() 7 | l = 0 8 | r = len(people) - 1 9 | boats = 0 10 | while l <= r: 11 | if l == r: 12 | l += 1 13 | r -= 1 14 | else: 15 | if people[l] + people[r] <= limit: 16 | l += 1 17 | r -= 1 18 | else: 19 | r -= 1 20 | boats += 1 21 | return boats -------------------------------------------------------------------------------- /leetcode/_303_RangeSumQuery.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/23/2022 5 | **/ 6 | 7 | class _303_RangeSumQuery { 8 | 9 | private int sum[]; 10 | 11 | public _303_RangeSumQuery(int[] nums) { 12 | sum = new int[nums.length]; 13 | sum[0] = nums[0]; 14 | for (int i = 1; i < nums.length; i++) { 15 | sum[i] = sum[i - 1] + nums[i]; 16 | } 17 | } 18 | 19 | public int sumRange(int left, int right) { 20 | if (left == 0) { 21 | return sum[right]; 22 | } else return sum[right] - sum[left - 1]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /lightoj/1178 - Trapezium.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() { 8 | //freopen("input.txt","r",stdin); 9 | double h,area,a,b,c,d,s,x, triangleArea; 10 | int test,cs=1; 11 | cin >> test; 12 | while(test--) { 13 | cin >> a >> b >> c >> d; 14 | x = fabs(a - c); 15 | s = 0.5*(x+b+d); 16 | triangleArea = sqrt(s*(s-x)*(s-b)*(s-d)); 17 | h = (triangleArea*2)/x; 18 | printf("Case %d: %.10lf\n",cs++,(0.5*(a+c)*h)); 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/362. Design Hit Counter.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | 4 | class HitCounter: 5 | 6 | def __init__(self): 7 | self.ht = [] 8 | 9 | def hit(self, timestamp: int) -> None: 10 | self.ht.append(timestamp) 11 | 12 | def getHits(self, timestamp: int) -> int: 13 | ht = self.ht 14 | left = bisect.bisect_left(ht, timestamp - 300 + 1) 15 | right = bisect.bisect_right(ht, timestamp) 16 | return right - left 17 | 18 | # Your HitCounter object will be instantiated and called as such: 19 | # obj = HitCounter() 20 | # obj.hit(timestamp) 21 | # param_2 = obj.getHits(timestamp) -------------------------------------------------------------------------------- /leetcode/Merge Sorted Array.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | void merge(int A[], int m, int B[], int n) { 9 | int C[m]; 10 | for(int i = 0; i < m; i++) 11 | C[i]= A[i]; 12 | int pos = 0, i = 0, j=0; 13 | 14 | while(i < m || j < n){ 15 | if(i==m) A[pos++] = B[j++]; 16 | else if(j == n) A[pos++] = C[i++]; 17 | else if(C[i] < B[j]) 18 | A[pos++] = C[i++]; 19 | else A[pos++] = B[j++]; 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/_1381_DesignAStackWithIncrementOperation.py: -------------------------------------------------------------------------------- 1 | class CustomStack: 2 | 3 | def __init__(self, maxSize: int): 4 | self.stack = [] 5 | self.maxSize = maxSize 6 | 7 | def push(self, x: int) -> None: 8 | if self.maxSize > len(self.stack): 9 | self.stack.append(x) 10 | 11 | def pop(self) -> int: 12 | if len(self.stack) > 0: 13 | return self.stack.pop() 14 | else: 15 | return -1 16 | 17 | def increment(self, k: int, val: int) -> None: 18 | for i in range(min(k, len(self.stack))): 19 | self.stack[i] += val 20 | -------------------------------------------------------------------------------- /leetcode/_1962_RemoveStonesToMinimizeTheTotal.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from math import floor 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | def minStoneSum(self, piles: List[int], k: int) -> int: 8 | pq = [] 9 | for s in piles: 10 | heappush(pq, -s) 11 | removed_piles = 0 12 | while pq[-1] < -1 and k > 0: 13 | s = -1 * heappop(pq) 14 | removed = floor(s / 2) 15 | removed_piles += removed 16 | heappush(pq, -(s - removed)) 17 | k -= 1 18 | return sum(piles) - removed_piles 19 | -------------------------------------------------------------------------------- /uva online judge/10929 - You can say 11.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int len,i,c,s; 9 | string str; 10 | while(true){ 11 | cin>>str; 12 | len = str.length(); 13 | if(str.at(0)=='0'&&len==1)break; 14 | c = 0; 15 | for(i = 0;i int: 6 | start = 0 7 | sub_arrays = 0 8 | group = 0 9 | for i, v in enumerate(nums): 10 | sub_arrays += group 11 | if left <= v <= right: 12 | group = (i - start + 1) 13 | else: 14 | if v > right: 15 | start = i + 1 16 | group = 0 17 | sub_arrays += group 18 | return sub_arrays 19 | 20 | -------------------------------------------------------------------------------- /leetcode/1506. Find Root of N-Ary Tree.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Node: 5 | def __init__(self, val=None, children=None): 6 | self.val = val 7 | self.children = children if children is not None else [] 8 | 9 | class Solution: 10 | def findRoot(self, tree: List['Node']) -> 'Node': 11 | root_value = 0 12 | for node in tree: 13 | root_value ^= node.val 14 | for child in node.children: 15 | root_value ^= child.val 16 | for node in tree: 17 | if node.val == root_value: 18 | return node 19 | return None -------------------------------------------------------------------------------- /leetcode/2134. Minimum Swaps to Group All 1's Together II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minSwaps(self, nums: List[int]) -> int: 6 | n = len(nums) 7 | window_sz = sum(nums) 8 | right = 0 9 | running_ones = 0 10 | ans = window_sz 11 | while right < n + window_sz - 1: 12 | running_ones += nums[right % n] 13 | right += 1 14 | 15 | if right >= window_sz: 16 | ans = min(ans, window_sz - running_ones) 17 | running_ones -= nums[right - window_sz] 18 | return ans 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /leetcode/540. Single Element in a Sorted Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def singleNonDuplicate(self, nums: List[int]) -> int: 6 | n = len(nums) 7 | low = 0 8 | high = n 9 | while low + 1 < high: 10 | cn = high - low 11 | half = cn // 2 12 | if half % 2 == 1: 13 | half += 1 14 | # print(low, high, cn, half) 15 | if nums[low + half - 2] == nums[low + half - 1]: 16 | low = low + half 17 | else: 18 | high = low + half - 1 19 | return nums[low] 20 | -------------------------------------------------------------------------------- /leetcode/852. Peak Index in a Mountain Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def peakIndexInMountainArray(self, arr: List[int]) -> int: 6 | 7 | def find_peak(left: int, right: int) -> int: 8 | mid = (left + right) // 2 9 | if mid - 1 >= 0 and mid + 1 < len(arr): 10 | if arr[mid - 1] < arr[mid] < arr[mid + 1]: 11 | return find_peak(mid, right) 12 | elif arr[mid - 1] > arr[mid] > arr[mid + 1]: 13 | return find_peak(left, mid) 14 | return mid 15 | 16 | return find_peak(0, len(arr) - 1) -------------------------------------------------------------------------------- /leetcode/_338_CountBits.java: -------------------------------------------------------------------------------- 1 | 2 | class _338_CountBits { 3 | static int[] bits = new int[100002]; 4 | 5 | static { 6 | for (int i = 0; i < 100002; i++) { 7 | int cnt = 0; 8 | for (int k = 0; k < 30; k++) { 9 | if (((1 << k) & i) != 0) { 10 | cnt++; 11 | } 12 | } 13 | bits[i] = cnt; 14 | } 15 | } 16 | 17 | public int[] countBits(int n) { 18 | int[] x = new int[n + 1]; 19 | for (int i = 0; i < n + 1; i++) { 20 | x[i] = bits[i]; 21 | } 22 | return x; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/_62_UniquePaths.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/27/2022 5 | **/ 6 | public class _62_UniquePaths { 7 | public int uniquePaths(int m, int n) { 8 | int[][] dp = new int[m][n]; 9 | for (int r = 0; r < m; r++) { 10 | dp[r][0] = 1; 11 | } 12 | for (int c = 0; c < n; c++) { 13 | dp[0][c] = 1; 14 | } 15 | for (int r = 1; r < m; r++) { 16 | for (int c = 1; c < n; c++) { 17 | dp[r][c] = dp[r][c - 1] + dp[r - 1][c]; 18 | } 19 | } 20 | return dp[m - 1][n - 1]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxNonOverlapping(self, nums: List[int], target: int) -> int: 6 | prefix_map = {0: -1} 7 | prefix = 0 8 | last_index = -1 9 | arrays = 0 10 | for i, v in enumerate(nums): 11 | prefix += v 12 | left_val = prefix - target 13 | if left_val in prefix_map and prefix_map[left_val] >= last_index: 14 | arrays += 1 15 | last_index = i 16 | prefix_map[prefix] = i 17 | return arrays 18 | -------------------------------------------------------------------------------- /leetcode/1698. Number of Distinct Substrings in a String.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self): 3 | self.child = [None] * 26 4 | class Solution: 5 | def countDistinct(self, s: str) -> int: 6 | n = len(s) 7 | root = Node() 8 | words = 0 9 | for i in range(n): 10 | node = root 11 | for j in range(i, n): 12 | ch = s[j] 13 | index = ord(ch) - ord('a') 14 | if not node.child[index]: 15 | node.child[index] = Node() 16 | words += 1 17 | node = node.child[index] 18 | return words -------------------------------------------------------------------------------- /leetcode/373. Find K Pairs with Smallest Sums.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: 7 | pq = [] 8 | for i in range(len(nums1)): 9 | heappush(pq, [nums1[i] + nums2[0], i, 0]) 10 | smp = [] 11 | while k > 0 and pq: 12 | _, i, j = heappop(pq) 13 | smp.append([nums1[i], nums2[j]]) 14 | if j + 1 < len(nums2): 15 | heappush(pq, [nums1[i] + nums2[j+1], i, j + 1]) 16 | k -= 1 17 | return smp -------------------------------------------------------------------------------- /leetcode/_1272_RemoveInterval.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: 6 | left_out_intervals = [] 7 | c, d = toBeRemoved 8 | for a, b in intervals: 9 | if b > c and d > a: 10 | x, y = a, c 11 | if a < c: 12 | left_out_intervals.append([a, c]) 13 | if d < b: 14 | left_out_intervals.append([d, b]) 15 | else: 16 | left_out_intervals.append([a, b]) 17 | return left_out_intervals 18 | -------------------------------------------------------------------------------- /leetcode/_1472_DesignBrowserHistory.py: -------------------------------------------------------------------------------- 1 | class BrowserHistory: 2 | 3 | def __init__(self, homepage: str): 4 | self.history = [None] * 5001 5 | self.total = 0 6 | self.n = 0 7 | self.visit(homepage) 8 | 9 | def visit(self, url: str) -> None: 10 | self.history[self.n] = url 11 | self.n = self.total = self.n + 1 12 | 13 | def back(self, steps: int) -> str: 14 | self.n = max(1, self.n - steps) 15 | return self.history[self.n - 1] 16 | 17 | def forward(self, steps: int) -> str: 18 | self.n = min(self.total, self.n + steps) 19 | return self.history[self.n - 1] 20 | -------------------------------------------------------------------------------- /leetcode/_14_LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | 2 | class _14_LongestCommonPrefix { 3 | public String longestCommonPrefix(String[] strs) { 4 | int prefixLength = 0; 5 | char ch; 6 | 7 | String text = strs[0]; 8 | for (int i = 0; i < text.length(); i++) { 9 | ch = text.charAt(i); 10 | int j = 1; 11 | for (j = 1; j < strs.length && prefixLength < strs[j].length() && strs[j].charAt(prefixLength) == ch; j++) { 12 | } 13 | if (j != strs.length) break; 14 | else prefixLength++; 15 | } 16 | return text.substring(0, prefixLength); 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/_275_HIndexII.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/11/2022 5 | **/ 6 | public class _275_HIndexII { 7 | public int hIndex(int[] citations) { 8 | int hIndex = 0; 9 | int lo = 0; 10 | int n = citations.length; 11 | int hi = n - 1; 12 | while (lo <= hi) { 13 | int mid = (lo + hi) / 2; 14 | if (citations[mid] >= n - mid) { 15 | hIndex = Math.max(hIndex, n - mid); 16 | hi = mid - 1; 17 | } else { 18 | lo = mid + 1; 19 | } 20 | } 21 | return hIndex; 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/_986_IntervalListIntersections.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: 6 | i = j = 0 7 | intersection_list = [] 8 | while i < len(firstList) and j < len(secondList): 9 | a, b = firstList[i] 10 | c, d = secondList[j] 11 | if b >= c and d >= a: 12 | intersection_list.append([max(a, c), min(b, d)]) 13 | if b < d: 14 | i += 1 15 | else: 16 | j += 1 17 | return intersection_list 18 | -------------------------------------------------------------------------------- /leetcode/255. Verify Preorder Sequence in Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def verifyPreorder(self, preorder: List[int]) -> bool: 4 | index = 0 5 | 6 | def validate(left, right) -> bool: 7 | nonlocal index 8 | if index >= len(preorder): 9 | return True 10 | val = preorder[index] 11 | 12 | if left < val < right: 13 | index += 1 14 | return validate(left, val) or validate(val, right) 15 | else: 16 | return False 17 | 18 | return validate(float('-inf'), float('inf')) 19 | -------------------------------------------------------------------------------- /leetcode/_202_HappyNumber.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | class _202_HappyNumber { 6 | public boolean isHappy(int n) { 7 | Map track = new HashMap<>(); 8 | while (n != 1 ) { 9 | int s = 0; 10 | while (n != 0) { 11 | s += Math.pow(n % 10, 2); 12 | n = n / 10; 13 | } 14 | n = s; 15 | if(track.containsKey(n)){ 16 | break; 17 | } 18 | track.put(n, true); 19 | } 20 | 21 | if (n == 1) return true; 22 | else return false; 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/_78_Subsets.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | class _78_Subsets { 6 | public List> subsets(int[] nums) { 7 | List> powerSet = new ArrayList<>(); 8 | int n = nums.length; 9 | for (int i = 0; i < (1 << n); i++) { 10 | ArrayList subset = new ArrayList<>(); 11 | for (int k = 0; k < n; k++) { 12 | if (((1 << k) & i) != 0) { 13 | subset.add(nums[k]); 14 | } 15 | } 16 | powerSet.add(subset); 17 | } 18 | 19 | return powerSet; 20 | } 21 | } -------------------------------------------------------------------------------- /uva online judge/10370-Above Average.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int c,m,i,n,co,a[1000]; 7 | float s,ave,per; 8 | cin>>c; 9 | m=0; 10 | while(m>n; 13 | s=0; 14 | co=0; 15 | for(i=0;i>a[i]; 18 | s=s+a[i]; 19 | } 20 | ave=(float)s/n; 21 | for(i=0;iave)co++; 23 | per=(float)co*100/n; 24 | printf("%.3f",per); 25 | cout<<"%"< None: 6 | n = len(matrix) 7 | 8 | r = c = 0 9 | lr = lc = n - 1 10 | while r < lr: 11 | for d in range(lr - r): 12 | val = matrix[r][lc - d] 13 | matrix[r][lc - d] = matrix[r + d][c] 14 | matrix[r + d][c] = matrix[lr][c + d] 15 | matrix[lr][c + d] = matrix[lr - d][lc] 16 | matrix[lr - d][lc] = val 17 | lr -= 1 18 | lc -= 1 19 | r += 1 20 | c += 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode/64. Minimum Path Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minPathSum(self, grid: List[List[int]]) -> int: 6 | m, n = len(grid), len(grid[0]) 7 | dp = [0] * n 8 | for r in range(m): 9 | for c in range(n): 10 | val = grid[r][c] 11 | if r == 0 and c == 0: 12 | dp[c] = val 13 | elif r == 0: 14 | dp[c] = dp[c-1] + val 15 | elif c == 0: 16 | dp[c] = dp[c] + val 17 | else: 18 | dp[c] = min(dp[c-1], dp[c]) + val 19 | return dp[n-1] -------------------------------------------------------------------------------- /leetcode/_1481_LeastNumberOfUniqueIntegersAfterKRemovals.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Solution: 5 | def findLeastNumOfUniqueInts(self, arr: list[int], k: int) -> int: 6 | fc = collections.defaultdict(int) 7 | for key in arr: 8 | fc[key] = fc[key] + 1 9 | seq = list(fc.items()) 10 | seq.sort(key=lambda t: t[1]) 11 | i = 0 12 | while k > 0 and i < len(seq): 13 | numKey, f = seq[i] 14 | if f <= k: 15 | del fc[numKey] 16 | k -= f 17 | i += 1 18 | else: 19 | break 20 | return len(fc) 21 | -------------------------------------------------------------------------------- /leetcode/_384_ShuffleAnArray.py: -------------------------------------------------------------------------------- 1 | import random 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | 7 | def __init__(self, nums: List[int]): 8 | self.nums = nums 9 | self.originalCopy = nums.copy() 10 | 11 | def reset(self) -> List[int]: 12 | for i in range(len(self.nums)): 13 | self.nums[i] = self.originalCopy[i] 14 | return self.nums 15 | 16 | def shuffle(self) -> List[int]: 17 | n = len(self.nums) 18 | for i in range(n - 1, -1, -1): 19 | r = random.randint(0, i) 20 | self.nums[r], self.nums[i] = self.nums[i], self.nums[r] 21 | return self.nums 22 | -------------------------------------------------------------------------------- /leetcode/_939_MinimumAreaRectangle.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minAreaRect(self, points: List[List[int]]) -> int: 6 | N = len(points) 7 | point_set = {tuple(p) for p in points} 8 | min_area = float('inf') 9 | for i in range(N): 10 | for j in range(i + 1, N): 11 | x1, y1 = points[i] 12 | x2, y2 = points[j] 13 | if x1 != x2 and y1 != y2 and (x2, y1) in point_set and (x1, y2) in point_set: 14 | min_area = min(min_area, abs(x1 - x2) * abs(y1 - y2)) 15 | return min_area if min_area != float('inf') else 0 16 | -------------------------------------------------------------------------------- /uva online judge/100-The 3n+1 problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a,b,i,c,n,k; 8 | while(scanf("%d%d",&a,&b)==2){ 9 | cout<b){ 11 | a=a+b; 12 | b=a-b; 13 | a=a-b; 14 | } 15 | c=1; 16 | for(k=a;k<=b;k++){ 17 | n=k; 18 | for(i=1;n>1;i++) 19 | { 20 | if(n%2!=0)n=3*n+1; 21 | else n=n/2; 22 | } 23 | if(c int: 7 | mod = (10 ** 9 + 7) 8 | 9 | @lru_cache 10 | def partial(k) -> int: 11 | if k == 2: 12 | return 1 13 | else: 14 | return (full(k - 2) + partial(k - 1)) % mod 15 | 16 | @lru_cache(maxsize=None) 17 | def full(k) -> int: 18 | if k < 3: 19 | return k 20 | else: 21 | return (full(k - 1) + full(k - 2) + 2 * partial(k - 1)) % mod 22 | 23 | return full(n) 24 | -------------------------------------------------------------------------------- /uva online judge/575-Skew Binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | char ar[500]; 10 | int l,num,k; 11 | //freopen("input.txt","r",stdin); 12 | while(gets(ar)) 13 | { 14 | l=strlen(ar); 15 | if(ar[0]=='0'&&ar[1]==NULL)break; 16 | num=0; 17 | k=1; 18 | for(l=l-1;l>=0;l--) 19 | { 20 | num=num+(ar[l]-48)*(pow(2,k)-1); 21 | k++; 22 | } 23 | cout< windowMap; 6 | 7 | public _729_MyCalendarI() { 8 | this.windowMap = new TreeMap<>(); 9 | } 10 | 11 | public boolean book(int start, int end) { 12 | Integer floorKey = windowMap.floorKey(start); 13 | Integer ceilKey = windowMap.ceilingKey(start); 14 | if ((floorKey != null && windowMap.get(floorKey) > start) || (ceilKey != null && end > ceilKey)) { 15 | return false; 16 | } else { 17 | windowMap.put(start, end); 18 | return true; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/_981_TimeBasedKeyValueStore.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | import collections 3 | 4 | 5 | class TimeMap: 6 | 7 | def __init__(self): 8 | self.repertory = collections.defaultdict(list) 9 | 10 | def set(self, key: str, value: str, timestamp: int) -> None: 11 | val_seq = self.repertory[key] 12 | val_seq.append((value, timestamp)) 13 | 14 | def get(self, key: str, timestamp: int) -> str: 15 | val_seq = self.repertory[key] 16 | val_index = bisect.bisect(val_seq, timestamp, key=lambda x: x[1]) - 1 17 | if val_index >= 0: 18 | return val_seq[val_index][0] 19 | else: 20 | return '' 21 | -------------------------------------------------------------------------------- /uva online judge/10107 - What is the Median.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define MAX 10001 5 | int main() 6 | { 7 | //freopen("input.txt","r",stdin); 8 | long long int a[MAX]; 9 | long long int temp, out, n = 0; 10 | int i, ind =-1; 11 | while(cin >> temp){ 12 | for(i=ind; i>=0 && (a[i]>temp); i--) { 13 | a[i+1] = a[i]; 14 | } 15 | 16 | a[i+1] = temp; 17 | n++; 18 | ind++; 19 | if(n%2==0) 20 | out = (a[n/2-1]+a[n/2])/2; 21 | else out = a[n/2]; 22 | cout << out << endl; 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /uva online judge/11723 - Numbering Roads.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int N,R,i; 8 | float dif,min; 9 | i=1; 10 | while(1){ 11 | scanf("%d%d",&R,&N); 12 | if(R==0&&N==0)break; 13 | if(N>=R){ 14 | cout<<"Case "< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | char a[1000]; 9 | int i,wn,l; 10 | while(gets(a)!=NULL) 11 | { 12 | wn=0; 13 | l=strlen(a); 14 | for(i=0;i='a'&&a[i]<='z')||(a[i]>='A'&&a[i]<='Z')) 18 | { 19 | if((a[i+1]>='a'&&a[i+1]<='z')||(a[i+1]>='A'&&a[i+1]<='Z')){} 20 | 21 | else wn++; 22 | 23 | 24 | } 25 | 26 | } 27 | 28 | cout< int: 7 | n = len(nums) 8 | max_consecutive_ones = 0 9 | 10 | zq = collections.deque() 11 | left = right = 0 12 | while right < n: 13 | if nums[right] == 0: 14 | zq.append(right) 15 | if len(zq) >= 2: 16 | left = zq.popleft() + 1 17 | max_consecutive_ones = max(max_consecutive_ones, right - left + 1) 18 | right += 1 19 | return max_consecutive_ones 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode/Valid Palindrome.cc: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution { 6 | public: 7 | bool isPalindrome(string s) { 8 | char seq[s.length()]; 9 | int ind = 0; 10 | for(int i = 0; i < s.length();i++){ 11 | if(isalpha(s[i])) 12 | seq[ind++]=tolower(s[i]); 13 | if(isdigit(s[i])) 14 | seq[ind++] = s[i]; 15 | } 16 | 17 | int lo = 0; 18 | int hi = ind-1; 19 | while(lo < hi){ 20 | if(seq[lo] != seq[hi]) return false; 21 | lo++;hi--; 22 | } 23 | return true; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /leetcode/_1518_WaterBottles.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/28/2022 5 | **/ 6 | public class _1518_WaterBottles { 7 | public int numWaterBottles(int numBottles, int numExchange) { 8 | int drankBottleCount, emptyBottleCount; 9 | drankBottleCount = numBottles; 10 | emptyBottleCount = numBottles; 11 | while (emptyBottleCount >= numExchange){ 12 | int newBottleCount = emptyBottleCount / numExchange; 13 | emptyBottleCount = emptyBottleCount % numExchange + newBottleCount; 14 | drankBottleCount += newBottleCount; 15 | } 16 | return drankBottleCount; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/_802_FindEventualSafeStates.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: 7 | n = len(graph) 8 | WHITE, GRAY, BLACK = 0, 1, 2 9 | color = collections.defaultdict(int) 10 | 11 | def dfs(u): 12 | if color[u] != WHITE: 13 | return color[u] == BLACK 14 | color[u] = GRAY 15 | for v in graph[u]: 16 | if not dfs(v): 17 | return False 18 | color[u] = BLACK 19 | return True 20 | 21 | return list(filter(dfs, range(n))) 22 | -------------------------------------------------------------------------------- /uva online judge/10991 - Region.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | 9 | double r1,r2,r3,a,b,c,A,B,C,s,area; 10 | int t; 11 | scanf("%d",&t); 12 | while(t--){ 13 | scanf("%lf%lf%lf",&r1,&r2,&r3); 14 | a=r1+r2; 15 | b=r2+r3; 16 | c=r3+r1; 17 | s =(a+b+c)/2; 18 | C = acos((a*a+b*b-c*c)/(2*a*b)); 19 | A = acos((b*b+c*c-a*a)/(2*b*c)); 20 | B = acos((c*c+a*a-b*b)/(2*c*a)); 21 | area =sqrt(s*(s-a)*(s-b)*(s-c))-(r1*r1*B+r2*r2*C+r3*r3*A)/2; 22 | printf("%.6lf\n",area); 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/1055. Shortest Way to Form String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestWay(self, source: str, target: str) -> int: 3 | si = ti = ti_prev = 0 4 | sub_seq_count = 0 5 | while ti < len(target): 6 | si = 0 7 | ti_prev = ti 8 | while si < len(source) and ti < len(target): 9 | if source[si] == target[ti]: 10 | si += 1 11 | ti += 1 12 | else: 13 | si += 1 14 | if ti_prev == ti: 15 | return -1 16 | else: 17 | sub_seq_count += 1 18 | return sub_seq_count 19 | 20 | 21 | -------------------------------------------------------------------------------- /leetcode/249. Group Shifted Strings.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def groupStrings(self, strings: List[str]) -> List[List[str]]: 7 | shift_group = collections.defaultdict(list) 8 | for w in strings: 9 | shift = ord(w[0]) - ord('a') 10 | shifted_word = [] 11 | for ch in w: 12 | idx = ord(ch) - shift 13 | if idx < 97: 14 | idx += 26 15 | shifted_word.append(chr(idx)) 16 | 17 | sw = ''.join(shifted_word) 18 | shift_group[sw].append(w) 19 | return shift_group.values() 20 | 21 | -------------------------------------------------------------------------------- /leetcode/948. Bag of Tokens.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def bagOfTokensScore(self, tokens: List[int], power: int) -> int: 6 | tokens.sort() 7 | lo = 0 8 | hi = len(tokens) - 1 9 | scores = 0 10 | while lo <= hi: 11 | if tokens[lo] <= power: 12 | power -= tokens[lo] 13 | scores += 1 14 | lo += 1 15 | elif lo < hi and tokens[lo] <= power + tokens[hi] and scores > 0: 16 | power += tokens[hi] 17 | hi -= 1 18 | scores -= 1 19 | else: 20 | break 21 | return scores -------------------------------------------------------------------------------- /leetcode/Binary Tree Postorder Traversal.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | vector postorderTraversal(TreeNode *root) { 14 | vector lst; 15 | traverse(root, lst); 16 | return lst; 17 | } 18 | void traverse(TreeNode *r , vector &lst){ 19 | if(r == NULL) return; 20 | traverse(r->left,lst); 21 | traverse(r->right,lst); 22 | lst.push_back(r->val); 23 | } 24 | }; -------------------------------------------------------------------------------- /leetcode/_1352_ProductOfTheLastKNumbers.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | 4 | class ProductOfNumbers: 5 | 6 | def __init__(self): 7 | self.z = [] # 0 based index 8 | self.p = [1] 9 | 10 | def add(self, num: int) -> None: 11 | if num == 0: 12 | self.z.append(len(self.p) - 1) 13 | self.p.append(self.p[-1]) 14 | else: 15 | self.p.append(self.p[-1] * num) 16 | 17 | def getProduct(self, k: int) -> int: 18 | ni = bisect.bisect_left(self.z, len(self.p) - k, 0) 19 | if ni < len(self.z): 20 | return 0 21 | else: 22 | return self.p[-1] // self.p[len(self.p) - k - 1] 23 | -------------------------------------------------------------------------------- /leetcode/_416_PartitionEqualSubsetSum.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def canPartition(self, nums: List[int]) -> bool: 7 | total_sum = sum(nums) 8 | if total_sum & 1: 9 | return False 10 | 11 | half = total_sum / 2 12 | 13 | @lru_cache(maxsize=None) 14 | def dfs(pos, target): 15 | if target == 0: 16 | return True 17 | elif pos < 0: 18 | return False 19 | return dfs(pos - 1, target) or (nums[pos] <= target and dfs(pos - 1, target - nums[pos])) 20 | 21 | return dfs(len(nums) - 1, half) 22 | -------------------------------------------------------------------------------- /leetcode/_811_SubdomainVisitCount.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subdomainVisits(self, cpdomains): 3 | count_map = {} 4 | for cd in cpdomains: 5 | count, domain = cd.split(' ') 6 | count = int(count) 7 | count_map[domain] = count_map.get(domain, 0) + count 8 | for i in range(len(domain)): 9 | if domain[i] == '.': 10 | key = domain[i+1:] 11 | count_map[key] = count_map.get(key, 0) + count 12 | return [str(cn) + ' ' + sbd for sbd, cn in count_map.items()] 13 | if __name__ == '__main__': 14 | print(Solution().subdomainVisits(["9001 discuss.leetcode.com"])) -------------------------------------------------------------------------------- /uva online judge/11900 - Boiled Eggs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n,p,q,t,ct,i,w,x; 9 | vector v; 10 | scanf("%d",&t); 11 | ct = 1; 12 | w = 0; 13 | while(ct<=t){ 14 | scanf("%d%d%d",&n,&p,&q); 15 | for(i = 0;i=p||w>q)break; 21 | } 22 | printf("Case %d: %d\n",ct,i); 23 | ct = ct + 1; 24 | w = 0; 25 | v.clear(); 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/1376. Time Needed to Inform All Employees.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: 6 | receive_time = [None] * n 7 | receive_time[headID] = 0 8 | 9 | def receive_information(u): 10 | if receive_time[u] == None: 11 | v = manager[u] 12 | receive_time[u] = receive_information(v) + informTime[v] 13 | return receive_time[u] 14 | 15 | max_time = 0 16 | for u in range(n): 17 | max_time = max(max_time, receive_information(u)) 18 | return max_time 19 | 20 | -------------------------------------------------------------------------------- /leetcode/159. Longest Substring with At Most Two Distinct Characters.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Solution: 5 | def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: 6 | fc = collections.defaultdict(int) 7 | left = right = 0 8 | mx_sub_len = 0 9 | while right < len(s): 10 | fc[s[right]] += 1 11 | while len(fc) > 2: 12 | ch = s[left] 13 | fc[ch] -= 1 14 | if fc[ch] == 0: 15 | del fc[ch] 16 | left += 1 17 | right += 1 18 | mx_sub_len = max(mx_sub_len, right - left) 19 | return mx_sub_len 20 | 21 | -------------------------------------------------------------------------------- /leetcode/Binary Tree Preorder Traversal.cc: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | struct TreeNode { 6 | int val; 7 | TreeNode *left; 8 | TreeNode *right; 9 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | }; 11 | 12 | class Solution { 13 | public: 14 | vector preorderTraversal(TreeNode *root) { 15 | vector lst; 16 | traverse(root, lst); 17 | return lst; 18 | } 19 | void traverse(TreeNode *r , vector &lst){ 20 | if(r == NULL) return; 21 | traverse(r->left,lst); 22 | traverse(r->right,lst); 23 | lst.push_back(r->val); 24 | } 25 | }; -------------------------------------------------------------------------------- /uva online judge/136 - Ugly Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef unsigned long long int ULL; 4 | ULL divide(ULL n, int d){ 5 | while(n%d==0){ 6 | n /=d; 7 | } 8 | return n; 9 | } 10 | bool isUgly(ULL n){ 11 | n = divide(n,2); 12 | n = divide(n,3); 13 | n = divide(n,5); 14 | if(n==1)return true; 15 | else return false; 16 | } 17 | int main() 18 | {/* 19 | int co = 0; 20 | ULL i = 1; 21 | while(co !=1500){ 22 | if(isUgly(i)){co++; cout << i << " " << co << endl;} 23 | i++; 24 | }*/ 25 | cout << "The 1500'th ugly number is 859963392."<< endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/1143. Longest Common Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | m, n = len(text1), len(text2) 4 | dp = [[-1] * n for _ in range(m)] 5 | 6 | def lcs(i, j) -> int: 7 | if i >= m or j >= n: 8 | return 0 9 | elif dp[i][j] != -1: 10 | return dp[i][j] 11 | else: 12 | if text1[i] == text2[j]: 13 | dp[i][j] = 1 + lcs(i + 1, j + 1) 14 | else: 15 | dp[i][j] = max(lcs(i + 1, j), lcs(i, j + 1)) 16 | return dp[i][j] 17 | 18 | return lcs(0, 0) 19 | -------------------------------------------------------------------------------- /leetcode/1216. Valid Palindrome III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidPalindrome(self, s: str, k: int) -> bool: 3 | n = len(s) 4 | dp = [[None] * n for _ in range(n)] 5 | 6 | def min_del(a, b): 7 | if a >= b: 8 | return 0 9 | elif dp[a][b] is not None: 10 | return dp[a][b] 11 | else: 12 | if s[a] == s[b]: 13 | ans = min_del(a + 1, b - 1) 14 | else: 15 | ans = 1 + min(min_del(a + 1, b), min_del(a, b - 1)) 16 | dp[a][b] = ans 17 | return ans 18 | 19 | return min_del(0, n - 1) <= k 20 | 21 | -------------------------------------------------------------------------------- /leetcode/1838. Frequency of the Most Frequent Element.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxFrequency(self, nums: List[int], k: int) -> int: 6 | n = len(nums) 7 | nums.sort() 8 | left = right = 0 9 | window_sum = 0 10 | max_allowed_window = 1 11 | 12 | while right < n: 13 | window_sum += nums[right] 14 | while window_sum + k < nums[right] * (right - left + 1): 15 | window_sum -= nums[left] 16 | left += 1 17 | max_allowed_window = max(max_allowed_window, right - left + 1) 18 | right += 1 19 | return max_allowed_window 20 | 21 | -------------------------------------------------------------------------------- /leetcode/510. Inorder Successor in BST II.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left = None 7 | self.right = None 8 | self.parent = None 9 | """ 10 | 11 | 12 | class Solution: 13 | def inorderSuccessor(self, node: 'Node') -> 'Optional[Node]': 14 | if node.right: 15 | down = node.right 16 | while down.left: 17 | down = down.left 18 | return down 19 | else: 20 | par = node.parent 21 | while par and par.left != node: 22 | node, par = par, par.parent 23 | return par 24 | -------------------------------------------------------------------------------- /leetcode/Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct TreeNode { 6 | int val; 7 | TreeNode *left; 8 | TreeNode *right; 9 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | }; 11 | 12 | class Solution { 13 | public: 14 | vector inorderTraversal(TreeNode *root) { 15 | vector lis; 16 | traverse(root, lis); 17 | return lis; 18 | } 19 | void traverse(TreeNode *r , vector &lis){ 20 | if(r == NULL)return; 21 | traverse(r->left, lis); 22 | lis.push_back(r->val); 23 | traverse(r->right,lis); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /leetcode/Minimum Depth of Binary Tree.cc: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int power(int a, int n){ 7 | int pw = 1; 8 | for(int i = 1; i <=n;i++) 9 | pw *= a; 10 | return pw; 11 | } 12 | int atoi(const char *str) { 13 | int e = 0; 14 | if(!isdigit(str[0])) 15 | e++; 16 | int p = 0; 17 | int ans = 0; 18 | for(int i = strlen(str)-1; i>=e;i--){ 19 | ans += (str[i]-'0')*power(10,p); 20 | p++; 21 | } 22 | 23 | if(str[0]=='-') 24 | ans = -ans; 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /leetcode/_1081_SmallestSubsequenceOfDistinctCharacters.py: -------------------------------------------------------------------------------- 1 | from collections import Counter, defaultdict 2 | 3 | 4 | class Solution: 5 | def smallestSubsequence(self, s: str) -> str: 6 | fc = Counter(s) 7 | stack = [] 8 | stack_fc = defaultdict(int) 9 | for c in s: 10 | while stack and stack_fc[c] == 0 and stack[-1] > c and fc[stack[-1]] > 0: 11 | stack_fc[stack.pop()] -= 1 12 | if stack_fc[c] == 0: 13 | stack.append(c) 14 | stack_fc[c] += 1 15 | fc[c] -= 1 16 | return ''.join(stack) 17 | 18 | 19 | #print(Solution().smallestSubsequence("cbaacabcaaccaacababa")) 20 | -------------------------------------------------------------------------------- /leetcode/_2095_DeleteTheMiddleNodeOfALinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/20/2022 5 | **/ 6 | public class _2095_DeleteTheMiddleNodeOfALinkedList { 7 | public ListNode deleteMiddle(ListNode head) { 8 | ListNode slow, fast, slowPrev; 9 | slow = fast = slowPrev = head; 10 | 11 | while (fast != null && fast.next != null) { 12 | slowPrev = slow; 13 | slow = slow.next; 14 | fast = fast.next.next; 15 | } 16 | if (slow == head) { 17 | return null; 18 | } else { 19 | slowPrev.next = slow.next; 20 | } 21 | return head; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/_538_ConvertBstToGreaterTree.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/21/2022 5 | **/ 6 | public class _538_ConvertBstToGreaterTree { 7 | public TreeNode convertBST(TreeNode root) { 8 | constructGst(root, 0); 9 | return root; 10 | } 11 | 12 | private int constructGst(TreeNode n, int pc) { 13 | if (n == null) { 14 | return 0; 15 | } 16 | int originalVal = n.val; 17 | int rightTotal = constructGst(n.right, pc); 18 | n.val = pc + originalVal + rightTotal; 19 | int leftTotal = constructGst(n.left, n.val); 20 | return leftTotal + originalVal + rightTotal; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lightoj/1227 - Boiled Eggs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int main() { 6 | int n,p,q,t,ct,i,w,x; 7 | vector v; 8 | scanf("%d",&t); 9 | ct = 1; 10 | w = 0; 11 | while(ct<=t) { 12 | scanf("%d%d%d",&n,&p,&q); 13 | for(i = 0; i=p||w>q)break; 20 | } 21 | printf("Case %d: %d\n",ct,i); 22 | ct = ct + 1; 23 | w = 0; 24 | v.clear(); 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /uva online judge/484 - The Department of Redundancy Department.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using std :: cout; 6 | using std :: cin; 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | map m; 12 | vector v; 13 | int num,size,i; 14 | while(std::cin>>num){ 15 | if(m.find(num)==m.end()){ 16 | m[num] = 1; 17 | v.push_back(num); 18 | } 19 | else m[num] = m[num]+1; 20 | } 21 | size = v.size(); 22 | for(i=0;ib)break; 21 | it++; 22 | } 23 | System.out.println("Case "+CT+": A = "+a+", limit = "+b+", number of terms = "+it); 24 | CT++; 25 | } 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/1792. Maximum Average Pass Ratio.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from heapq import heappush, heappop, heapify 3 | class Solution: 4 | def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: 5 | pq = [] 6 | for p, t in classes: 7 | pq.append([(p/t)-(p+1)/(t+1), p, t]) 8 | heapify(pq) 9 | for i in range(extraStudents): 10 | avg, p, t =heappop(pq) 11 | p += 1 12 | t += 1 13 | heappush(pq, [(p/t)-(p+1)/(t+1), p, t]) 14 | avg_sum = 0 15 | while pq: 16 | _, p ,t = heappop(pq) 17 | avg_sum += p/t 18 | return avg_sum / len(classes) -------------------------------------------------------------------------------- /leetcode/663. Equal Tree Partition.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 checkEqualTree(self, root: Optional[TreeNode]) -> bool: 9 | ss = [] 10 | def dfs(sb): 11 | if not sb: 12 | return 0 13 | else: 14 | s = dfs(sb.left) + dfs(sb.right) + sb.val 15 | ss.append(s) 16 | return s 17 | dfs(root) 18 | total = ss.pop() 19 | return total % 2 == 0 and (total//2) in ss 20 | -------------------------------------------------------------------------------- /leetcode/_1642_FurthestBuildingYouCanReach.py: -------------------------------------------------------------------------------- 1 | from heapq import heappop, heappush 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: 7 | pq = [] 8 | for i in range(1, len(heights)): 9 | h1 = heights[i - 1] 10 | h2 = heights[i] 11 | if h1 < h2: 12 | heappush(pq, h2 - h1) 13 | if ladders > 0: 14 | ladders -= 1 15 | elif bricks >= pq[0]: 16 | bricks -= heappop(pq) 17 | else: 18 | return i - 1 19 | return len(heights) - 1 20 | -------------------------------------------------------------------------------- /leetcode/_388_LongestAbsoluteFilePath.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class Solution: 5 | def lengthLongestPath(self, input: str) -> int: 6 | token_list = re.split("([\n\t]+)", input) 7 | dir_stack = [] 8 | deepest_file_len = 0 9 | for token in token_list: 10 | if token.find('\n') >= 0: 11 | tab_count = token.count('\t') 12 | dir_stack = dir_stack[:tab_count] 13 | else: 14 | dir_stack.append(token) 15 | if token.find('.') >= 0: 16 | deepest_file_len = max(deepest_file_len, sum(map(len, dir_stack)) + len(dir_stack) - 1) 17 | return deepest_file_len 18 | -------------------------------------------------------------------------------- /leetcode/_45_JumpGameII.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | /** 5 | * @author Shahidul Islam 6 | * @date 2/5/2022 7 | **/ 8 | public class _45_JumpGameII { 9 | public int jump(int[] nums) { 10 | int n = nums.length; 11 | int[] jp = new int[n]; 12 | int inf = 1000000; 13 | Arrays.fill(jp, inf); 14 | jp[0] = 0; 15 | for (int i = 0; i < n - 1; i++) { 16 | if (jp[i] != inf) { 17 | for (int k = 1; k <= nums[i] && i + k < n; k++) { 18 | jp[i + k] = Math.min(jp[i + k], jp[i] + 1); 19 | } 20 | } 21 | } 22 | return jp[n - 1]; 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /uva online judge/10473 - Simple Base Conversion.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.lang.String; 3 | import static java.lang.Integer.*; 4 | public class Main { 5 | public static void main(String[] args) { 6 | int intValue; 7 | Scanner sc = new Scanner(System.in); 8 | String str; 9 | while(true){ 10 | str = sc.nextLine(); 11 | if(str.charAt(0)=='-')break; 12 | if(str.charAt(0)=='0'&&str.charAt(1)=='x'){ 13 | str = str.substring(2); 14 | System.out.println(parseInt(str,16)); 15 | } 16 | else{ 17 | intValue = parseInt(str); 18 | System.out.println("0x"+toHexString(intValue).toUpperCase()); 19 | } 20 | 21 | } 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/1641. Count Sorted Vowel Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.dp = [[-1] * 5 for _ in range(51)] 4 | 5 | def count(self, n: int, char_index: int) -> int: 6 | if n == 1: 7 | return 1 8 | elif self.dp[n][char_index] == -1: 9 | total = 0 10 | for vi in range(0, char_index + 1): 11 | total += self.count(n - 1, vi) 12 | self.dp[n][char_index] = total 13 | return self.dp[n][char_index] 14 | 15 | def countVowelStrings(self, n: int) -> int: 16 | ans = 0 17 | for voul_index in range(5): 18 | ans += self.count(n, voul_index) 19 | return ans -------------------------------------------------------------------------------- /leetcode/_1048_LongestStringChain.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def longestStrChain(self, words: List[str]) -> int: 7 | word_set = set(words) 8 | 9 | @lru_cache(maxsize=None) 10 | def lsc(w): 11 | mx = 0 12 | for i in range(len(w)): 13 | pw = (w[:i] if i > 0 else '') + (w[i + 1:] if i + 1 < len(w) else '') 14 | if pw in word_set: 15 | mx = max(mx, lsc(pw)) 16 | return 1 + mx 17 | 18 | return max(lsc(w) for w in words) 19 | 20 | 21 | #print(Solution().longestStrChain(["a", "b", "ba", "bca", "bda", "bdca"])) 22 | -------------------------------------------------------------------------------- /leetcode/_1510_StoneGameIV.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def winnerSquareGame(self, n: int) -> bool: 3 | dp = [None] * (n + 1) 4 | dp[0] = False 5 | dp[1] = True 6 | 7 | def can_win(s): 8 | if dp[s] != None: 9 | return dp[s] 10 | else: 11 | i = 1 12 | while i * i <= s: 13 | if not can_win(s - i * i): 14 | break 15 | i += 1 16 | else: 17 | dp[s] = False 18 | return dp[s] 19 | 20 | dp[s] = True 21 | return dp[s] 22 | 23 | return can_win(n) 24 | -------------------------------------------------------------------------------- /leetcode/186. Reverse Words in a String II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def reverseWords(self, s: List[str]) -> None: 6 | """ 7 | Do not return anything, modify s in-place instead. 8 | """ 9 | 10 | def reverse(x, y): 11 | while x < y: 12 | s[x], s[y] = s[y], s[x] 13 | x += 1 14 | y -= 1 15 | 16 | reverse(0, len(s) - 1) 17 | left = right = 0 18 | while right < len(s): 19 | while right < len(s) and s[right] != ' ': 20 | right += 1 21 | reverse(left, right - 1) 22 | right += 1 23 | left = right 24 | -------------------------------------------------------------------------------- /leetcode/_173_BinarySearchTreeIterator.py: -------------------------------------------------------------------------------- 1 | class TreeNode(object): 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | class BSTIterator(object): 7 | def __init__(self, root): 8 | self.root = root 9 | self.stack = [] 10 | self.inorder_left(root) 11 | def next(self): 12 | top = self.stack.pop() 13 | self.inorder_left(top.right) 14 | return top.val 15 | 16 | def hasNext(self): 17 | return len(self.stack) > 0 18 | 19 | def inorder_left(self, root): 20 | while root: 21 | self.stack.append(root) 22 | root = root.left -------------------------------------------------------------------------------- /leetcode/_299_BullsAndCows.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def getHint(self, secret: str, guess: str) -> str: 6 | character_frequency = Counter(secret) 7 | N = len(secret) 8 | bulls = cows = 0 9 | for i, c in enumerate(guess): 10 | if secret[i] == guess[i]: 11 | bulls += 1 12 | character_frequency[c] -= 1 13 | for i, c in enumerate(guess): 14 | if secret[i] != guess[i] and c in character_frequency and character_frequency[c] > 0: 15 | cows += 1 16 | character_frequency[c] -= 1 17 | return ''.join([str(bulls), 'A', str(cows), 'B']) 18 | -------------------------------------------------------------------------------- /codejam/Pancake Deque.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ == '__main__': 4 | T = int(sys.stdin.readline()) 5 | for tc in range(1, T + 1, 1): 6 | N = int(sys.stdin.readline()) 7 | a = list(map(int, sys.stdin.readline().split(' '))) 8 | left = 0 9 | right = len(a) - 1 10 | d = 0 11 | paid = 0 12 | while left <= right: 13 | if a[left] < a[right]: 14 | v = a[left] 15 | left += 1 16 | else: 17 | v = a[right] 18 | right -= 1 19 | if d <= v: 20 | paid += 1 21 | d = v 22 | print('Case #' + str(tc) + ': ' + str(paid)) 23 | -------------------------------------------------------------------------------- /codejam/PunchedCards.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ == '__main__': 4 | tc = int(sys.stdin.readline()) 5 | char_map = [['+', '-'], ['|', '.']] 6 | ct = 1 7 | while ct <= tc: 8 | print('Case #' + str(ct) + ':') 9 | line = sys.stdin.readline() 10 | 11 | R, C = line.split(' ') 12 | R, C = 2 * int(R) + 1, 2 * int(C) + 1 13 | for r in range(R): 14 | for c in range(C): 15 | if 0 <= r <= 1 and 0 <= c <= 1: 16 | print('.', end='') 17 | else: 18 | print(char_map[r % 2][c % 2], end='') 19 | if c == C - 1: 20 | print('') 21 | ct += 1 22 | -------------------------------------------------------------------------------- /leetcode/1498. Number of Subsequences That Satisfy the Given Sum Condition.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def numSubseq(self, nums: List[int], target: int) -> int: 7 | n = len(nums) 8 | p2 = [1] 9 | while len(p2) < n: 10 | p2.append((p2[-1] * 2) % 1_000_000_007) 11 | nums.sort() 12 | low = 0 13 | ans = 0 14 | while low < n and 2 * nums[low] <= target: 15 | high = bisect.bisect_right(nums, target - nums[low], lo = low, hi = n) 16 | seq_len = high - low 17 | ans = (ans + p2[seq_len - 1]) % 1_000_000_007 18 | low += 1 19 | return ans -------------------------------------------------------------------------------- /leetcode/155. Min Stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | self.stack = [] 5 | 6 | def push(self, val: int) -> None: 7 | min_val = val 8 | if self.stack: 9 | min_val = min(min_val, self.stack[-1][-1]) 10 | self.stack.append([val, min_val]) 11 | 12 | def pop(self) -> None: 13 | self.stack.pop() 14 | 15 | def top(self) -> int: 16 | return self.stack[-1][0] 17 | 18 | def getMin(self) -> int: 19 | return self.stack[-1][-1] 20 | 21 | # Your MinStack object will be instantiated and called as such: 22 | # obj = MinStack() 23 | # obj.push(val) 24 | # obj.pop() 25 | # param_3 = obj.top() 26 | # param_4 = obj.getMin() -------------------------------------------------------------------------------- /leetcode/1855. Maximum Distance Between a Pair of Values.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: 6 | opt_dist = 0 7 | for i, v in enumerate(nums2): 8 | low = 0 9 | high = min(i, len(nums1) - 1) 10 | while low <= high: 11 | mid = (low + high) // 2 12 | if nums1[mid] > v: 13 | low = mid + 1 14 | else: 15 | high = mid - 1 16 | if low <= min(i, len(nums1) - 1) and nums1[low] <= v: 17 | opt_dist = max(opt_dist, i - low) 18 | return opt_dist 19 | 20 | 21 | -------------------------------------------------------------------------------- /leetcode/2021. Brightest Position on Street.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop, heapify 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def brightestPosition(self, lights: List[List[int]]) -> int: 7 | pq = [] 8 | for lp, r in lights: 9 | pq.append([lp - r, 1]) 10 | pq.append([lp + r + 1, -1]) 11 | 12 | heapify(pq) 13 | opt = [float('-inf'), 0] 14 | cur_val = 0 15 | while pq: 16 | # print(pq[0], cur_val) 17 | lp, lv = heappop(pq) 18 | cur_val += lv 19 | opp, opv = opt 20 | if opv < cur_val: 21 | opt = [lp, cur_val] 22 | return opt[0] 23 | -------------------------------------------------------------------------------- /leetcode/845. Longest Mountain in Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def longestMountain(self, arr: List[int]) -> int: 4 | ans = start = end = 0 5 | n = len(arr) 6 | while start < n: 7 | end = start 8 | if end + 1 < n and arr[end] < arr[end + 1]: 9 | while end + 1 < n and arr[end] < arr[end + 1]: 10 | end += 1 11 | if end + 1 < n and arr[end] > arr[end + 1]: 12 | while end + 1 < n and arr[end] > arr[end + 1]: 13 | end += 1 14 | ans = max(ans, end - start + 1) 15 | start = max(start + 1, end) 16 | return ans -------------------------------------------------------------------------------- /leetcode/_1038_BinarySearchTreeToGreaterSumTree.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/21/2022 5 | **/ 6 | public class _1038_BinarySearchTreeToGreaterSumTree { 7 | public TreeNode bstToGst(TreeNode root) { 8 | constructGst(root, 0); 9 | return root; 10 | } 11 | 12 | private int constructGst(TreeNode n, int pc) { 13 | if (n == null) { 14 | return 0; 15 | } 16 | int originalVal = n.val; 17 | int rightTotal = constructGst(n.right, pc); 18 | n.val = pc + originalVal + rightTotal; 19 | int leftTotal = constructGst(n.left, n.val); 20 | return leftTotal + originalVal + rightTotal; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lightoj/1387 - Setu.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | //freopen("input.txt","r",stdin); 6 | int i, test, n, ctc=1, k, account; 7 | char input[50], type[20]; 8 | scanf("%d",&test); 9 | while(test--) { 10 | scanf("%d",&n); 11 | gets(input); 12 | account = 0; 13 | printf("Case %d:\n",ctc++); 14 | for(i=0; i6) { 17 | sscanf(input,"%s %d",type,&k); 18 | account += k; 19 | } else { 20 | printf("%d\n",account); 21 | } 22 | 23 | } 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /uva online judge/10082 - WERTYU.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Main { 3 | 4 | /** 5 | * @param args 6 | */ 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner sc = new Scanner(System.in); 10 | String str,keyboard; 11 | int len; 12 | keyboard = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./"; 13 | while(sc.hasNext()){ 14 | str = sc.nextLine(); 15 | len = str.length(); 16 | for(int i = 0;i int: 3 | n = len(s) 4 | dp = [[None] * n for _ in range(n)] 5 | 6 | def min_insertion(a, b): 7 | if a >= b: 8 | return 0 9 | elif dp[a][b] is not None: 10 | return dp[a][b] 11 | else: 12 | if s[a] == s[b]: 13 | dp[a][b] = min_insertion(a + 1, b - 1) 14 | else: 15 | dp[a][b] = min(min_insertion(a + 1, b), min_insertion(a, b - 1)) + 1 16 | return dp[a][b] 17 | 18 | return min_insertion(0, len(s) - 1) 19 | -------------------------------------------------------------------------------- /leetcode/1395. Count Number of Teams.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numTeams(self, rating: List[int]) -> int: 6 | def team_count(rt): 7 | n = len(rt) 8 | bigger_ns = [0] * n 9 | for i in range(n): 10 | for k in range(i + 1, n): 11 | if rt[i] < rt[k]: 12 | bigger_ns[i] += 1 13 | teams = 0 14 | for i in range(n): 15 | for j in range(i + 1, n): 16 | if rt[i] < rt[j]: 17 | teams += bigger_ns[j] 18 | return teams 19 | 20 | return team_count(rating) + team_count(rating[::-1]) 21 | -------------------------------------------------------------------------------- /leetcode/777. Swap Adjacent in LR String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canTransform(self, start: str, end: str) -> bool: 3 | n = len(start) 4 | i = k = 0 5 | while i < n or k < n: 6 | while i < n and start[i] == 'X': 7 | i += 1 8 | while k < n and end[k] == 'X': 9 | k += 1 10 | if i == n and k == n: 11 | return True 12 | elif i == n or k == n or start[i] != end[k]: 13 | return False 14 | 15 | if (start[i] == 'L' and i < k) or (start[i] == 'R' and i > k): 16 | return False 17 | i += 1 18 | k += 1 19 | return True 20 | 21 | -------------------------------------------------------------------------------- /leetcode/_1861_RotatingTheBox.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: 6 | m, n = len(box), len(box[0]) 7 | rotated_box = [['.'] * m for _ in range(n)] 8 | for r in range(m): 9 | c = wc = n - 1 10 | while c >= 0: 11 | match box[r][c]: 12 | case '*': 13 | rotated_box[c][m - 1 - r] = '*' 14 | wc = c - 1 15 | case '#': 16 | rotated_box[wc][m - 1 - r] = '#' 17 | wc -= 1 18 | c -= 1 19 | 20 | return rotated_box 21 | -------------------------------------------------------------------------------- /leetcode/_983_MinimumCostForTickets.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | from functools import lru_cache 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 8 | @lru_cache 9 | def min_cost(s): 10 | if s >= len(days): 11 | return 0 12 | else: 13 | lowest_cost = float('inf') 14 | for i, d in enumerate([1, 7, 30]): 15 | next_start = bisect(days, days[s] + d - 1, lo=s) 16 | lowest_cost = min(costs[i] + min_cost(next_start), lowest_cost) 17 | return lowest_cost 18 | 19 | return min_cost(0) 20 | -------------------------------------------------------------------------------- /leetcode/713. Subarray Product Less Than K.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: 6 | pd = 1 7 | left = right = ans = 0 8 | while right < len(nums): 9 | v = nums[right] 10 | while left < right and pd * v >= k: 11 | ans += right - left 12 | pd /= nums[left] 13 | left += 1 14 | 15 | if pd * v < k: 16 | pd *= v 17 | else: 18 | pd = 1 19 | left = right + 1 20 | right += 1 21 | n = right - left 22 | return ans + (n * (n + 1)) // 2 23 | 24 | -------------------------------------------------------------------------------- /leetcode/_1023_CamelcaseMatching.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: 6 | def match(i: int, s: str, j: int, t: str): 7 | if i >= len(s): 8 | return j >= len(t) or t[j:].islower() 9 | elif j >= len(t): 10 | return False 11 | else: 12 | if s[i] == t[j]: 13 | return match(i + 1, s, j + 1, t) 14 | elif t[j].isupper(): 15 | return False 16 | else: 17 | return match(i, s, j + 1, t) 18 | 19 | return [match(0, pattern, 0, t) for t in queries] 20 | -------------------------------------------------------------------------------- /leetcode/_152_MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/6/2022 5 | **/ 6 | public class _152_MaximumProductSubarray { 7 | public int maxProduct(int[] nums) { 8 | int n = nums.length; 9 | int x; 10 | int y; 11 | int globalMaxProduct; 12 | x = y = globalMaxProduct = nums[0]; 13 | for (int i = 1; i < n; i++) { 14 | int tmpX = Math.min(Math.min(x * nums[i], y * nums[i]), nums[i]); 15 | y = Math.max(Math.max(x * nums[i], y * nums[i]), nums[i]); 16 | globalMaxProduct = Math.max(globalMaxProduct, y); 17 | x = tmpX; 18 | } 19 | return globalMaxProduct; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/_230_KthSmallestElementInABST.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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 9 | stack = [] 10 | cr = root 11 | while True: 12 | while cr: 13 | stack.append(cr) 14 | cr = cr.left 15 | cr = stack.pop() 16 | k -= 1 17 | if k == 0: 18 | return cr.val 19 | else: 20 | cr = cr.right 21 | return None 22 | 23 | -------------------------------------------------------------------------------- /leetcode/_792_NumberOfMatchingSubsequences.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def numMatchingSubseq(self, s: str, words: List[str]) -> int: 7 | bk = collections.defaultdict(list) 8 | for w in words: 9 | it = iter(w) 10 | bk[next(it)].append(it) 11 | match_count = 0 12 | for c in s: 13 | matched_words = bk[c] 14 | bk[c] = [] 15 | for wit in matched_words: 16 | nx_ch = next(wit, None) 17 | if nx_ch: 18 | bk[nx_ch].append(wit) 19 | else: 20 | match_count += 1 21 | return match_count 22 | -------------------------------------------------------------------------------- /codejam/3DPrinting.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ == '__main__': 4 | T = int(sys.stdin.readline()) 5 | for tc in range(1, T + 1, 1): 6 | m = [float('inf')] * 4 7 | for i in range(3): 8 | p = list(map(int, sys.stdin.readline().split(' '))) 9 | for c in range(4): 10 | m[c] = min(m[c], p[c]) 11 | s = sum(m) 12 | print('Case #' + str(tc) + ':', end='') 13 | if s < 10 ** 6: 14 | print(' IMPOSSIBLE') 15 | else: 16 | r = 10 ** 6 17 | for c in range(4): 18 | ink = min(r, m[c]) 19 | r -= ink 20 | print(' ' + str(ink), end=' ') 21 | print('') 22 | -------------------------------------------------------------------------------- /leetcode/1570. Dot Product of Two Sparse Vectors.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class SparseVector: 5 | def __init__(self, nums: List[int]): 6 | self.em = {} 7 | for i, v in enumerate(nums): 8 | if v != 0: 9 | self.em[i] = v 10 | 11 | # Return the dotProduct of two sparse vectors 12 | def dotProduct(self, vec: 'SparseVector') -> int: 13 | ans = 0 14 | for k, v in vec.em.items(): 15 | if k in self.em: 16 | ans += v * self.em[k] 17 | return ans 18 | 19 | # Your SparseVector object will be instantiated and called as such: 20 | # v1 = SparseVector(nums1) 21 | # v2 = SparseVector(nums2) 22 | # ans = v1.dotProduct(v2) -------------------------------------------------------------------------------- /leetcode/1996. The Number of Weak Characters in the Game.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: 6 | properties.sort() 7 | max_defense = 0 8 | right = len(properties) 9 | 10 | weak_characters = 0 11 | for i in range(len(properties) - 1, -1, -1): 12 | at, df = properties[i] 13 | while right - 1 > i and properties[right - 1][0] > at: 14 | right -= 1 15 | max_defense = max(max_defense, properties[right][1]) 16 | if max_defense > df: 17 | weak_characters += 1 18 | return weak_characters 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /leetcode/_2116_CheckIfAParenthesesStringCanBeValid.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canBeValid(self, s: str, locked: str) -> bool: 3 | n = len(s) 4 | if n % 2 != 0: 5 | return False 6 | else: 7 | close_prefix = 0 8 | open_suffix = 0 9 | for i in range(n): 10 | if s[i] == ')' and locked[i] == '1': 11 | close_prefix += 1 12 | if s[~i] == '(' and locked[~i] == '1': 13 | open_suffix += 1 14 | if 2 * close_prefix > i + 1 or 2 * open_suffix > i + 1: 15 | return False 16 | return True 17 | 18 | 19 | print(Solution().canBeValid("()()", "1111")) 20 | -------------------------------------------------------------------------------- /leetcode/1525. Number of Good Ways to Split a String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSplits(self, s: str) -> int: 3 | left = [0] * 26 4 | right = [0] * 26 5 | for c in s: 6 | right[ord(c) - ord('a')] += 1 7 | good_splits = 0 8 | for i in range(len(s)): 9 | bal = 0 10 | for ci in range(26): 11 | if left[ci] > 0: 12 | bal += 1 13 | if right[ci] > 0: 14 | bal -= 1 15 | if bal == 0: 16 | good_splits += 1 17 | 18 | ci = ord(s[i]) - ord('a') 19 | left[ci] += 1 20 | right[ci] -= 1 21 | return good_splits 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode/306. Additive Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAdditiveNumber(self, num: str) -> bool: 3 | n = len(num) 4 | 5 | def move_next(start_index, p1, p2, seq_count) -> bool: 6 | if start_index == n: 7 | return seq_count >= 3 8 | 9 | for i in range(start_index, min(start_index + 12, n)): 10 | if num[start_index] == '0' and (i - start_index) > 0: 11 | continue 12 | p3 = int(num[start_index: i + 1]) 13 | if (p1 == -1 or p2 == -1 or p1 + p2 == p3) and move_next(i + 1, p2, p3, seq_count + 1): 14 | return True 15 | return False 16 | 17 | return move_next(0, -1, -1, 0) -------------------------------------------------------------------------------- /leetcode/328. Odd Even Linked List.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | class Solution: 9 | def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: 10 | odd = odd_sentinel = ListNode() 11 | even = even_sentinel = ListNode() 12 | while head: 13 | odd.next, head = head, head.next 14 | odd = odd.next 15 | if head: 16 | even.next, head = head, head.next 17 | even = even.next 18 | odd.next, even.next = even_sentinel.next, None 19 | return odd_sentinel.next 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode/678. Valid Parenthesis String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkValidString(self, s: str) -> bool: 3 | min_balance = max_balance = 0 # keep track of range of stage(s) 4 | for ch in s: 5 | left = right = 0 6 | if ch == '(': 7 | left = right = 1 8 | elif ch == ')': 9 | left = right = -1 10 | else: 11 | left = -1 12 | right = 1 13 | 14 | min_balance += left 15 | max_balance += right 16 | if max_balance < 0: 17 | break 18 | min_balance = max(min_balance, 0) # skip invaid state(s) 19 | return min_balance <= 0 <= max_balance 20 | -------------------------------------------------------------------------------- /leetcode/_134_GasStation.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 2/1/2022 5 | **/ 6 | public class _134_GasStation { 7 | public int canCompleteCircuit(int[] gas, int[] cost) { 8 | int cd = 0; 9 | int td = 0; 10 | int n = gas.length; 11 | 12 | int i, s; 13 | i = s = 0; 14 | for (i = 0; i < n; i++) { 15 | int d = gas[i] - cost[i]; 16 | td += d; 17 | cd += d; 18 | if (cd < 0) { 19 | cd = 0; 20 | s = i + 1; 21 | } 22 | } 23 | if (td >= 0 && i == n) { 24 | return s; 25 | } else { 26 | return -1; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/_1647_MinimumDeletionsToMakeCharacterFrequenciesUnique.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from collections import Counter 3 | 4 | 5 | class Solution: 6 | def minDeletions(self, s: str) -> int: 7 | fl = list(Counter(s).values()) 8 | 9 | fl.sort() 10 | used_fc = collections.defaultdict(int) 11 | for f in fl: 12 | used_fc[f] += 1 13 | dl = 0 14 | for f in fl: 15 | if used_fc[f] > 1: 16 | avf = f 17 | while avf in used_fc: 18 | avf -= 1 19 | dl += f - avf 20 | if avf > 0: 21 | used_fc[avf] += 1 22 | used_fc[f] -= 1 23 | return dl 24 | -------------------------------------------------------------------------------- /leetcode/_200_NumberOfIslands.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def numIslands(self, grid: List[List[str]]) -> int: 6 | 7 | def dfs(r, c): 8 | grid[r][c] = '0' 9 | for dr, dc in [(0, 1), (-1, 0), (0, -1), (1, 0)]: 10 | nr, nc = r + dr, c + dc 11 | if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == '1': 12 | dfs(nr, nc) 13 | 14 | R, C = len(grid), len(grid[0]) 15 | island_count = 0 16 | for r in range(R): 17 | for c in range(C): 18 | if grid[r][c] == '1': 19 | dfs(r, c) 20 | island_count += 1 21 | return island_count 22 | -------------------------------------------------------------------------------- /leetcode/_2050_ParallelCoursesIII.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int: 6 | rg = [set() for _ in range(n + 1)] 7 | mt = {} 8 | for v, v in relations: 9 | rg[v].add(v) 10 | 11 | def dfs(v): 12 | if v in mt: 13 | return mt[v] 14 | ut = 0 15 | for u in rg[v]: 16 | ut = max(dfs(u), ut) 17 | 18 | mt[v] = ut + time[v - 1] 19 | return mt[v] 20 | 21 | max_time = 0 22 | for v in range(1, n + 1, 1): 23 | max_time = max(max_time, dfs(v)) 24 | return max_time 25 | -------------------------------------------------------------------------------- /leetcode/_213_HouseRobberII.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def rob(self, nums: List[int]) -> int: 6 | def max_profit(s, dp): 7 | if s >= len(nums): 8 | return 0 9 | elif s in dp: 10 | return dp[s] 11 | else: 12 | dp[s] = max(nums[s] + max_profit(s + 2, dp), max_profit(s + 1, dp)) 13 | return dp[s] 14 | 15 | if len(nums) == 1: 16 | return nums[0] 17 | else: 18 | last_val = nums.pop() 19 | ans = max_profit(0, dict()) 20 | nums.append(last_val) 21 | nums.pop(0) 22 | return max(ans, max_profit(0, dict())) 23 | -------------------------------------------------------------------------------- /leetcode/_498_DiagonalTraverse.py: -------------------------------------------------------------------------------- 1 | class _498_DiagonalTraverse(object): 2 | def findDiagonalOrder(self, mat): 3 | m = len(mat) 4 | n = len(mat[0]) 5 | st = [] 6 | d = 0 7 | for d in range(m + n - 1): 8 | from_row = True if d < m else False 9 | r = d if from_row else m - 1 10 | c = 0 if from_row else d - m + 1 11 | diagonal = [] 12 | while 0 <= r < m and 0 <= c < n: 13 | diagonal.append(mat[r][c]) 14 | r = r - 1 15 | c = c + 1 16 | if d % 2 == 0: 17 | st += diagonal 18 | else: 19 | st += diagonal[::-1] 20 | return st 21 | -------------------------------------------------------------------------------- /leetcode/2250. Count Number of Rectangles Containing Each Point.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]: 7 | rectangle_group = [[] for _ in range(101)] 8 | for x, y in rectangles: 9 | rectangle_group[y].append(x) 10 | for y in range(101): 11 | rectangle_group[y].sort() 12 | count = [0] * len(points) 13 | for i, [px, py] in enumerate(points): 14 | for y in range(py, 101): 15 | count[i] += len(rectangle_group[y]) - bisect.bisect_right(rectangle_group[y], px - 1) 16 | return count 17 | 18 | 19 | -------------------------------------------------------------------------------- /leetcode/513. Find Bottom Left Tree Value.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int: 11 | ans = [None, -1] 12 | 13 | def pre_order_dfs(sb, depth): 14 | nonlocal ans 15 | if sb: 16 | if ans[1] < depth: 17 | ans = [sb, depth] 18 | pre_order_dfs(sb.left, depth + 1) 19 | pre_order_dfs(sb.right, depth + 1) 20 | 21 | pre_order_dfs(root, 0) 22 | return ans[0].val 23 | -------------------------------------------------------------------------------- /leetcode/_66_PlusOne.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author Shahidul Islam 4 | * @date 1/23/2022 5 | **/ 6 | public class _66_PlusOne { 7 | 8 | public int[] plusOne(int[] digits) { 9 | int[] sum = new int[digits.length]; 10 | int c = 1; 11 | for (int i = digits.length - 1; i >= 0; i--){ 12 | c = c + digits[i]; 13 | sum[i] = c %10; 14 | c = c /10; 15 | } 16 | if (c > 0){ 17 | int[] extendedSum = new int[sum.length + 1]; 18 | extendedSum[0] = c; 19 | System.arraycopy(sum, 0, extendedSum, 1, sum.length); 20 | return extendedSum; 21 | }else { 22 | return sum; 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /uva online judge/10327-Flip sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | vector v; 8 | int n,i,x,noswap,k; 9 | while(scanf("%d",&n)==1) 10 | { 11 | noswap=0; 12 | for(i=0;iv[k+1]) 21 | { 22 | swap(v[k],v[k+1]); 23 | noswap=noswap+1; 24 | } 25 | } 26 | cout<<"Minimum exchange operations : "< int: 7 | # def dimensions(self) -> list[]: 8 | 9 | class Solution: 10 | def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: 11 | m, n = binaryMatrix.dimensions() 12 | r, c = 0, n - 1 13 | last_col = -1 14 | while r < m and c >= 0: 15 | if binaryMatrix.get(r, c) == 1: 16 | last_col = c 17 | c -= 1 18 | else: 19 | r += 1 20 | return last_col 21 | -------------------------------------------------------------------------------- /leetcode/340. Longest Substring with At Most K Distinct Characters.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Solution: 5 | def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: 6 | f = collections.defaultdict(int) 7 | left = right = 0 8 | sub_len = 0 9 | while right < len(s): 10 | ch = s[right] 11 | f[ch] += 1 12 | while len(f) > k: 13 | ch = s[left] 14 | if f[ch] == 1: 15 | del f[ch] 16 | else: 17 | f[ch] -= 1 18 | left += 1 19 | right += 1 20 | sub_len = max(right - left, sub_len) 21 | return sub_len 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /leetcode/368. Largest Divisible Subset.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def largestDivisibleSubset(self, nums: List[int]) -> List[int]: 6 | n = len(nums) 7 | nums.sort() 8 | lds = [1] * n 9 | pi = [k for k in range(n)] 10 | for e in range(n): 11 | for s in range(e): 12 | if nums[e] % nums[s] == 0 and lds[e] < lds[s] + 1: 13 | lds[e] = lds[s] + 1 14 | pi[e] = s 15 | k = max([(lds[k], k) for k in range(n)])[1] 16 | seq = [] 17 | while k != pi[k]: 18 | seq.append(nums[k]) 19 | k = pi[k] 20 | seq.append(nums[k]) 21 | return seq[::-1] 22 | 23 | -------------------------------------------------------------------------------- /leetcode/779. K-th Symbol in Grammar.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthGrammar(self, n: int, k: int) -> int: 3 | def find_kth_bit(current_n : int, current_k : int, is_flip:bool)-> int: 4 | if current_n == 1: 5 | if is_flip: 6 | return 1 7 | else: 8 | return 0 9 | else: 10 | prev_row_bit_count = 1 << (current_n - 2) 11 | if prev_row_bit_count >= current_k: 12 | return find_kth_bit(current_n - 1, current_k, is_flip) 13 | else: 14 | return find_kth_bit(current_n - 1, current_k - prev_row_bit_count, not is_flip) 15 | return find_kth_bit(n, k, False) -------------------------------------------------------------------------------- /leetcode/_833_FindAndReplaceInString.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str: 6 | seq = [] 7 | rm = {v: (sources[i], targets[i]) for i, v in enumerate(indices)} 8 | i = 0 9 | while i < len(s): 10 | if i in rm: 11 | if s.startswith(rm[i][0], i): 12 | seq.append(rm[i][1]) 13 | i += len(rm[i][0]) 14 | else: 15 | seq.append(s[i]) 16 | i += 1 17 | else: 18 | seq.append(s[i]) 19 | i += 1 20 | return ''.join(seq) 21 | -------------------------------------------------------------------------------- /lightoj/1005 - Rooks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | typedef unsigned long long int u64; 9 | int main(){ 10 | //freopen("input.txt", "r", stdin); 11 | int test, n, k, tc=1; 12 | u64 ans; 13 | scanf("%d", &test); 14 | 15 | while( test-- ){ 16 | scanf("%d %d", &n, &k); 17 | ans = 0; 18 | if(n*n >= k){ 19 | ans = 1; 20 | for(int ck = 1; ck <= k; ck++){ 21 | ans = ans * n*n/ck; 22 | n -= 1; 23 | } 24 | } 25 | printf("Case %d: %llu\n", tc++, ans); 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /lightoj/1053 - Higher Math.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | int main() { 12 | //freopen("input.txt","r",stdin); 13 | //freopen("output.txt","w",stdout); 14 | unsigned long int tc,TC,a[3]; 15 | cin >> TC; 16 | tc = 1; 17 | 18 | while(TC>=tc) { 19 | cin >> a[0] >> a[1] >> a[2]; 20 | cout << "Case "<< tc <<": "; 21 | sort(a,a+3); 22 | if(a[2]*a[2]== a[0]*a[0]+a[1]*a[1])cout << "yes"<< endl; 23 | else cout << "no"<< endl; 24 | tc++; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /uva online judge/10298 - Power Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | char s[1000000+5]; 10 | bool got; 11 | int i,j,len; 12 | while(gets(s)&&s[0]!='.'){ 13 | len = strlen(s); 14 | got = true; 15 | for(i=1;i 2 | #include 3 | 4 | using namespace std; 5 | typedef unsigned long long int u64; 6 | int coins[22]; 7 | u64 C[10000]; 8 | #define N 21 9 | int W; 10 | u64 countWays(){ 11 | for(int i = 1; i<=W; i++)C[i] = 0; 12 | C[0] = 1; 13 | for(int i = 1; i<=N; i++) 14 | for(int j = coins[i]; j<=W; j++){ 15 | C[j] = C[j] + C[j - coins[i]]; 16 | } 17 | 18 | return C[W]; 19 | } 20 | void makeCoins(){ 21 | for(int i = 1; i <= 21; i++) coins[i] = i*i*i; 22 | } 23 | int main() 24 | { 25 | 26 | makeCoins(); 27 | while(scanf("%d", &W) == 1){ 28 | printf("%llu\n", countWays()); 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/1060. Missing Element in Sorted Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def missingElement(self, nums: List[int], k: int) -> int: 6 | lo = 0 7 | hi = len(nums) - 1 8 | last_known = len(nums) - 1 9 | while lo <= hi: 10 | mid = (lo + hi) // 2 11 | n = nums[mid] - nums[0] + 1 12 | missing_n = n - (mid + 1) 13 | if missing_n >= k: 14 | last_known = mid - 1 15 | hi = mid - 1 16 | else: 17 | lo = mid + 1 18 | # print(last_known) 19 | missing_nums = (nums[last_known] - nums[0] + 1) - (last_known + 1) 20 | return nums[last_known] + k - missing_nums 21 | -------------------------------------------------------------------------------- /leetcode/907. Sum of Subarray Minimums.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def sumSubarrayMins(self, arr: List[int]) -> int: 6 | mod = 10 ** 9 + 7 7 | stack = [] 8 | ans = 0 9 | for i, v in enumerate(arr): 10 | left = i 11 | while stack and stack[-1][2] >= v: 12 | left, org_pos, left_val = stack.pop() 13 | ans += (org_pos - left + 1) * (i - org_pos) * left_val 14 | ans %= mod 15 | stack.append([left, i, v]) 16 | while stack: 17 | left, org_pos, v = stack.pop() 18 | ans += (org_pos - left + 1) * (len(arr) - org_pos) * v 19 | ans %= mod 20 | return ans 21 | --------------------------------------------------------------------------------