Math and Number Theory Pattern: Template + 485 LeetCode Problems

Find the closed form, the invariant, or the modular identity — and skip the loop entirely.

  • 121 Easy
  • 244 Medium
  • 120 Hard
  • O(log n) or O(1) time

What the math and number theory pattern is

Some problems have no algorithm worth writing because they have a formula. The tell is a statement about digits, divisors, remainders, or counting arrangements, together with a constraint large enough — 10⁹ and up — that any loop over the input range is hopeless by construction. The recurring tools are small in number: the Euclidean algorithm for the greatest common divisor, which underlies fractions, cycles and repeating patterns; modular arithmetic, where addition and multiplication distribute over the modulus so you can reduce at every step instead of overflowing; a sieve when many primes below a bound are needed rather than one primality test; and fast exponentiation, which raises to the nth power in log n multiplications by squaring. The other half of this pattern is not a technique but a habit: compute the first six answers by hand, look for the pattern, then prove it. An invariant — a quantity the operations never change — usually collapses a simulation into a one-line check.

When to use it

  • The constraints are far too large to iterate, so the answer must be computed rather than searched.
  • The statement is about digits, divisibility, remainders, primes, or gcd.
  • You are counting arrangements and the answer is requested modulo 10⁹ + 7.
  • A simulation is described but some quantity is clearly conserved throughout it.

The math and number theory template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 485 problems listed below.

Math and Number Theory — Python template
def gcd(a, b):
    while b:
        a, b = b, a % b       # gcd(a, b) == gcd(b, a mod b), and b strictly shrinks
    return a

def power_mod(base, exponent, mod):
    result = 1
    base %= mod
    while exponent:
        if exponent & 1:                  # this bit of the exponent is set
            result = result * base % mod
        base = base * base % mod          # square for the next bit
        exponent >>= 1
    return result

Complexity characteristics

Time
O(log n) or O(1)
Auxiliary space
O(1)

The point of the pattern is that there is no loop over the input: a closed form is O(1), the Euclidean algorithm for a greatest common divisor is O(log min(a, b)), and fast exponentiation raises to the nth power in O(log n) multiplications. A sieve is the exception that costs real time and memory — O(n log log n) to build and O(n) to hold — and is only worth it when many primes below a bound are needed rather than a single primality test.

All 485 math and number theory LeetCode problems

Every problem in the library the math and number theory pattern applies to, grouped by LeetCode's own difficulty rating. 413 of the 485 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Easy (121)

