Subtract Two Large Number Strings
Updated
Problem statement
You are given two non-negative integers num1 and num2, each written as a string of decimal digits. num1 is at least as large as num2, so the difference is never negative.
Return num1 - num2 as a string of decimal digits with no leading zeros. If the difference is zero, return "0".
The numbers can be much longer than any built-in integer type. Do not convert a whole string into a number: no Integer.parseInt, BigInteger, int() on the full string, or similar big-number helpers. Work digit by digit.
Function
subtractStrings(num1: String, num2: String) → StringExamples
Example 1
num1 = "34783783211748"num2 = "923048230"return = "34782860163518"34783783211748 - 923048230 = 34782860163518. The shorter number lines up with the last nine digits ofnum1.
Example 2
num1 = "1000"num2 = "1"return = "999"- The ones column needs a borrow, and the borrow passes through two zeros before it reaches the 1. The answer is
999, which has no leading zero.
Example 3
num1 = "5"num2 = "5"return = "0"- Equal numbers give
0, written as a single digit.
Constraints
1 <= num1.length, num2.length <= 104num1andnum2contain only the digits0to9.- Neither number has a leading zero, except the number
0itself. num1 >= num2as integers.
More StackAdapt interview questions
- Running Medians and PercentilesPHONE SCREEN · Seen Aug 2026
- Nested Recipe Inventory ManagerPHONE SCREEN · Seen Jul 2026
- Build a Tree from Preorder and Inorder TraversalsONSITE INTERVIEW · Seen Sep 2026
- Maximum Bananas Delivered by a CamelONSITE INTERVIEW · Seen Sep 2026
- Reservoir Sampling with Recorded DrawsONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Fair Coin from a Biased CoinAnthropic · PHONE SCREENAnthropic interview questions
- Fizz and Buzz Words From 1 to nDocuSign · PHONE SCREENDocuSign interview questions
- Fizz BuzzBloomberg LP · PHONE SCREENBloomberg LP interview questions
- Double-Base PalindromesxAI · PHONE SCREENxAI interview questions
- Add Signed Character ArraysByteDance · PHONE SCREENByteDance interview questions
- Per-Segment SpeedingOnePay · PHONE SCREENOnePay interview questions
- Add Decimal Strings ExactlyMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Format a Centered Pagination BarMixpanel · PHONE SCREENMixpanel interview questions
- Get Max DeletionsJP Morgan Chase · OAJP Morgan Chase interview questions
- Add Two Numeric Strings with CarryZipRecruiter · ONSITE INTERVIEWZipRecruiter interview questions