Talentd
FleetCode
Make and follow sheets.Sign in

Thousand Separator solution and explanation

EasyString4 min read53.7% acceptanceUpdated 9 Apr 2026
LeetCode in Python 1556. Thousand Separator - Michelle小梦想家Michelle小梦想家 · 25:36 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode in Python 1556. Thousand Separator - Michelle小梦想家Michelle小梦想家 · 25:36 · 1K views
  2. தமிழ் | THOUSAND SEPARATOR | LEETCODE 1556 | leetcode easy problem | leetcode string problem| javaAlgo Tamizha · 6:42 · 879 views
  3. LeetCode 1556. Thousand Separator - Interview Prep Ep 93Fisher Coder · 6:16 · 762 views
  4. thousand separator leetcode | leetcode 1556 | StringNaresh Gupta · 6:56 · 685 views
  5. 1556. Thousand SeparatorChhavi Bansal · 5:40 · 611 views
  6. LeetCode 1556 Thousand Separator | Python 刷題 | Coding KevinCoding Kevin BKH · 6:06 · 556 views
  7. 1556. Thousand Separator (Leetcode Easy)Programming Live with Larry · 3:45 · 272 views
  8. LeetCode 1556. [easy] Thousand SeparatorFrancesco Manicardi · 2:49 · 143 views
  9. LeetCode Çözümleri - 1556. Thousand SeparatorSoner Gönül · 6:24 · 118 views
  10. 1556. Thousand Separator | LeetCode | Biweekly Contest 33 | StringsCoding Gist · 6:04 · 114 views

The problem

Given an integer n, add a dot (".") as the thousands separator and return it in string format.

Example 1:

Input: n = 987
Output: "987"

Example 2:

Input: n = 1234
Output: "1.234"

Constraints:

  • 0 <= n <= 231 - 1

Approach overview

Problem Overview: You receive a non‑negative integer n. The task is to convert it into a string where digits are grouped by thousands using a dot (.) as the separator. For example, 1234567 becomes 1.234.567. The challenge is purely formatting, but you must place separators exactly every three digits from the right side.

Approach 1: String Processing from Right to Left (O(n) time, O(n) space)

Convert the integer to a string and iterate from the last digit toward the first. Maintain a counter and insert a dot after every three digits while building the result string. Many implementations push characters into a buffer (or StringBuilder) and reverse the result at the end. The key insight: thousand separators are determined relative to the rightmost digit, so right‑to‑left iteration avoids complicated index math. This approach relies only on basic string manipulation and works consistently across languages.

The algorithm scans the digits once, making the time complexity O(n), where n is the number of digits. The output string requires O(n) extra space because separators are inserted during construction. This is the most common implementation in coding interviews because it is straightforward and language‑agnostic.

Approach 2: Using Regular Expression Formatting (O(n) time, O(n) space)

Languages with strong regular expression support can solve this with pattern-based formatting. First convert the number to a string, then apply a regex that inserts a dot before groups of three digits from the right side. Patterns typically use lookahead expressions such as (?=(\d{3})+$) to match positions where a separator should appear.

The regex engine scans the string and inserts separators automatically, producing clean and concise code. Complexity remains O(n) because the regex engine processes each digit once in typical implementations. Space complexity is also O(n) due to the newly constructed formatted string. This method is convenient in languages like Python, Java, and JavaScript where regex replacements are expressive and concise.

Recommended for interviews: The right‑to‑left string processing approach is usually expected. It shows you understand digit grouping logic and basic string processing operations without relying on language‑specific regex tricks. Regex solutions are perfectly valid in production code, but interviewers often prefer the explicit iteration because it demonstrates clear reasoning about indexing and formatting rules.

Approach 1: String Processing from Right to Left

This approach involves converting the number to a string, and then processing it from the rightmost digit to the leftmost. By counting every three digits, we insert a dot (".") as a separator. This helps in formatting the number correctly especially when its length is greater than 3.

def thousand_separator(n):
    s = str(n)
    result = []
    count = 0
    for char in reversed(s):
        result.append(char)
        count += 1
        if count % 3 == 0 and count != len(s):
            result.append('.')
    return ''.join(reversed(result))

print(thousand_separator(1234))
public class Main {
    public static String thousandSeparator(int n) {
        StringBuilder sb = new StringBuilder();
        String str = Integer.toString(n);
        int len = str.length();
        int count = 0;
        for (int i = len - 1; i >= 0; i--) {
            sb.append(str.charAt(i));
            count++;
            if (count % 3 == 0 && i != 0) {
                sb.append('.');
            }
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        int n = 1234;
        System.out.println(thousandSeparator(n));
    }
}
#include <iostream>
#include <string>
#include <algorithm>

std::string thousandSeparator(int n) {
    std::string s = std::to_string(n);
    int len = s.length();
    for (int i = len - 3; i > 0; i -= 3) {
        s.insert(i, ".");
    }
    return s;
}

int main() {
    int n = 1234;
    std::cout << thousandSeparator(n) << std::endl;
    return 0;
}
function thousandSeparator(n) {
    const s = n.toString();
    let count = 0;
    const result = [];
    for (let i = s.length - 1; i >= 0; i--) {
        result.push(s[i]);
        count++;
        if (count % 3 === 0 && i !== 0) {
            result.push('.');
        }
    }
    return result.reverse().join('');
}

console.log(thousandSeparator(1234));
#include <stdio.h>
#include <string.h>

char *thousandSeparator(int n) {
    static char result[20];
    char temp[20];
    int len, i = 0, j = 0;
    sprintf(temp, "%d", n);
    len = strlen(temp);
    while(len--) {
        if (i && i % 3 == 0) {
            result[j++] = '.';
        }
        result[j++] = temp[i++];
    }
    result[j] = '\0';
    strrev(result);
    return result;
}

int main() {
    int n = 1234;
    printf("%s\n", thousandSeparator(n));
    return 0;
}
using System;

public class Solution {
    public static string ThousandSeparator(int n) {
        var s = n.ToString();
        var result = new System.Text.StringBuilder();
        int count = 0;
        for (int i = s.Length - 1; i >= 0; i--) {
            result.Insert(0, s[i]);
            count++;
            if (count % 3 == 0 && i != 0) {
                result.Insert(0, '.');
            }
        }
        return result.ToString();
    }