#ProblemDifficultyTopics
9Palindrome NumberEasyMath
13Roman to IntegerEasyHash Table, Math, String
66Plus OneEasyArray, Math
67Add BinaryEasyBit Manipulation, Math, String +1
69Sqrt(x)EasyMath, Binary Search
70Climbing StairsEasyMemoization, Math, Dynamic Programming
168Excel Sheet Column TitleEasyMath, String
171Excel Sheet Column NumberEasyMath, String
202Happy NumberEasyHash Table, Math, Two Pointers
231Power of TwoEasyBit Manipulation, Recursion, Math
258Add DigitsEasyMath, Number Theory, Simulation
263Ugly NumberEasyMath
268Missing NumberEasyBit Manipulation, Array, Hash Table +3
292Nim GameEasyBrainteaser, Math, Game Theory
326Power of ThreeEasyRecursion, Math
342Power of FourEasyBit Manipulation, Recursion, Math
367Valid Perfect SquareEasyMath, Binary Search
405Convert a Number to HexadecimalEasyBit Manipulation, Math, String
412Fizz BuzzEasyMath, String, Simulation
415Add StringsEasyMath, String, Simulation
441Arranging CoinsEasyMath, Binary Search
492Construct the RectangleEasyMath
504Base 7EasyMath, String
507Perfect NumberEasyMath
509Fibonacci NumberEasyRecursion, Memoization, Math +1
598Range Addition IIEasyArray, Math
628Maximum Product of Three NumbersEasyArray, Math, Sorting
728Self Dividing NumbersEasyMath
1071Greatest Common Divisor of StringsEasyMath, String
1137N-th Tribonacci NumberEasyMemoization, Math, Dynamic Programming
762Prime Number of Set Bits in Binary RepresentationEasyBit Manipulation, Math
800Similar RGB ColorPremiumEasyMath, String, Enumeration
812Largest Triangle AreaEasyGeometry, Array, Math
836Rectangle OverlapEasyGeometry, Math
883Projection Area of 3D ShapesEasyGeometry, Array, Math +1
892Surface Area of 3D ShapesEasyGeometry, Array, Math +1
908Smallest Range IEasyArray, Math
914X of a Kind in a Deck of CardsEasyArray, Hash Table, Math +2
976Largest Perimeter TriangleEasyGreedy, Array, Math +1
989Add to Array-Form of IntegerEasyArray, Math
1025Divisor GameEasyBrainteaser, Math, Dynamic Programming +1
1030Matrix Cells in Distance OrderEasyGeometry, Array, Math +2
1037Valid BoomerangEasyGeometry, Array, Math
1056Confusing NumberPremiumEasyMath
1085Sum of Digits in the Minimum NumberPremiumEasyArray, Math
1103Distribute Candies to PeopleEasyMath, Simulation
1118Number of Days in a MonthPremiumEasyMath
1134Armstrong NumberPremiumEasyMath
1154Day of the YearEasyMath, String
1175Prime ArrangementsEasyMath
1180Count Substrings with Only One Distinct LetterPremiumEasyMath, String
1185Day of the WeekEasyMath
1217Minimum Cost to Move Chips to The Same PositionEasyGreedy, Array, Math
1228Missing Number In Arithmetic ProgressionPremiumEasyArray, Math
1232Check If It Is a Straight LineEasyGeometry, Array, Math
1252Cells with Odd Values in a MatrixEasyArray, Math, Simulation
1266Minimum Time Visiting All PointsEasyGeometry, Array, Math
1271HexspeakPremiumEasyMath, String
1281Subtract the Product and Sum of Digits of an IntegerEasyMath
1290Convert Binary Number in a Linked List to IntegerEasyLinked List, Math
1295Find Numbers with Even Number of DigitsEasyArray, Math
1304Find N Unique Integers Sum up to ZeroEasyArray, Math
1317Convert Integer to the Sum of Two No-Zero IntegersEasyMath
1323Maximum 69 NumberEasyGreedy, Math
1342Number of Steps to Reduce a Number to ZeroEasyBit Manipulation, Math
1360Number of Days Between Two DatesEasyMath, String
1399Count Largest GroupEasyHash Table, Math
1427Perform String ShiftsPremiumEasyArray, Math, String
1486XOR Operation in an ArrayEasyBit Manipulation, Math
1512Number of Good PairsEasyArray, Hash Table, Math +1
1518Water BottlesEasyMath, Simulation
1523Count Odd Numbers in an Interval RangeEasyMath
1588Sum of All Odd Length SubarraysEasyArray, Math, Prefix Sum
1688Count of Matches in TournamentEasyMath, Simulation
1716Calculate Money in Leetcode BankEasyMath
1742Maximum Number of Balls in a BoxEasyHash Table, Math, Counting
1812Determine Color of a Chessboard SquareEasyMath, String
1822Sign of the Product of an ArrayEasyArray, Math
1837Sum of Digits in Base KEasyMath
1863Sum of All Subset XOR TotalsEasyBit Manipulation, Array, Math +3
1903Largest Odd Number in StringEasyGreedy, Math, String
1925Count Square Sum TriplesEasyMath, Enumeration
1952Three DivisorsEasyMath, Enumeration, Number Theory
1979Find Greatest Common Divisor of ArrayEasyArray, Math, Number Theory
2119A Number After a Double ReversalEasyMath
2160Minimum Sum of Four Digit Number After Splitting DigitsEasyGreedy, Math, Sorting
2169Count Operations to Obtain ZeroEasyMath, Simulation
2180Count Integers With Even Digit SumEasyMath, Simulation
2235Add Two IntegersEasyMath
2269Find the K-Beauty of a NumberEasyMath, String, Sliding Window
2409Count Days Spent TogetherEasyMath, String
2413Smallest Even MultipleEasyMath, Number Theory
2427Number of Common FactorsEasyMath, Enumeration, Number Theory
2455Average Value of Even Numbers That Are Divisible by ThreeEasyArray, Math
2469Convert the TemperatureEasyMath
2481Minimum Cuts to Divide a CircleEasyGeometry, Math
2485Find the Pivot IntegerEasyMath, Prefix Sum
2520Count the Digits That Divide a NumberEasyMath
2525Categorize Box According to CriteriaEasyMath
2535Difference Between Element Sum and Digit Sum of an ArrayEasyArray, Math
2544Alternating Digit SumEasyMath
2549Count Distinct Numbers on BoardEasyArray, Hash Table, Math +1
2566Maximum Difference by Remapping a DigitEasyGreedy, Math
2578Split With Minimum SumEasyGreedy, Math, Sorting
2582Pass the PillowEasyMath, Simulation
2591Distribute Money to Maximum ChildrenEasyGreedy, Math
2600K Items With the Maximum SumEasyGreedy, Math
2614Prime In DiagonalEasyArray, Math, Matrix +1
2651Calculate Delayed Arrival TimeEasyMath
2652Sum MultiplesEasyMath
2729Check if The Number is FascinatingEasyHash Table, Math
2739Total Distance TraveledEasyMath, Simulation
2748Number of Beautiful PairsEasyArray, Hash Table, Math +2
2769Find the Maximum Achievable NumberEasyMath
2806Account Balance After Rounded PurchaseEasyMath
2843Count Symmetric IntegersEasyMath, Enumeration
2864Maximum Odd Binary NumberEasyGreedy, Math, String
2894Divisible and Non-divisible Sums DifferenceEasyMath
2928Distribute Candies Among Children IEasyMath, Combinatorics, Enumeration
2946Matrix Similarity After Cyclic ShiftsEasyArray, Math, Matrix +1
2965Find Missing and Repeated ValuesEasyArray, Hash Table, Math +1

Medium (244)

#ProblemDifficultyTopics
2Add Two NumbersMediumRecursion, Linked List, Math
7Reverse IntegerMediumMath
12Integer to RomanMediumHash Table, Math, String
29Divide Two IntegersMediumBit Manipulation, Math
43Multiply StringsMediumMath, String, Simulation
48Rotate ImageMediumArray, Math, Matrix
50Pow(x, n)MediumRecursion, Math
62Unique PathsMediumMath, Dynamic Programming, Combinatorics
89Gray CodeMediumBit Manipulation, Math, Backtracking
96Unique Binary Search TreesMediumTree, Binary Search Tree, Math +2
150Evaluate Reverse Polish NotationMediumStack, Array, Math
166Fraction to Recurring DecimalMediumHash Table, Math, String
172Factorial Trailing ZeroesMediumMath
189Rotate ArrayMediumArray, Math, Two Pointers
204Count PrimesMediumArray, Math, Enumeration +1
223Rectangle AreaMediumGeometry, Math
227Basic Calculator IIMediumStack, Math, String
241Different Ways to Add ParenthesesMediumRecursion, Memoization, Math +2
264Ugly Number IIMediumHash Table, Math, Dynamic Programming +1
279Perfect SquaresMediumBreadth-First Search, Math, Dynamic Programming
313Super Ugly NumberMediumArray, Math, Dynamic Programming
319Bulb SwitcherMediumBrainteaser, Math
343Integer BreakMediumMath, Dynamic Programming
357Count Numbers with Unique DigitsMediumMath, Dynamic Programming, Backtracking
365Water and Jug ProblemMediumDepth-First Search, Breadth-First Search, Math
368Largest Divisible SubsetMediumArray, Math, Dynamic Programming +1
371Sum of Two IntegersMediumBit Manipulation, Math
372Super PowMediumMath, Divide and Conquer
375Guess Number Higher or Lower IIMediumMath, Dynamic Programming, Game Theory
380Insert Delete GetRandom O(1)MediumDesign, Array, Hash Table +2
382Linked List Random NodeMediumReservoir Sampling, Linked List, Math +1
384Shuffle an ArrayMediumDesign, Array, Math +1
390Elimination GameMediumRecursion, Math
396Rotate FunctionMediumArray, Math, Dynamic Programming
398Random Pick IndexMediumReservoir Sampling, Hash Table, Math +1
400Nth DigitMediumMath, Binary Search
423Reconstruct Original Digits from EnglishMediumHash Table, Math, String
445Add Two Numbers IIMediumStack, Linked List, Math
447Number of BoomerangsMediumArray, Hash Table, Math
453Minimum Moves to Equal Array ElementsMediumArray, Math
462Minimum Moves to Equal Array Elements IIMediumArray, Math, Sorting
464Can I WinMediumBit Manipulation, Memoization, Math +3
470Implement Rand10() Using Rand7()MediumMath, Rejection Sampling, Probability and Statistics +1
477Total Hamming DistanceMediumBit Manipulation, Array, Math
478Generate Random Point in a CircleMediumGeometry, Math, Rejection Sampling +1
486Predict the WinnerMediumRecursion, Array, Math +2
497Random Point in Non-overlapping RectanglesMediumReservoir Sampling, Array, Math +4
519Random Flip MatrixMediumReservoir Sampling, Hash Table, Math +1
523Continuous Subarray SumMediumArray, Hash Table, Math +1
528Random Pick with WeightMediumArray, Math, Binary Search +2
537Complex Number MultiplicationMediumMath, String, Simulation
539Minimum Time DifferenceMediumArray, Math, String +1
553Optimal DivisionMediumArray, Math, Dynamic Programming
556Next Greater Element IIIMediumMath, Two Pointers, String
592Fraction Addition and SubtractionMediumMath, String, Simulation
593Valid SquareMediumGeometry, Math
633Sum of Square NumbersMediumMath, Two Pointers, Binary Search
640Solve the EquationMediumMath, String, Simulation
6502 Keys KeyboardMediumMath, Dynamic Programming
667Beautiful Arrangement IIMediumArray, Math
670Maximum SwapMediumGreedy, Math
672Bulb Switcher IIMediumBit Manipulation, Depth-First Search, Breadth-First Search +1
738Monotone Increasing DigitsMediumGreedy, Math
973K Closest Points to OriginMediumGeometry, Array, Math +4
294Flip Game IIPremiumMediumMemoization, Math, Dynamic Programming +2
356Line ReflectionPremiumMediumArray, Hash Table, Math
360Sort Transformed ArrayPremiumMediumArray, Math, Two Pointers +1
369Plus One Linked ListPremiumMediumLinked List, Math
469Convex PolygonPremiumMediumGeometry, Array, Math
573Squirrel SimulationPremiumMediumArray, Math
625Minimum FactorizationPremiumMediumGreedy, Math
634Find the Derangement of An ArrayPremiumMediumMath, Dynamic Programming, Combinatorics
6514 Keys KeyboardPremiumMediumMath, Dynamic Programming
750Number Of Corner RectanglesPremiumMediumArray, Math, Dynamic Programming +1
754Reach a NumberMediumMath, Binary Search
775Global and Local InversionsMediumArray, Math
779K-th Symbol in GrammarMediumBit Manipulation, Recursion, Math
781Rabbits in ForestMediumGreedy, Array, Hash Table +1
788Rotated DigitsMediumMath, Dynamic Programming
789Escape The GhostsMediumArray, Math
808Soup ServingsMediumMath, Dynamic Programming, Probability and Statistics
837New 21 GameMediumMath, Dynamic Programming, Sliding Window +1
840Magic Squares In GridMediumArray, Hash Table, Math +1
858Mirror ReflectionMediumGeometry, Math, Number Theory
866Prime PalindromeMediumMath, Number Theory
869Reordered Power of 2MediumHash Table, Math, Counting +2
877Stone GameMediumArray, Math, Dynamic Programming +1
910Smallest Range IIMediumGreedy, Array, Math +1
932Beautiful ArrayMediumArray, Math, Divide and Conquer
939Minimum Area RectangleMediumGeometry, Array, Hash Table +2
957Prison Cells After N DaysMediumBit Manipulation, Array, Hash Table +1
963Minimum Area Rectangle IIMediumGeometry, Array, Hash Table +1
970Powerful IntegersMediumHash Table, Math, Enumeration
991Broken CalculatorMediumGreedy, Math
1006Clumsy FactorialMediumStack, Math, Simulation
1015Smallest Integer Divisible by KMediumHash Table, Math
1017Convert to Base -2MediumMath
1033Moving Stones Until ConsecutiveMediumBrainteaser, Math
1040Moving Stones Until Consecutive IIMediumArray, Math, Sorting +1
1041Robot Bounded In CircleMediumMath, String, Simulation
1058Minimize Rounding Error to Meet TargetPremiumMediumGreedy, Array, Math +2
1073Adding Two Negabinary NumbersMediumArray, Math
1093Statistics from a Large SampleMediumArray, Math, Probability and Statistics
1104Path In Zigzag Labelled Binary TreeMediumTree, Math, Binary Tree
1131Maximum of Absolute Value ExpressionMediumArray, Math
1140Stone Game IIMediumArray, Math, Dynamic Programming +2
1201Ugly Number IIIMediumMath, Binary Search, Combinatorics +1
1215Stepping NumbersPremiumMediumBreadth-First Search, Math, Backtracking
1227Airplane Seat Assignment ProbabilityMediumBrainteaser, Math, Dynamic Programming +1
1230Toss Strange CoinsPremiumMediumArray, Math, Dynamic Programming +1
1237Find Positive Integer Solution for a Given EquationMediumMath, Two Pointers, Binary Search +1
1238Circular Permutation in Binary RepresentationMediumBit Manipulation, Math, Backtracking
1247Minimum Swaps to Make Strings EqualMediumGreedy, Math, String
1248Count Number of Nice SubarraysMediumArray, Hash Table, Math +2
1256Encode NumberPremiumMediumBit Manipulation, Math, String
1276Number of Burgers with No Waste of IngredientsMediumMath
1344Angle Between Hands of a ClockMediumMath
1352Product of the Last K NumbersMediumDesign, Array, Math +2
1362Closest DivisorsMediumMath
1390Four DivisorsMediumArray, Math
1401Circle and Rectangle OverlappingMediumGeometry, Math
1414Find the Minimum Number of Fibonacci Numbers Whose Sum Is KMediumGreedy, Math
1432Max Difference You Can Get From Changing an IntegerMediumGreedy, Math
1442Count Triplets That Can Form Two Arrays of Equal XORMediumBit Manipulation, Array, Hash Table +2
1447Simplified FractionsMediumMath, String, Number Theory
1492The kth Factor of nMediumMath, Number Theory
1513Number of Substrings With Only 1sMediumMath, String
1524Number of Sub-arrays With Odd SumMediumArray, Math, Dynamic Programming +1
1538Guess the Majority in a Hidden ArrayPremiumMediumArray, Math, Interactive
1551Minimum Operations to Make Array EqualMediumMath
1561Maximum Number of Coins You Can GetMediumGreedy, Array, Math +2
1573Number of Ways to Split a StringMediumMath, String
1577Number of Ways Where Square of Number Is Equal to Product of Two NumbersMediumArray, Hash Table, Math +1
1621Number of Sets of K Non-Overlapping Line SegmentsMediumMath, Dynamic Programming, Combinatorics
1628Design an Expression Tree With Evaluate FunctionPremiumMediumStack, Tree, Design +3
1634Add Two Polynomials Represented as Linked ListsPremiumMediumLinked List, Math, Two Pointers
1641Count Sorted Vowel StringsMediumMath, Dynamic Programming, Combinatorics
1648Sell Diminishing-Valued Colored BallsMediumGreedy, Array, Math +3
1680Concatenation of Consecutive Binary NumbersMediumBit Manipulation, Math, Simulation
1685Sum of Absolute Differences in a Sorted ArrayMediumArray, Math, Prefix Sum
1686Stone Game VIMediumGreedy, Array, Math +3
1690Stone Game VIIMediumArray, Math, Dynamic Programming +1
1753Maximum Score From Removing StonesMediumGreedy, Math, Heap (Priority Queue)
1759Count Number of Homogenous SubstringsMediumMath, String
1780Check if Number is a Sum of Powers of ThreeMediumMath
1802Maximum Value at a Given Index in a Bounded ArrayMediumGreedy, Math, Binary Search
1806Minimum Number of Operations to Reinitialize a PermutationMediumArray, Math, Simulation
1814Count Nice Pairs in an ArrayMediumArray, Hash Table, Math +1
1823Find the Winner of the Circular GameMediumRecursion, Queue, Array +2
1828Queries on Number of Points Inside a CircleMediumGeometry, Array, Math
1860Incremental Memory LeakMediumMath, Simulation
1878Get Biggest Three Rhombus Sums in a GridMediumArray, Math, Matrix +3
1884Egg Drop With 2 Eggs and N FloorsMediumMath, Dynamic Programming
1904The Number of Full Rounds You Have PlayedMediumMath, String
1908Game of NimPremiumMediumBit Manipulation, Brainteaser, Array +3
1922Count Good NumbersMediumRecursion, Math
1927Sum GameMediumGreedy, Math, String +1
1954Minimum Garden Perimeter to Collect Enough ApplesMediumMath, Binary Search
1969Minimum Non-Zero Product of the Array ElementsMediumGreedy, Recursion, Math
1999Smallest Greater Multiple Made of Two DigitsPremiumMediumMath, Enumeration
2001Number of Pairs of Interchangeable RectanglesMediumArray, Hash Table, Math +2
2028Find Missing ObservationsMediumArray, Math, Simulation
2029Stone Game IXMediumGreedy, Array, Math +2
2033Minimum Operations to Make a Uni-Value GridMediumArray, Math, Matrix +1
2038Remove Colored Pieces if Both Neighbors are the Same ColorMediumGreedy, Math, String +1
2048Next Greater Numerically Balanced NumberMediumHash Table, Math, Backtracking +2
2063Vowels of All SubstringsMediumMath, String, Dynamic Programming +1
2083Substrings That Begin and End With the Same LetterPremiumMediumHash Table, Math, String +2
2101Detonate the Maximum BombsMediumDepth-First Search, Breadth-First Search, Graph +3
2110Number of Smooth Descent Periods of a StockMediumArray, Math, Two Pointers +2
2125Number of Laser Beams in a BankMediumArray, Math, String +1
2128Remove All Ones With Row and Column FlipsPremiumMediumBit Manipulation, Array, Math +1
2139Minimum Moves to Reach Target ScoreMediumGreedy, Math
2152Minimum Number of Lines to Cover PointsPremiumMediumBit Manipulation, Geometry, Array +5
2162Minimum Cost to Set Cooking TimeMediumMath, Enumeration
2165Smallest Value of the Rearranged NumberMediumMath, Sorting
2177Find Three Consecutive Integers That Sum to a Given NumberMediumMath, Simulation
2178Maximum Split of Positive Even IntegersMediumGreedy, Math, Backtracking
2189Number of Ways to Build House of CardsPremiumMediumMath, Dynamic Programming
2195Append K Integers With Minimal SumMediumGreedy, Array, Math +1
2198Number of Single Divisor TripletsPremiumMediumMath
2217Find Palindrome With Fixed LengthMediumArray, Math
2221Find Triangular Sum of an ArrayMediumArray, Math, Combinatorics +1
2240Number of Ways to Buy Pens and PencilsMediumMath, Enumeration
2249Count Lattice Points Inside a CircleMediumGeometry, Array, Hash Table +2
2266Count Number of TextsMediumHash Table, Math, String +1
2280Minimum Lines to Represent a Line ChartMediumGeometry, Array, Math +2
2310Sum of Numbers With Units Digit KMediumGreedy, Math, Dynamic Programming +1
2317Maximum XOR After OperationsMediumBit Manipulation, Array, Math
2348Number of Zero-Filled SubarraysMediumArray, Math
2358Maximum Number of Groups Entering a CompetitionMediumGreedy, Array, Math +1
2364Count Number of Bad PairsMediumArray, Hash Table, Math +1
2393Count Strictly Increasing SubarraysPremiumMediumArray, Math, Dynamic Programming
2396Strictly Palindromic NumberMediumBrainteaser, Math, Two Pointers
2400Number of Ways to Reach a Position After Exactly k StepsMediumMath, Dynamic Programming, Combinatorics
2417Closest Fair IntegerPremiumMediumMath, Enumeration
2436Minimum Split Into Subarrays With GCD Greater Than OnePremiumMediumGreedy, Array, Math +2
2442Count Number of Distinct Integers After Reverse OperationsMediumArray, Hash Table, Math +1
2443Sum of Number and Its ReverseMediumMath, Enumeration
2447Number of Subarrays With GCD Equal to KMediumArray, Math, Number Theory
2450Number of Distinct Binary Strings After Applying OperationsPremiumMediumMath, String
2457Minimum Addition to Make Integer BeautifulMediumGreedy, Math
2464Minimum Subarrays in a Valid SplitPremiumMediumArray, Math, Dynamic Programming +1
2470Number of Subarrays With LCM Equal to KMediumArray, Math, Number Theory
2489Number of Substrings With Fixed RatioPremiumMediumHash Table, Math, String +1
2495Number of Subarrays Having Even ProductPremiumMediumArray, Math, Dynamic Programming
2505Bitwise OR of All Subsequence SumsPremiumMediumBit Manipulation, Brainteaser, Array +2
2507Smallest Value After Replacing With Sum of Prime FactorsMediumMath, Number Theory, Simulation
2513Minimize the Maximum of Two ArraysMediumMath, Binary Search, Number Theory
2521Distinct Prime Factors of Product of ArrayMediumArray, Hash Table, Math +1
2523Closest Prime Numbers in RangeMediumMath, Number Theory
2527Find Xor-Beauty of ArrayMediumBit Manipulation, Array, Math
2539Count the Number of Good SubsequencesPremiumMediumHash Table, Math, String +2
2541Minimum Operations to Make Array Equal IIMediumGreedy, Array, Math
2550Count Collisions of Monkeys on a PolygonMediumRecursion, Math
2572Count the Number of Square-Free SubsetsMediumBit Manipulation, Array, Math +2
2575Find the Divisibility Array of a StringMediumArray, Math, String
2579Count Total Number of Colored CellsMediumMath
2597The Number of Beautiful SubsetsMediumArray, Hash Table, Math +4
2598Smallest Missing Non-negative Integer After OperationsMediumGreedy, Array, Hash Table +1
2601Prime Subtraction OperationMediumGreedy, Array, Math +2
2607Make K-Subarray Sums EqualMediumGreedy, Array, Math +2
2638Count the Number of K-Free SubsetsPremiumMediumArray, Math, Dynamic Programming +2
2654Minimum Number of Operations to Make All Array Elements Equal to 1MediumArray, Math, Number Theory
2698Find the Punishment Number of an IntegerMediumMath, Backtracking
2745Construct the Longest New StringMediumGreedy, Brainteaser, Math +1
2750Ways to Split Array Into Good SubarraysMediumArray, Math, Dynamic Programming
2761Prime Pairs With Target SumMediumArray, Math, Enumeration +1
2802Find The K-th Lucky NumberPremiumMediumBit Manipulation, Math, String
2807Insert Greatest Common Divisors in Linked ListMediumLinked List, Math, Number Theory
2816Double a Number Represented as a Linked ListMediumStack, Linked List, Math
2829Determine the Minimum Sum of a k-avoiding ArrayMediumGreedy, Math
2834Find the Minimum Possible Sum of a Beautiful ArrayMediumGreedy, Math
2844Minimum Operations to Make a Special NumberMediumGreedy, Math, String +1
2847Smallest Number With Given Digit ProductPremiumMediumGreedy, Math
2849Determine if a Cell Is Reachable at a Given TimeMediumMath
2929Distribute Candies Among Children IIMediumMath, Combinatorics, Enumeration
2930Number of Strings Which Can Be Rearranged to Contain SubstringMediumMath, Dynamic Programming, Combinatorics
2939Maximum Xor ProductMediumGreedy, Bit Manipulation, Math
2947Count Beautiful Substrings IMediumHash Table, Math, String +3
2961Double Modular ExponentiationMediumArray, Math, Simulation
2967Minimum Cost to Make Array EqualindromicMediumGreedy, Array, Math +2
2979Most Expensive Item That Can Not Be BoughtPremiumMediumMath, Dynamic Programming, Number Theory
2992Number of Self-Divisible PermutationsPremiumMediumBit Manipulation, Array, Math +4

