Integer to String with Thousands Separators, Including Negative Numbers
Company: Hudson River Trading
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Convert a 32-bit signed integer to its decimal string with commas between groups of three digits, so 1234 becomes 1,234, while handling negative numbers, zero and the most negative value. A variant of classic integer-to-string conversion that tests digit extraction and grouping edge cases.
Read the full Hudson River Trading Software Engineer interview experience this question came from
Constraints
- -2^31 <= n <= 2^31 - 1
- For n = -2^31 the absolute value is 2^31, which exceeds 2^31 - 1, so an implementation in a fixed-width integer type must not negate it in 32 bits (Java and C++ receive an int and should widen it to long / long long first).
Examples
Input: (0,)
Expected Output: '0'
Explanation: Minimum valid: zero is returned as the string 0 with no sign and no comma.
Input: (1,)
Expected Output: '1'
Explanation: Single positive digit, no comma.
Hints
- Deal with the minus sign separately from the digits: it belongs directly in front of the first group, never next to a comma.
- Groups are counted from the rightmost digit, so only the leftmost group may have fewer than three digits, and inner groups such as 000 keep their zeros.
- The absolute value of -2^31 does not fit in a 32-bit signed integer, so choose a wider type before negating.