Separate the Digits in an Array
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an array of positive integers nums, return an arrayanswer that consists of the digits of each integer innums _after separating them inthe same order they appear in _nums.
To separate the digits of an integer is to get all the digits it has in the same order.
- For example, for the integer
10921, the separation of its digits is[1,0,9,2,1].
Examples
Example 1
Input: nums = [13,25,83,77]
Output: [1,3,2,5,8,3,7,7]
Explanation:
- The separation of 13 is [1,3].
- The separation of 25 is [2,5].
- The separation of 83 is [8,3].
- The separation of 77 is [7,7].
answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order.
Example 2
Input: nums = [7,1,3,9]
Output: [7,1,3,9]
Explanation: The separation of each integer in nums is itself.
answer = [7,1,3,9].
Constraints
1 <= nums.length <= 10001 <= nums[i] <= 10^5
Solution
Method 1 – String Conversion and Flattening
Intuition
We can convert each number to a string, split it into digits, and collect all digits in order. This is direct and efficient for the given constraints.
Approach
- For each number in nums, convert it to a string.
- For each character in the string, convert it back to an integer and add to the result list.
- Return the result list.
Code
C++
class Solution {
public:
vector<int> separateDigits(vector<int>& nums) {
vector<int> ans;
for (int x : nums) {
string s = to_string(x);
for (char c : s) ans.push_back(c - '0');
}
return ans;
}
};
Go
func separateDigits(nums []int) []int {
res := []int{}
for _, x := range nums {
for _, c := range fmt.Sprint(x) {
res = append(res, int(c-'0'))
}
}
return res
}
Java
import java.util.*;
class Solution {
public List<Integer> separateDigits(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int x : nums) {
for (char c : String.valueOf(x).toCharArray()) ans.add(c - '0');
}
return ans;
}
}
Kotlin
class Solution {
fun separateDigits(nums: IntArray): List<Int> {
val ans = mutableListOf<Int>()
for (x in nums) {
for (c in x.toString()) ans.add(c - '0')
}
return ans
}
}
Python
class Solution:
def separateDigits(self, nums: list[int]) -> list[int]:
ans = []
for x in nums:
ans.extend(int(c) for c in str(x))
return ans
Rust
impl Solution {
pub fn separate_digits(nums: Vec<i32>) -> Vec<i32> {
let mut ans = vec![];
for x in nums {
for c in x.to_string().chars() {
ans.push(c.to_digit(10).unwrap() as i32);
}
}
ans
}
}
TypeScript
class Solution {
separateDigits(nums: number[]): number[] {
const ans: number[] = [];
for (const x of nums) {
for (const c of x.toString()) ans.push(Number(c));
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n * d), where n = length of nums, d = max number of digits per number (≤ 5). Each digit is processed once. - 🧺 Space complexity:
O(n * d), for the output list.