Hard (120)

#ProblemDifficultyTopics
60Permutation SequenceHardRecursion, Math
149Max Points on a LineHardGeometry, Array, Hash Table +1
224Basic CalculatorHardStack, Recursion, Math +1
233Number of Digit OneHardRecursion, Math, Dynamic Programming
273Integer to English WordsHardRecursion, Math, String
282Expression Add OperatorsHardMath, String, Backtracking
335Self CrossingHardGeometry, Array, Math
381Insert Delete GetRandom O(1) - Duplicates allowedHardDesign, Array, Hash Table +2
391Perfect RectangleHardGeometry, Array, Hash Table +2
458Poor PigsHardMath, Dynamic Programming, Combinatorics
479Largest Palindrome ProductHardMath, Enumeration
483Smallest Good BaseHardMath, Binary Search
564Find the Closest PalindromeHardMath, String
587Erect the FenceHardGeometry, Array, Math
668Kth Smallest Number in Multiplication TableHardMath, Binary Search
67924 GameHardArray, Math, Backtracking
710Random Pick with BlacklistHardArray, Hash Table, Math +3
296Best Meeting PointPremiumHardArray, Math, Matrix +1
660Remove 9PremiumHardMath
770Basic Calculator IVHardStack, Recursion, Hash Table +2
772Basic Calculator IIIPremiumHardStack, Recursion, Math +1
780Reaching PointsHardMath
782Transform to ChessboardHardBit Manipulation, Array, Math +1
793Preimage Size of Factorial Zeroes FunctionHardMath, Binary Search
805Split Array With Same AverageHardBit Manipulation, Array, Math +2
810Chalkboard XOR GameHardBit Manipulation, Brainteaser, Array +2
829Consecutive Numbers SumHardMath, Enumeration
843Guess the WordHardArray, Math, String +2
878Nth Magical NumberHardMath, Binary Search
887Super Egg DropHardMath, Binary Search, Dynamic Programming
891Sum of Subsequence WidthsHardArray, Math, Sorting
899Orderly QueueHardMath, String, Sorting
902Numbers At Most N Given Digit SetHardArray, Math, String +2
906Super PalindromesHardMath, String, Enumeration
913Cat and MouseHardGraph, Topological Sort, Memoization +3
920Number of Music PlaylistsHardMath, Dynamic Programming, Combinatorics
927Three Equal PartsHardArray, Math
952Largest Component Size by Common FactorHardUnion Find, Array, Hash Table +2
964Least Operators to Express NumberHardMemoization, Math, Dynamic Programming
972Equal Rational NumbersHardMath, String
996Number of Squareful ArraysHardBit Manipulation, Array, Hash Table +4
1012Numbers With Repeated DigitsHardMath, Dynamic Programming
1067Digit Count in RangePremiumHardMath, Dynamic Programming
1088Confusing Number IIPremiumHardMath, Backtracking
1183Maximum Number of OnesPremiumHardGreedy, Math, Sorting +1
1199Minimum Time to Build BlocksPremiumHardGreedy, Array, Math +1
1250Check If It Is a Good ArrayHardArray, Math, Number Theory
1259Handshakes That Don't CrossPremiumHardMath, Dynamic Programming
1307Verbal Arithmetic PuzzleHardArray, Math, String +1
1330Reverse Subarray To Maximize Array ValueHardGreedy, Array, Math
1359Count All Valid Pickup and Delivery OptionsHardMath, Dynamic Programming, Combinatorics
1363Largest Multiple of ThreeHardGreedy, Array, Math +2
1406Stone Game IIIHardArray, Math, Dynamic Programming +1
1453Maximum Number of Darts Inside of a Circular DartboardHardGeometry, Array, Math
1467Probability of a Two Boxes Having The Same Number of Distinct BallsHardArray, Math, Dynamic Programming +3
1478Allocate MailboxesHardArray, Math, Dynamic Programming +1
1510Stone Game IVHardMath, Dynamic Programming, Game Theory
1515Best Position for a Service CentreHardGeometry, Array, Math +1
1563Stone Game VHardArray, Math, Dynamic Programming +1
1569Number of Ways to Reorder Array to Get Same BSTHardTree, Union Find, Binary Search Tree +7
1610Maximum Number of Visible PointsHardGeometry, Array, Math +2
1622Fancy SequenceHardDesign, Segment Tree, Math
1627Graph Connectivity With ThresholdHardUnion Find, Array, Math +1
1643Kth Smallest InstructionsHardArray, Math, Dynamic Programming +1
1728Cat and Mouse IIHardGraph, Topological Sort, Memoization +5
1735Count Ways to Make Array With ProductHardArray, Math, Dynamic Programming +2
1739Building BoxesHardGreedy, Math, Binary Search
1766Tree of CoprimesHardTree, Depth-First Search, Array +2
1776Car Fleet IIHardStack, Array, Math +2
1799Maximize Score After N OperationsHardBit Manipulation, Array, Math +4
1808Maximize Number of Nice DivisorsHardRecursion, Math, Number Theory
1819Number of Different Subsequences GCDsHardArray, Math, Counting +1
1830Minimum Number of Operations to Make String SortedHardMath, String, Combinatorics
1835Find XOR Sum of All Pairs Bitwise ANDHardBit Manipulation, Array, Math
1840Maximum Building HeightHardArray, Math, Sorting
1862Sum of Floored PairsHardArray, Math, Binary Search +1
1866Number of Ways to Rearrange Sticks With K Sticks VisibleHardMath, Dynamic Programming, Combinatorics
1872Stone Game VIIIHardArray, Math, Dynamic Programming +2
1896Minimum Cost to Change the Final Value of ExpressionHardStack, Math, String +1
1916Count Ways to Build Rooms in an Ant ColonyHardTree, Graph, Topological Sort +3
1924Erect the Fence IIPremiumHardGeometry, Array, Math
1956Minimum Time For K Virus Variants to SpreadPremiumHardGeometry, Array, Math +2
1994The Number of Good SubsetsHardBit Manipulation, Array, Hash Table +5
1998GCD Sort of an ArrayHardUnion Find, Array, Math +2
2005Subtree Removal Game with Fibonacci TreePremiumHardTree, Math, Dynamic Programming +2
2019The Score of Students Solving Math ExpressionHardStack, Memoization, Array +4
2081Sum of k-Mirror NumbersHardMath, Enumeration
2117Abbreviating the Product of a RangeHardMath
2147Number of Ways to Divide a Long CorridorHardMath, String, Dynamic Programming
2183Count Array Pairs Divisible by KHardArray, Math, Number Theory
2197Replace Non-Coprime Numbers in ArrayHardStack, Array, Math +1
2338Count the Number of Ideal ArraysHardMath, Dynamic Programming, Combinatorics +1
2344Minimum Deletions to Make Array DivisibleHardArray, Math, Number Theory +2
2366Minimum Replacements to Sort the ArrayHardGreedy, Array, Math
2376Count Special IntegersHardMath, Dynamic Programming
2440Create Components With Same ValueHardTree, Depth-First Search, Array +2
2514Count AnagramsHardHash Table, Math, String +2
2524Maximum Frequency Score of a SubarrayPremiumHardStack, Array, Hash Table +2
2543Check if Point Is ReachableHardMath, Number Theory
2584Split the Array to Make Coprime ProductsHardArray, Hash Table, Math +1
2613Beautiful PairsPremiumHardGeometry, Array, Math +3
2647Color the Triangle RedPremiumHardArray, Math
2681Power of HeroesHardArray, Math, Dynamic Programming +2
2709Greatest Common Divisor TraversalHardUnion Find, Array, Math +1
2719Count of IntegersHardMath, String, Dynamic Programming
2790Maximum Number of Groups With Increasing LengthHardGreedy, Array, Math +2
2818Apply Operations to Maximize ScoreHardStack, Greedy, Array +4
2827Number of Beautiful Integers in the RangeHardMath, Dynamic Programming
2842Count K-Subsequences of a String With Maximum BeautyHardGreedy, Hash Table, Math +2
2851String TransformationHardMath, String, Dynamic Programming +1
2862Maximum Element-Sum of a Complete Subset of IndicesHardArray, Math, Number Theory
2867Count Valid Paths in a TreeHardTree, Depth-First Search, Math +2
2868The Wording GamePremiumHardGreedy, Array, Math +3
2912Number of Ways to Reach Destination in the GridPremiumHardMath, Dynamic Programming, Combinatorics
2927Distribute Candies Among Children IIIPremiumHardMath, Combinatorics
2941Maximum GCD-Sum of a SubarrayPremiumHardArray, Math, Binary Search +1
2949Count Beautiful Substrings IIHardHash Table, Math, String +2
2954Count the Number of Infection SequencesHardArray, Math, Combinatorics
2963Count the Number of Good PartitionsHardArray, Hash Table, Math +1
2999Count the Number of Powerful IntegersHardMath, String, Dynamic Programming

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

