I started okay, figured out I needed to handle the sign first by comparing which string was larger, then do the actual subtraction on the bigger minus the smaller.
First, compare the two strings as numbers to determine the sign of the result and which number is larger. Then, perform digit-by-digit subtraction from right to left, handling borrows, and finally strip leading zeros from the result. If the result is negative, prepend a minus sign.
Pro tip: Clarify with the interviewer whether the inputs are guaranteed to be valid non-negative integers and whether the result should be returned as a string without leading zeros. Also, mention that you'll handle edge cases like equal numbers and zeros.
Compare the lengths of the two strings; if lengths differ, the longer string represents the larger number. If lengths are equal, compare lexicographically to determine which is larger. Based on this, decide the sign of the result and which number to subtract from which.
Ensure the larger number is the minuend and the smaller is the subtrahend. Pad the shorter string with leading zeros to align digits for subtraction.
Iterate from the least significant digit (rightmost) to the most significant. For each digit, subtract the subtrahend digit and any borrow from the minuend digit. If the result is negative, add 10 and set borrow to 1; otherwise, set borrow to 0. Build the result string in reverse order.
After the loop, if there is a remaining borrow, it indicates an error (should not happen if the larger number was chosen correctly). Remove any leading zeros from the result string. If the result is empty, return '0'.
If the original comparison indicated that num1 < num2, prepend a minus sign to the result. Return the final string.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.