Katkat

Format an Integer with Thousands Separators

Hudson River TradingSoftware Engineer · Technical Screen

Last updated

Implement a function that formats a signed integer with a custom thousands separator character without relying on built-in string formatting utilities.

Problem Statement

Given a 64-bit signed integer n and a separator character sep, return the string representation of n with sep inserted after every group of three digits counting from right to left.

Your solution should handle negative values properly (the negative sign - should remain at the very front of the resulting string and should not be separated from adjacent digits). Do not use built-in number formatting libraries such as Python's f"{n:,}", str.format(), or standard locale-based formatters.

Function Signature

def format_integer(n: int, sep: str = ",") -> str:
    pass

Examples

Example 1

Input: n = 1234567, sep = ","
Output: "1,234,567"
Explanation: Grouping every 3 digits from the right gives 1, 234, and 567 separated by commas.

Example 2

Input: n = -9876543210, sep = "."
Output: "-9.876.543.210"
Explanation: The negative sign is preserved at the front, and periods are inserted every three digits from right to left.

Example 3

Input: n = 0, sep = ","
Output: "0"
Explanation: Zero requires no separators.

Constraints

  • -2^63 <= n <= 2^63 - 1
  • sep is a single ASCII character (e.g., ',', '.' , '_').
  • Time complexity should be O(d) where d is the number of digits in n.
  • Auxiliary space complexity should be O(d) to store the resulting characters.

Edge Cases to Consider

  • n = 0.
  • Negative numbers where abs(n) == 2^63 (avoid 64-bit integer overflow when taking absolute value in systems like C++).
  • Numbers with fewer than 4 digits (no separator needed).
  • Numbers whose digit counts are exact multiples of 3 (e.g., 123456 -> "123,456" without a leading separator).

Hints

Hint 1

Work from the least significant digit to the most significant digit (right-to-left) using modulo and division operations to avoid converting the entire number directly via built-in formatting.

Hint 2

Collect characters or digit chunks in a list, track the count of processed digits, and insert the separator whenever the count is a positive multiple of 3 and more digits remain.

Hint 3

Pay special attention to negative values: record the sign early, work with the magnitude, and append the negative sign at the very end before reversing the result.

Follow-up questions

  • How would you extend this function to support floating-point numbers with fixed decimal precision?
  • In languages like C++ where `abs(-2^63)` overflows a signed 64-bit integer, how do you handle the minimum integer value safely?
  • How would you optimize this implementation for high-throughput logging to avoid intermediate heap allocations?