    public static void Main() {
        int n = 1234;
        Console.WriteLine(ThousandSeparator(n));
    }
}

Python's string handling capabilities make it straightforward to iterate through and manipulate strings. Here, handling is similar to other languages but Python's `reversed` and `join` functions add elegance to the solution.

Complexity

Time Complexity: O(log n).
Space Complexity: O(log n) for storing intermediate lists.

Try this approach in the editor

Approach 2: Using Regular Expression Formatting

This approach makes use of string manipulation libraries available in some languages to directly format numbers with a thousands separator using regular expressions or language-specific numeral formatting techniques.

def thousand_separator(n):
    return f'{n:,}'.replace(',', '.')

print(thousand_separator(1234))
import java.text.DecimalFormat;

public class Main {
    public static String thousandSeparator(int n) {
        DecimalFormat formatter = new DecimalFormat("#,###");
        return formatter.format(n).replace(',', '.');
    }

    public static void main(String[] args) {
        int n = 1234;
        System.out.println(thousandSeparator(n));
    }
}
function thousandSeparator(n) {
    return n.toLocaleString().replace(/,/g, '.');
}

console.log(thousandSeparator(1234));
using System;

public class Solution {
    public static string ThousandSeparator(int n) {
        return String.Format("{0:n0}", n).Replace(',', '.');
    }

    public static void Main() {
        int n = 1234;
        Console.WriteLine(ThousandSeparator(n));
    }
}

Python's formatted string literals or f-strings make numeric string manipulation exceptionally simple. By formatting the integer `n` with the thousands separator using a comma and then replacing it with a dot, the task is efficiently handled.

Complexity

Time Complexity: O(1) on average, due to built-in optimizations.
Space Complexity: O(log n), for the output string.

Try this approach in the editor

Approach 3: Default Approach

func thousandSeparator(n int) string {
	cnt := 0
	ans := []byte{}
	for {
		v := n % 10
		n /= 10
		ans = append(ans, byte('0'+v))
		if n == 0 {
			break
		}
		cnt++
		if cnt == 3 {
			ans = append(ans, '.')
			cnt = 0
		}
	}
	for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
		ans[i], ans[j] = ans[j], ans[i]
	}
	return string(ans)
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
String Processing from Right to Left

Time Complexity: O(log n).
Space Complexity: O(log n) for storing intermediate lists.

Using Regular Expression Formatting

Time Complexity: O(1) on average, due to built-in optimizations.
Space Complexity: O(log n), for the output string.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
String Processing from Right to LeftO(n)O(n)Best general solution; simple logic and works in any language
Regular Expression FormattingO(n)O(n)Concise implementation when strong regex support is available

Frequently asked questions

Is Thousand Separator easy or hard?

Thousand Separator is classified as an Easy problem. The challenge focuses on careful string formatting and handling digit grouping correctly rather than complex algorithms or data structures.

Thousand Separator Python/Java solution

Both Python and Java solutions typically convert the integer to a string and iterate from right to left, inserting a dot after every three digits. Python can also use regex replacement, while Java often uses StringBuilder for efficient string construction.

How to solve Thousand Separator in O(n)?

Convert the integer to a string, iterate from the last character to the first, and insert a dot after every third digit while constructing the result. Using a buffer or StringBuilder keeps the process efficient. After processing all digits, reverse the result if you built it backward.

What is the best approach for Thousand Separator?

The most reliable approach is processing the number as a string from right to left and inserting a dot after every three digits. This runs in O(n) time and O(n) space where n is the number of digits. It avoids complex index calculations and works consistently in languages like C++, Java, Python, and JavaScript.

Is Thousand Separator asked at Google/Amazon/Meta?

This problem is categorized as an easy string formatting task and appears mainly in practice sets or screening rounds. While not among the most frequently reported interview questions at Google or Meta, it reflects common string manipulation patterns that appear in real interview questions.

What data structure is used in Thousand Separator?

The solution primarily uses strings and sometimes a mutable buffer such as StringBuilder, list, or character array to build the formatted result efficiently. No advanced data structures are required.

What is the time complexity of Thousand Separator?

The optimal solution runs in O(n) time because each digit of the number is processed exactly once. Space complexity is O(n) since the algorithm builds a new formatted string containing digits and separator characters.

Comments

Now write it yourselfClose this page and solve Thousand Separator in the editor, without looking.
Practise Thousand Separator