#2553

Separate the Digits in an Array

Easy
ArraySimulationArraySimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution builds the output array directly by iterating through each number and its digits without converting to strings. This reduces overhead and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty list called 'answer'.
  2. 2Step 2: For each number in the input array 'nums', repeatedly extract the last digit by taking modulo 10.
  3. 3Step 3: Append the extracted digit to 'answer' and remove the last digit by performing integer division by 10 until the number becomes 0.
  4. 4Step 4: Since digits are extracted in reverse order, reverse the 'answer' list at the end.
solution.py8 lines
1def separateDigits(nums):
2    answer = []
3    for num in nums:
4        while num > 0:
5            answer.append(num % 10)
6            num //= 10
7    answer.reverse()
8    return answer

Complexity note: The time complexity is O(n) because we process each digit of each number exactly once. The space complexity is O(n) due to the output list storing all the digits.

  • 1Understanding how to manipulate numbers directly can be more efficient than converting to strings.
  • 2Reversing the order of digits is a common pattern when extracting digits from numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.