Math and Number Theory pattern FAQ

What is the math and number theory pattern?

Some problems have no algorithm worth writing because they have a formula. The tell is a statement about digits, divisors, remainders, or counting arrangements, together with a constraint large enough — 10⁹ and up — that any loop over the input range is hopeless by construction.

How many LeetCode problems use the math and number theory pattern?

This page lists 485 LeetCode problems that the math and number theory pattern applies to: 121 Easy, 244 Medium and 120 Hard. 413 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the math and number theory pattern?

O(log n) or O(1) time and O(1) space. The point of the pattern is that there is no loop over the input: a closed form is O(1), the Euclidean algorithm for a greatest common divisor is O(log min(a, b)), and fast exponentiation raises to the nth power in O(log n) multiplications. A sieve is the exception that costs real time and memory — O(n log log n) to build and O(n) to hold — and is only worth it when many primes below a bound are needed rather than a single primality test.

When should I use the math and number theory pattern in an interview?

The constraints are far too large to iterate, so the answer must be computed rather than searched. The statement is about digits, divisibility, remainders, primes, or gcd.

Which math and number theory problem should I start with?

LeetCode 9. Palindrome Number is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to math and number theory?

Bit Manipulation, Dynamic Programming, Greedy, Prefix Sum. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.

Meet the math and number theory problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer is saying — while staying invisible to screen sharing.