Separate the Digits in an Array solution and explanation
9 more videos on this problem
Separate the Digits in an Array || LeetCode Biweekly Contest 97 || Explanation with SolutionLearn to Code · 4:32 · 1K views
Leetcode 2553 Separate the Digits in an Array (Java) - Leetcode Biweekly Contest 97 - Beats 100%TheAnalyticGuy · 3:04 · 856 views
2553. Separate the Digits in an Array | Leetcode BiWeekly Contest 97Tech Courses · 3:27 · 586 views
Separate the Digits in an Array | Leetcode 2553 | Array | Simulation | Easiest ExplanationPragya Gupta · 8:53 · 521 views
2553. Separate the Digits in an Array | Leetcode Daily - PythonLeetcode Daily · 6:19 · 497 views
2553. Separate the Digits in an Array (Leetcode Easy)Programming Live with Larry · 2:51 · 332 views
Separate the Digits in an Array | LeetCode 2553Streak To Scale · 2:03 · 264 views
Leetcode 2553. Separate the Digits in an ArrayElite Code · 17:52 · 200 views
2553. Separate the Digits in an Array | Leetcode Daily ChallengeLogic soch · 2:51 · 180 views
Separate the Digits in an Array | LeetCode 2553 - Pythonimpoldev · 3:44 · 143 views
The problem
Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the 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].
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] <= 105
Approach overview
Problem Overview: You receive an array of positive integers. For every number, split it into its individual digits and append those digits to a result array while preserving the original order. For example, [13, 25] becomes [1, 3, 2, 5]. The challenge is simply extracting digits efficiently while keeping the sequence correct.
This problem falls under basic Array traversal and Simulation. You process each number one by one and simulate digit extraction.
Approach 1: String Conversion Method (O(n·k) time, O(n·k) space)
The simplest implementation converts each number into a string, then iterates over its characters. Each character represents a digit, so convert it back to an integer and append it to the result list. If n is the number of integers and k is the average number of digits per integer, the algorithm performs roughly n × k operations.
This approach is popular because it is extremely readable and avoids manual digit manipulation. Most high-level languages provide fast string iteration, so the performance is usually more than sufficient for interview constraints. The tradeoff is extra temporary memory used by the string representation, which makes the space complexity O(n·k) including the output.
Approach 2: Mathematical Division Method (O(n·k) time, O(n·k) space)
This method extracts digits using arithmetic instead of string operations. For each number, repeatedly apply num % 10 to obtain the last digit and num / 10 to remove it. Because this produces digits in reverse order, store them temporarily (for example in a stack or small list) and then append them back to the result in reverse.
The algorithm still processes every digit exactly once, so the time complexity remains O(n·k). Space complexity is also O(n·k) due to the output plus a small temporary buffer per number. This approach is useful when you want tighter control over numeric operations or when avoiding string conversions is preferred.
Recommended for interviews: Both approaches are acceptable because the complexity is identical. The string conversion solution demonstrates clean thinking and quick implementation, which interviewers appreciate for an easy problem. The mathematical division method shows deeper understanding of digit manipulation and is sometimes preferred in lower-level environments where avoiding string conversion matters.
Approach 1: String Conversion Method
This approach involves converting each integer in the array to a string, then iterating over each character in the string to convert it back to an integer. This allows us to access each digit in its original order effortlessly.
def separate_digits(nums):
result = []
for num in nums:
result.extend(int(digit) for digit in str(num))
return resultimport java.util.ArrayList;
import java.util.List;
public class SeparateDigits {
public static List<Integer> separateDigits(int[] nums) {
List<Integer> result = new ArrayList<>();
for (int num : nums) {
for (char c : String.valueOf(num).toCharArray()) {
result.add(c - '0');
}
}
return result;
}
}#include <vector>
#include <string>
std::vector<int> separateDigits(std::vector<int>& nums) {
std::vector<int> result;
for (int num : nums) {
for (char c : std::to_string(num)) {
result.push_back(c - '0');
}
}
return result;
}function separateDigits(nums) {
const result = [];
for (const num of nums) {
for (const char of String(num)) {
result.push(Number(char));
}
}
return result;
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* separateDigits(int* nums, int numsSize, int* returnSize) {
int* result = (int*)malloc(numsSize * 5 * sizeof(int));
int index = 0;
for (int i = 0; i < numsSize; i++) {
char numStr[6];
snprintf(numStr, sizeof(numStr), "%d", nums[i]);
for (int j = 0; j < strlen(numStr); j++) {
result[index++] = numStr[j] - '0'; // Convert char to int
}
}
*returnSize = index;
return result;
}using System;
using System.Collections.Generic;
public class SeparateDigits {
public static List<int> SeparateDigits(int[] nums) {
List<int> result = new List<int>();
foreach (int num in nums) {
foreach (char c in num.ToString()) {
result.Add(c - '0');
}
}
return result;
}
}This Python solution converts each number into a string and iterates over each digit, directly extending the result list with integer-converted digits. As Python lists are dynamic, this is an efficient way to handle increasing result length.
Time Complexity: O(n * k) because of iterating digits of each number.
Space Complexity: O(n * k) for the resulting list storage.
Approach 2: Mathematical Division Method
This approach involves using mathematical operations to extract digits from each number without converting it to a string. The core idea retains the remainder of number by using modulo operation followed by integer division to remove processed digits from the right.
def separate_digits(nums):
result = []
for num in nums:
digits = []
while num:
digits.append(num % 10)
num //= 10
result.extend(reversed(digits))
return resultimport java.util.ArrayList;
import java.util.List;
public class SeparateDigits {
public static List<Integer> separateDigits(int[] nums) {
List<Integer> result = new ArrayList<>();
for (int num : nums) {
List<Integer> digits = new ArrayList<>();
while (num > 0) {
digits.add(num % 10);
num /= 10;
}
for (int i = digits.size() - 1; i >= 0; i--) {
result.add(digits.get(i));
}
}
return result;
}
}#include <vector>
std::vector<int> separateDigits(const std::vector<int>& nums) {
std::vector<int> result;
for (int num : nums) {
std::vector<int> digits;
while (num > 0) {
digits.push_back(num % 10);
num /= 10;
}
for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
result.push_back(*it);
}
}
return result;
}function separateDigits(nums) {
const result = [];
for (const num of nums) {
const digits = [];
let currentNum = num;
while (currentNum > 0) {
digits.push(currentNum % 10);
currentNum = Math.floor(currentNum / 10);
}
digits.reverse();
result.push(...digits);
}
return result;
}#include <stdio.h>
#include <stdlib.h>
int* separateDigits(int* nums, int numsSize, int* returnSize) {
int* result = (int*)malloc(numsSize * 5 * sizeof(int));
int index = 0;
for (int i = 0; i < numsSize; i++) {
int num = nums[i], reversed = 0;
while (num > 0) {
reversed = reversed * 10 + (num % 10);
num /= 10;
}
// needing to reverse it again because digits are extracted in reverse order
int originalReverse = 0;
while (reversed > 0) {
originalReverse = originalReverse * 10 + (reversed % 10);
reversed /= 10;
}
while (originalReverse > 0) {
result[index++] = originalReverse % 10;
originalReverse /= 10;
}
}
*returnSize = index;
return result;
}using System;
using System.Collections.Generic;
public class SeparateDigits {
public static List<int> SeparateDigits(int[] nums) {
List<int> result = new List<int>();
foreach (int num in nums) {
List<int> digits = new List<int>();
int tempNum = num;
while (tempNum > 0) {
digits.Add(tempNum % 10);
tempNum /= 10;
}
digits.Reverse();
result.AddRange(digits);
}
return result;
}
}In Python, the modulo and floor division operations efficiently handle current digit extraction and sequence tracking handled by appending in reverse order. This approach offers clarity via direct iterative list modification.
Time Complexity: O(n * k) due to reversing auxiliary lists.
Space Complexity: O(n * k) on account of interim storage and reversal overheads.
Approach 3: Simulation
Split each number in the array into digits, then put the split numbers into the answer array in order.
The time complexity is O(n times log_{10} M), and the space complexity is O(n times log_{10} M). Where n is the length of the array nums, and M is the maximum value in the array nums.
function separateDigits(nums: number[]): number[] {
const ans: number[] = [];
for (let num of nums) {
const t: number[] = [];
while (num) {
t.push(num % 10);
num = Math.floor(num / 10);
}
ans.push(...t.reverse());
}
return ans;
}func separateDigits(nums []int) (ans []int) {
for _, x := range nums {
t := []int{}
for ; x > 0; x /= 10 {
t = append(t, x%10)
}
for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 {
t[i], t[j] = t[j], t[i]
}
ans = append(ans, t...)
}
return
}impl Solution {
pub fn separate_digits(nums: Vec<i32>) -> Vec<i32> {
let mut ans = Vec::new();
for &num in nums.iter() {
let mut num = num;
let mut t = Vec::new();
while num != 0 {
t.push(num % 10);
num /= 10;
}
t.into_iter().rev().for_each(|v| ans.push(v));
}
ans
}
}Approach 4: Default Approach
impl Solution {
pub fn separate_digits(nums: Vec<i32>) -> Vec<i32> {
let mut ans = vec![];
for n in nums {
let mut t = vec![];
let mut x = n;
while x != 0 {
t.push(x % 10);
x /= 10;
}
for i in (0..t.len()).rev() {
ans.push(t[i]);
}
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| String Conversion Method | Time Complexity: O(n * k) because of iterating digits of each number. |
| Mathematical Division Method | Time Complexity: O(n * k) due to reversing auxiliary lists. |
| Simulation | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Conversion Method | O(n·k) | O(n·k) | Best for readability and fast implementation in interviews |
| Mathematical Division Method | O(n·k) | O(n·k) | When avoiding string conversion or demonstrating numeric digit extraction |
Frequently asked questions
Is Separate the Digits in an Array easy or hard?
Separate the Digits in an Array is classified as an Easy problem. It mainly tests basic array traversal and simple digit extraction logic rather than complex data structures or algorithms.
Separate the Digits in an Array Python/Java solution
In Python or Java, the most common solution converts each number to a string and iterates through the characters to append digits to a result list. The same logic works in C++, JavaScript, and C#. The complexity remains O(n·k) time and O(n·k) space.
How to solve Separate the Digits in an Array in O(n)?
Strictly speaking, the complexity depends on the number of digits processed. The practical optimal solution is O(n·k), which behaves close to linear relative to total digits. Iterate through the array and extract digits using either string iteration or repeated modulo and division operations.
What is the best approach for Separate the Digits in an Array?
The string conversion approach is usually the best for interviews because it is short and easy to reason about. Convert each integer to a string, iterate through its characters, and append each digit to the result array. The algorithm runs in O(n·k) time where k is the number of digits per number.
Is Separate the Digits in an Array asked at Google/Amazon/Meta?
This problem represents an easy-level array simulation pattern commonly used in screening rounds and coding practice platforms. Variations involving digit manipulation or array transformations can appear in interviews at companies like Amazon or Google as warm-up questions.
What data structure is used in Separate the Digits in an Array?
The primary data structure is an array or dynamic list used to store the resulting digits. Some implementations also use a temporary stack or list when extracting digits mathematically to restore the correct order.
What is the time complexity of Separate the Digits in an Array?
The time complexity is O(n·k), where n is the number of elements in the input array and k is the number of digits in each number. Every digit is processed exactly once when extracting digits from each integer.
