#1556
Thousand Separator
EasyStringString ManipulationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution builds the result string in a single pass without reversing the string multiple times. It counts characters and appends dots directly.
⚙️
Algorithm
5 steps- 1Step 1: Convert the integer n to a string.
- 2Step 2: Initialize an empty result string and a counter for digits.
- 3Step 3: Iterate through the string from the end to the beginning.
- 4Step 4: Append each character to the result and increment the counter.
- 5Step 5: If the counter reaches 3, append a dot and reset the counter.
solution.py10 lines
1def thousand_separator(n):
2 s = str(n)
3 result = ''
4 count = 0
5 for i in range(len(s) - 1, -1, -1):
6 if count > 0 and count % 3 == 0:
7 result += '.'
8 result += s[i]
9 count += 1
10 return result[::-1]ℹ
Complexity note: The time complexity is O(n) since we only traverse the string once, and the space complexity is O(n) for the result string.
- 1Understanding string manipulation is crucial for this problem.
- 2Counting characters and managing positions can optimize the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.