Math Coding Problems: 213 Questions with Solutions
213 math coding problems — 108 easy · 80 medium · 25 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 8-day plan.
- Problems: 213
- By difficulty: 108 easy · 80 medium · 25 hard
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
- Cost: Free on every plan; sign in to run and submit
Problems whose solution is a fact about numbers rather than a data structure: digit sums, divisibility, parity, arithmetic sequences, geometry on a grid, and the integer overflow and truncating division that trip a correct idea. The habit these build is to look for a closed form or an invariant before reaching for a loop.
How math works, step by step
x = 1234321- Is 1234321 a palindrome? Rather than make a string, peel digits off the end: x % 10 is the last digit and x // 10 drops it. Each peeled digit is appended to rev as rev × 10 + digit, so rev grows into the right half read backwards.
- The last digit of 1234321 is 1234321 % 10 = 1; it moves onto rev, which becomes 0 × 10 + 1 = 1, and x becomes 1234321 // 10 = 123432. x is still the larger, so the two halves have not met yet.
- The last digit of 123432 is 123432 % 10 = 2; it moves onto rev, which becomes 1 × 10 + 2 = 12, and x becomes 123432 // 10 = 12343. x is still the larger, so the two halves have not met yet.
- The last digit of 12343 is 12343 % 10 = 3; it moves onto rev, which becomes 12 × 10 + 3 = 123, and x becomes 12343 // 10 = 1234. x is still the larger, so the two halves have not met yet.
- The last digit of 1234 is 1234 % 10 = 4; it moves onto rev, which becomes 123 × 10 + 4 = 1234, and x becomes 1234 // 10 = 123. Now x (123) is no larger than rev (1234): rev holds the right half, so the peeling stops.
- 7 digits is odd, so rev also took the middle digit 4; rev // 10 = 123 drops it. x = 123 and rev // 10 = 123 are equal, so the left half matches the right half read backwards.
- 1234321 is a palindrome. Only half its digits were peeled, so the test is O(log n) time and O(1) space, with no string and no full reverse to overflow; negative numbers and numbers ending in 0 are ruled out before the loop.
Math study plan
14 of the 213 Math problems (4 easy, 7 medium and 3 hard) over 8 days, about 8 h 10 min in all — the pattern first, then easiest to hardest. After that, the other 199 in the full list below are practice at your own pace. Then move on to Two Pointers.
Day 1
Learn the pattern: read the essentials and step through the walkthrough above, then solve these 3.
Day 2
Medium problems: the same pattern with one twist each. Name the twist before you code.
- Missing Number Easy
- Continuous Subarray Sum Medium
Day 3
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
Day 4
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Ugly Number II Medium
- Rotate Image Medium
Day 5
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Sum of Two Integers Medium
- Reverse Integer Medium
Day 6
Hard problems: the pattern combined with a second idea. Give each a full attempt before reading the editorial.
- Stone Game IV Hard
Day 7
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
- Max Points on a Line Hard
Day 8
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Math: the essentials
When to reach for it
Numbers too large to loop up to (n up to 10⁹ or beyond), questions about digits, remainders or parity, and an operation repeated so often that it must settle into a pattern. If the brute force is "simulate a billion steps", the intended answer is a formula, a cycle or an invariant.
The pattern
Work the small cases by hand and tabulate them; the rule often shows within the first half-dozen. Take digits off an integer with n % 10 and n // 10 rather than converting to a string, which keeps sign and overflow handling explicit. Check a result against the type's limit before the operation that could exceed it, not after.
def reverse(x): # 32-bit signed result, or 0
LIMIT = 2**31 - 1
sign, x, out = (-1 if x < 0 else 1), abs(x), 0
while x:
x, d = divmod(x, 10)
if out > (LIMIT - d) // 10: # out * 10 + d would overflow
return 0
out = out * 10 + d
return sign * out
Cost
A digit loop is O(log n), trial division up to √n is O(√n), and a closed form is O(1). That gap is the point: for n = 10¹² a loop to n never finishes, while a loop to √n is a million steps.
Common mistakes
- Overflow in a 32-bit
int:a * bora + bcan pass 2³¹ − 1 long before the final answer does. Widen to 64 bits first. - Division and remainder with negatives: in Java and C++
-7 / 2is-3and-7 % 2is-1(JavaScript's%agrees); in Python-7 // 2is-4and-7 % 2is1. - Using floating point for an integer question:
sqrtorpowcan return 2.9999… for an exact square, so confirm with integer arithmetic. - Forgetting 0, 1 and negative inputs, which most formulas treat specially.
Start with
- Palindrome Number: digits without a string.
- Plus One: carrying through a number held as digits.
- Reverse Integer: the overflow check before it happens.
All math problems
Easy (108)
- Type of Triangle Array, Sorting
- Calculate Delayed Arrival Time
- Number of Beautiful Pairs Array, Hash Table, Counting
- Find the Integer Added to Array I Array
- Find the Child Who Has the Ball After K Seconds Simulation
- Minimum Time Visiting All Points Array, Geometry
- Prime In Diagonal Array, Matrix, Number Theory
- Maximum Difference by Remapping a Digit Greedy
- Alternating Digit Sum
- Minimum Amount of Time to Fill Cups Array, Greedy, Heap
- Sqrt(x) Binary Search
- Find the K-Beauty of a Number String, Sliding Window
- Smallest Number With All Set Bits Bit Manipulation
- Complement of Base 10 Integer Bit Manipulation
- Count Total Number of Colored Cells Simulation
- Find the Maximum Divisibility Score Array, Counting
- Construct the Rectangle Number Theory
- Sum of Squares of Special Elements Array, Number Theory
- Count Distinct Numbers on Board Simulation, Number Theory
- Sum Multiples Number Theory
- Split With Minimum Sum Greedy, Sorting
- Number of Even and Odd Bits Bit Manipulation
- Find the Pivot Integer Prefix Sum
- Check if The Number is Fascinating Hash Table, String
- Find Missing and Repeated Values Matrix, Hash Table
- Count the Digits That Divide a Number
- Number of Common Factors Number Theory, Enumeration
- Smallest Even Multiple Number Theory
- Count Symmetric Integers Enumeration
- Distribute Money to Maximum Children Greedy
- Find the Maximum Achievable Number
- Find the Winning Player in Coin Game Game Theory
- Account Balance After Rounded Purchase
- Divisible and Non-Divisible Sums Difference
- Largest Odd Number in String String, Greedy
- Check If It Is a Straight Line Array, Geometry
- Maximum Number of Balls in a Box Hash Table, Counting
- Count Square Sum Triples Enumeration
- Count Integers With Even Digit Sum Simulation
- Sum of Digits in Base K
- Three Divisors Number Theory
- Minimum Sum of Four Digit Number After Splitting Digits Greedy, Sorting
- Count of Matches in Tournament Simulation
- Add to Array-Form of Integer Array
- Check If Word Equals Summation of Two Words String
- Determine Color of a Chessboard Square String
- Count Substrings with Only One Distinct Letter String
- Greatest Common Divisor of Strings String
- Count Operations to Obtain Zero Simulation
- Sign of the Product of an Array Array
- Count Largest Group Hash Table
- Find N Unique Integers Sum up to Zero Array
- Distribute Candies to People Array, Simulation
- X of a Kind in a Deck of Cards Array, Number Theory
- Count Odd Numbers in an Interval Range
- Water Bottles Simulation
- Sum of All Subset XOR Totals Array, Backtracking, Bit Manipulation
- XOR Operation in an Array Bit Manipulation, Simulation
- Nim Game Brainteaser, Game Theory
- Base 7
- Convert a Number to Hexadecimal Bit Manipulation
- Prime Number of Set Bits in Binary Representation Bit Manipulation
- Power of Four Bit Manipulation, Recursion
- Maximum Product of Three Numbers Array, Sorting
- Smallest Range I Array
- Largest Perimeter Triangle Array, Greedy, Sorting
- Minimum Cost to Move Chips to The Same Position Array, Greedy
- Divisor Game Dynamic Programming, Brainteaser, Game Theory
- Projection Area of 3D Shapes Array, Geometry, Matrix
- Matrix Cells in Distance Order Array, Matrix, Sorting
- Cells with Odd Values in a Matrix Array, Simulation
- Difference Between Element Sum and Digit Sum of an Array Array
- Sum of All Odd Length Subarrays Array, Prefix Sum
- Number of Good Pairs Array, Hash Table, Counting
- Maximum 69 Number Greedy
- Find Numbers with Even Number of Digits Array
- Subtract the Product and Sum of Digits of an Integer
- Number of Steps to Reduce a Number to Zero Bit Manipulation
- Self Dividing Numbers
- Find Greatest Common Divisor of Array Array, Number Theory
- Prime Factorisation Number Theory
- Perfect Number
- Harshad Number
- Disarium Number
- Neon Number
- Automorphic Number String
- Strong Number
- Armstrong Number
- N-th Tribonacci Number Dynamic Programming, Memoization
- Fibonacci Number Dynamic Programming, Recursion
- Add Strings String, Simulation
- Plus One Array
- Add Binary String, Bit Manipulation, Simulation
- Roman to Integer Hash Table, String
- Excel Sheet Column Title String
- Excel Sheet Column Number String
- Power of Three Recursion
- Power of Two Bit Manipulation
- Add Digits Simulation, Number Theory
- Ugly Number
- Happy Number Hash Table, Two Pointers
- Arranging Coins Binary Search
- Valid Perfect Square Binary Search
- Sqrt(x) Binary Search
- Missing Number Array, Bit Manipulation
- Climbing Stairs Dynamic Programming, Memoization
- Fizz Buzz String, Simulation
- Palindrome Number
Medium (80)
- Find the Winner of the Circular Game Array, Recursion, Simulation
- Stone Game VII Array, Dynamic Programming, Game Theory
- Number of Ways to Divide a Long Corridor String, Dynamic Programming
- Count Ways to Group Overlapping Ranges Array, Sorting
- Count Number of Ways to Place Houses Dynamic Programming
- Count Number of Texts Hash Table, String, Dynamic Programming
- Number of Ways to Reach a Position After Exactly k Steps Dynamic Programming, Combinatorics
- Count Number of Homogenous Substrings String
- Count Substrings Starting and Ending with Given Character String, Counting
- Sum of Digit Differences of All Pairs Array, Hash Table, Counting
- Water Bottles II Simulation
- Determine the Minimum Sum of a k-avoiding Array Array, Greedy
- Maximum Score From Removing Stones Greedy, Heap (Priority Queue)
- Detonate the Maximum Bombs Array, Graph, Depth-First Search
- Number of Corner Rectangles Array, Matrix, Dynamic Programming
- Find the N-th Value After K Seconds Array, Simulation, Prefix Sum
- Count Alternating Subarrays Array, Dynamic Programming
- Stone Game IX Array, Greedy, Counting
- Smallest Missing Non-negative Integer After Operations Array, Hash Table, Greedy
- Maximum Split of Positive Even Integers Greedy
- Find Three Consecutive Integers That Sum to a Given Number Simulation
- Maximum Value at a Given Index in a Bounded Array Binary Search, Greedy
- Sort Transformed Array Array, Two Pointers, Sorting
- Sum of Square Numbers Two Pointers, Binary Search
- Find the Xor-Beauty of Array Bit Manipulation, Array, Brainteaser
- Maximum Value of an Ordered Triplet I Array, Prefix Sum
- Super Ugly Number Dynamic Programming, Heap
- Minimum Moves to Reach Target Score Greedy
- The kth Factor of n Number Theory
- Clumsy Factorial Stack, Simulation
- Reordered Power of 2 Counting, Enumeration
- Closest Divisors Number Theory
- Prime Subtraction Operation Array, Greedy, Number Theory
- Smallest Value After Replacing With Sum of Prime Factors Number Theory, Simulation
- Number of Zero-Filled Subarrays Array, Counting
- Number of Boomerangs Hash Table, Array
- Number of Pairs of Interchangeable Rectangles Array, Hash Table, Counting
- Count Nice Pairs in an Array Array, Hash Table, Counting
- Number of Ways to Split a String String, Counting
- Unique Binary Search Trees Dynamic Programming
- Minimum Operations to Make Array Equal
- Reach a Number Binary Search
- Smallest Value of the Rearranged Number Sorting
- Check if Number is a Sum of Powers of Three Number Theory
- Minimum Moves to Equal Array Elements II Array, Sorting
- Minimum Moves to Equal Array Elements Array
- Rotate Function Array, Dynamic Programming
- Nth Digit Binary Search
- Bulb Switcher Brainteaser
- Count Triplets That Can Form Two Arrays of Equal XOR Array, Hash Table, Bit Manipulation
- Divide Two Integers Bit Manipulation
- Concatenation of Consecutive Binary Numbers Bit Manipulation, Simulation
- Gray Code Backtracking, Bit Manipulation
- Sum of Two Integers Bit Manipulation
- Total Hamming Distance Array, Bit Manipulation
- Basic Calculator II String, Stack
- Next Greater Element III Two Pointers, String
- K Closest Points to Origin Array, Divide and Conquer, Geometry
- Monotone Increasing Digits Greedy
- Maximum Swap Greedy
- Maximum Number of Coins You Can Get Array, Greedy, Sorting
- 2 Keys Keyboard Dynamic Programming
- Stone Game Array, Dynamic Programming, Game Theory
- Count Numbers with Unique Digits Dynamic Programming, Backtracking
- Ugly Number II Hash Table, Dynamic Programming, Heap
- Integer Break Dynamic Programming
- Perfect Squares Dynamic Programming, Breadth-First Search
- Count Sorted Vowel Strings Dynamic Programming, Combinatorics
- Count Number of Nice Subarrays Array, Hash Table, Sliding Window
- Continuous Subarray Sum Array, Hash Table, Prefix Sum
- Integer to Roman Hash Table, String, Greedy
- Factorial Trailing Zeroes
- Count Primes Sieve of Eratosthenes
- Reverse Integer
- Rotate Image Array, Matrix
- Unique Paths Dynamic Programming, Combinatorics
- Evaluate Reverse Polish Notation Array, Stack
- Multiply Strings String, Simulation
- String to Integer (atoi) String
- Rotate Array Array, Two Pointers
Hard (25)
- Count Ways to Make Array With Product Array, Dynamic Programming, Combinatorics
- Count the Number of Ideal Arrays Dynamic Programming, Combinatorics, Number Theory
- Number of Ways to Rearrange Sticks With K Sticks Visible Dynamic Programming, Combinatorics
- The Number of Good Subsets Array, Dynamic Programming, Bit Manipulation
- Number of Ways to Reorder Array to Get Same BST Array, Divide and Conquer, Dynamic Programming
- Minimum Replacements to Sort the Array Array, Greedy
- Stone Game VIII Array, Dynamic Programming, Prefix Sum
- Allocate Mailboxes Array, Dynamic Programming, Sorting
- Count All Valid Pickup and Delivery Options Dynamic Programming, Combinatorics
- Count Special Integers Dynamic Programming, Combinatorics
- Count Anagrams Hash Table, String, Combinatorics
- Apply Operations to Maximize Score Array, Stack, Greedy
- Construct Target Array With Multiple Sums Array, Heap (Priority Queue)
- Largest Component Size by Common Factor Array, Union Find, Number Theory
- Number of Music Playlists Dynamic Programming, Combinatorics
- Kth Smallest Number in Multiplication Table Binary Search
- Count the Number of Square-Free Subsets Bit Manipulation, Dynamic Programming, Bitmask
- Minimum One Bit Operations to Make Integers Zero Bit Manipulation, Dynamic Programming
- Smallest Good Base Binary Search, Number Theory
- Number of Digit One Digit DP, Recursion
- Preimage Size of Factorial Zeroes Function Binary Search, Number Theory
- Nth Magical Number Binary Search, Number Theory
- Largest Multiple of Three Array, Greedy, Dynamic Programming
- Max Points on a Line Hash Table, Geometry
- Stone Game IV Dynamic Programming, Game Theory
Companies that ask math problems
- Amazon 185 problems on math
- Google 105 problems on math
- Adobe 56 problems on math
- TCS 37 problems on math
- Infosys 32 problems on math
- Microsoft 32 problems on math
- Meta 25 problems on math
- Wipro 12 problems on math
- Zoho 11 problems on math
- Apple 9 problems on math
- Capgemini 9 problems on math
- Cognizant 8 problems on math
Next topic: Two Pointers