2553. Separate the Digits in an Array
- Array
- Simulation
TIME
O(d)
SPACE
O(d)
Intuition
The result must preserve both orders:
- the order of numbers in
nums - the left-to-right order of digits inside each number
Converting each number to a string gives the digits directly in the required order.
Approach
- Initialize an empty result array.
- For each number in
nums:- convert it to a string
- iterate over its characters
- convert each character back to an integer and append it
- Return the result.
Complexity
- Time: O(d), where
dis the total number of digits across all numbers - Space: O(d), for the returned answer
Edge Cases
- Single-digit numbers remain unchanged
- Multi-digit numbers are expanded in-place order
- Values like
100000include zero digits in the result
Code
from typing import List
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
"""
2553. Separate the Digits in an Array
Time: O(d)
Space: O(d)
"""
answer = []
for num in nums:
for digit in str(num):
answer.append(int(digit))
return answerimport java.util.ArrayList;
import java.util.List;
/**
* 2553. Separate the Digits in an Array
* Time: O(d)
* Space: O(d)
*/
class Solution {
public int[] separateDigits(int[] nums) {
List<Integer> digits = new ArrayList<>();
for (int num : nums) {
for (char digit : String.valueOf(num).toCharArray()) {
digits.add(digit - '0');
}
}
int[] answer = new int[digits.size()];
for (int i = 0; i < digits.size(); i++) {
answer[i] = digits.get(i);
}
return answer;
}
}