Separate the Digits in an Array — Easy Problem & Solution

Replace each number in nums by its digits, keeping both the order of the numbers and the order of the digits inside each one. Return the resulting array.

  • Difficulty: Easy
  • Topics: Arrays, Simulation
  • Asked at: Amazon, Google, Capgemini
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Replace each number in nums by its digits, keeping both the order of the numbers and the order of the digits inside each one.

Return the resulting array.

Example 1

Input: nums = [13,25,83,77]
Output: [1,3,2,5,8,3,7,7]

Example 2

Input: nums = [7,1,3,9]
Output: [7,1,3,9]
Explanation: Single-digit numbers are unchanged.

Example 3

Input: nums = [100,5]
Output: [1,0,0,5]

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^5

How to solve Separate the Digits in an Array

For each number, peel its digits with repeated % 10 and / 10, then append them in reverse so the original order is preserved.

Approach

  1. For each number, push v % 10 and divide by 10 until it reaches 0.
  2. Append that buffer to the output back to front.

Why it works

The % 10 loop is the natural way to read digits, but it delivers the least significant one first — hence the reversal. Every value is at least 1, so the loop always produces at least one digit and no number contributes nothing.

Complexity

  • Time — O(n · digits)
  • Space — O(n · digits) for the output

Pitfalls

  • Appending the peeled digits directly reverses each number.
  • A value of 0 would produce no digits, but the constraints keep every value at least 1.
  • Converting to strings works but does more allocation than the arithmetic.

Reference solution

Python

from typing import List

def separateDigits(nums: List[int]) -> List[int]:
    out = []
    for v in nums:
        digits = []
        while v > 0:
            digits.append(v % 10)
            v //= 10
        out.extend(reversed(digits))
    return out

JavaScript

var separateDigits = function(nums) {
    var out = [];
    for (var i = 0; i < nums.length; i++) {
        var digits = [];
        var v = nums[i];
        while (v > 0) {
            digits.push(v % 10);
            v = Math.floor(v / 10);
        }
        for (var j = digits.length - 1; j >= 0; j--) out.push(digits[j]);
    }
    return out;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue