# Separate the Digits in an Array
**Difficulty:** EASY
[External](https://leetcode.com/problems/separate-the-digits-in-an-array)
Canonical: https://scaleengineer.com/dsa/problems/separate-the-digits-in-an-array
**Data structures:** Array
---
## 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 <= 1000`
* `1 <= nums[i] <= 105`

# Approaches
## Mathematical Extraction with Reversal
This approach uses mathematical operations (modulo and division) to extract digits from each number. Since this process extracts digits from right to left (least significant to most significant), a temporary list is used to store these digits, which is then reversed to get the correct order before being added to the final result.
**Time:** O(N * K), where `N` is the number of elements in `nums` and `K` is the maximum number of digits in an element. For each number, we perform O(K) operations to extract digits and O(K) to reverse the temporary list. · **Space:** O(N * K), where `N` is the number of elements in `nums` and `K` is the maximum number of digits in an element. This is for the final result list. Additionally, O(K) space is used for the temporary list for each number.
**Pros:** Avoids string conversions, which can be beneficial in performance-critical environments that penalize type casting.; The logic for extracting digits (modulo and division) is a fundamental and efficient arithmetic technique.
**Cons:** Requires creating a new temporary list for each number in the input array.; The reversal step for each number's digits adds computational overhead.; The overall logic is more complex compared to more direct approaches.
### Explanation
The core idea is to process each number individually. For a given number, we can easily extract its digits in reverse order by repeatedly taking the number modulo 10 (to get the last digit) and then dividing by 10 (to remove the last digit). We store these reversed digits in a temporary list. Once all digits of a number are extracted, we reverse this temporary list to restore the original order and then append these correctly ordered digits to our main result list. This process is repeated for every number in the input array.

```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Solution {
    public int[] separateDigits(int[] nums) {
        List<Integer> answerList = new ArrayList<>();
        for (int num : nums) {
            // Per the constraints, nums[i] >= 1, so no need to handle num == 0.
            List<Integer> tempDigits = new ArrayList<>();
            int currentNum = num;
            while (currentNum > 0) {
                tempDigits.add(currentNum % 10);
                currentNum /= 10;
            }
            Collections.reverse(tempDigits);
            answerList.addAll(tempDigits);
        }
        
        int[] result = new int[answerList.size()];
        for (int i = 0; i < answerList.size(); i++) {
            result[i] = answerList.get(i);
        }
        return result;
    }
}
```
### Algorithm
- Initialize an empty list of integers, `answerList`.
- Iterate through each integer `num` in the input array `nums`.
- Create a temporary list, `tempDigits`.
- While `num` is greater than 0:
  - Extract the last digit using `num % 10`.
  - Add the digit to `tempDigits`.
  - Update the number by integer division: `num = num / 10`.
- Reverse the `tempDigits` list to get the digits in the correct order.
- Add all digits from the reversed `tempDigits` list to `answerList`.
- After processing all numbers, convert `answerList` into an array and return it.

## String Conversion
This approach converts each number into a string. Then, it iterates through the characters of the string, converts each character back to its integer value, and adds it to the result list. This is often the most straightforward and readable method due to its simplicity.
**Time:** O(N * K), where `N` is the number of elements in `nums` and `K` is the maximum number of digits in an element. Converting a number to a string takes O(K) time. We then iterate K times for each of the N numbers. · **Space:** O(N * K) to store the resulting list of digits, where `N` is the length of `nums` and `K` is the maximum number of digits. A temporary string of size O(K) is also created for each number.
**Pros:** Very simple to understand and implement.; The code is concise and highly readable.; Directly gets digits in the correct order without needing reversal.
**Cons:** Involves type conversions (int to string, char to int) which can have a slight performance overhead compared to pure mathematical operations.; Creates intermediate string objects, which can lead to increased memory allocations.
### Explanation
The logic leverages built-in string conversion functionalities. For each number in the input array, we first convert it to a `String`. A string is essentially a sequence of characters, so we can iterate through it from left to right. Each character in the string corresponds to a digit. We convert each character back to its numeric value and append it to a dynamic list that accumulates our final answer. This method preserves the order of digits naturally.

```java
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] separateDigits(int[] nums) {
        List<Integer> answerList = new ArrayList<>();
        for (int num : nums) {
            String s = String.valueOf(num);
            for (char c : s.toCharArray()) {
                answerList.add(c - '0'); // Fast conversion from char to int
            }
        }
        
        // Convert List<Integer> to int[]
        int[] result = new int[answerList.size()];
        for (int i = 0; i < answerList.size(); i++) {
            result[i] = answerList.get(i);
        }
        return result;
    }
}
```
### Algorithm
- Initialize an empty list of integers, `answerList`.
- Iterate through each integer `num` in the input array `nums`.
- Convert `num` to its string representation, `s`.
- Iterate through each character `c` in the string `s`.
- Convert the character `c` to an integer digit and add it to `answerList`.
- After processing all numbers, convert `answerList` into an array and return it.

## Mathematical Extraction with Divisor
This efficient approach avoids any reversals or temporary data structures by calculating the digits from left to right. For each number, it first finds the largest power of 10 (the divisor) that is smaller than the number. Then, it repeatedly divides the number by the divisor to get the most significant digit and appends it to the result. The number and the divisor are updated in each step until all digits are extracted.
**Time:** O(N * K), where `N` is the number of elements and `K` is the max number of digits. For each of `N` numbers, finding the initial divisor takes O(K) time, and extracting the digits also takes O(K) time. · **Space:** O(N * K) for the result list, where `N` is the length of `nums` and `K` is the maximum number of digits. The space used within the loop is constant.
**Pros:** Highly efficient, using only mathematical operations.; Processes everything in a single forward pass without temporary collections for each number.; Avoids the overhead of string conversions, reversals, or recursion.
**Cons:** The logic to find and manage the divisor is slightly more complex to write and understand compared to the string conversion method.
### Explanation
This method is a pure mathematical solution that extracts digits in their correct order. For any number, say `10921`, the most significant digit (`1`) can be found by dividing by the correct power of ten (`10000`). To implement this, we first find this starting divisor. Then, we loop, extracting the leftmost digit, adding it to our result, and updating both the number (by taking the remainder) and the divisor (by dividing by 10) to process the next digit. This continues until the divisor becomes 0. This is done for all numbers in the input array, appending all resulting digits to a single list.

```java
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] separateDigits(int[] nums) {
        List<Integer> answerList = new ArrayList<>();
        for (int num : nums) {
            // Find the largest power of 10 less than or equal to num
            int divisor = 1;
            while (num / divisor >= 10) {
                divisor *= 10;
            }
            
            // Extract digits from left to right
            int currentNum = num;
            while (divisor > 0) {
                int digit = currentNum / divisor;
                answerList.add(digit);
                currentNum %= divisor;
                divisor /= 10;
            }
        }
        
        int[] result = new int[answerList.size()];
        for (int i = 0; i < answerList.size(); i++) {
            result[i] = answerList.get(i);
        }
        return result;
    }
}
```
### Algorithm
- Initialize an empty `ArrayList` of integers, `answerList`.
- Iterate through each integer `num` in the input array `nums`.
- For each `num`, find the largest power of 10, `divisor`, that is less than or equal to `num`.
- While the `divisor` is greater than 0:
  - Get the leftmost digit: `digit = num / divisor`.
  - Add `digit` to `answerList`.
  - Remove the leftmost digit from `num`: `num = num % divisor`.
  - Reduce the `divisor` for the next digit: `divisor = divisor / 10`.
- After processing all numbers, convert `answerList` to an array.

# Solutions
### Java

```java
class Solution {
public
  int[] separateDigits(int[] nums) {
    List<Integer> res = new ArrayList<>();
    for (int x : nums) {
      List<Integer> t = new ArrayList<>();
      for (; x > 0; x /= 10) {
        t.add(x % 10);
      }
      Collections.reverse(t);
      res.addAll(t);
    }
    int[] ans = new int[res.size()];
    for (int i = 0; i < ans.length; ++i) {
      ans[i] = res.get(i);
    }
    return ans;
  }
}

```

### CPP

```cpp
class Solution {
public:
  vector<int> separateDigits(vector<int> &nums) {
    vector<int> ans;
    for (int x : nums) {
      vector<int> t;
      for (; x; x /= 10) {
        t.push_back(x % 10);
      }
      while (t.size()) {
        ans.push_back(t.back());
        t.pop_back();
      }
    }
    return ans;
  }
};

```

### Python

```python
class Solution:
    def separateDigits(self, nums: List[int]) -> List[int]: ans = [] for x in nums: t = [] while x: t . append(x % 10) x //= 10 ans . extend(t[:: - 1]) return ans

```
