We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Separate the Digits in an Array

Number: 2639

Difficulty: Easy

Paid? No

Companies: Meta


Problem Description

Given an array of positive integers, the goal is to return a new array that consists of the digits of each integer separated in the same order as they appear in the input array.


Key Insights

  • Process each number individually.
  • Convert each number into its individual digits.
  • Maintain the order of digits as they appear in the original numbers.
  • Simple iteration over numbers and their digits ensures the solution is both straightforward and efficient.

Space and Time Complexity

Time Complexity: O(n * d), where n is the number of integers in the array and d is the average number of digits per integer (bounded by 5 given the constraints), so it is effectively O(n).
Space Complexity: O(n * d) for storing the resulting digits, which is effectively O(n).


Solution

The solution uses a simple iterative approach. We loop through each integer in the input array, convert the integer to a string, and then iterate over each character in the string. Each character is then converted back to an integer and added to the result array. This method leverages the ease of string manipulation to separate the digits while preserving their order.


Code Solutions

# Function to separate digits in an array
def separate_digits(nums):
    # List to hold the resulting digits
    result = []
    # Loop through each number in the input list
    for num in nums:
        # Convert the number to a string to iterate over each digit
        for digit_char in str(num):
            # Convert each character back to integer and append to result
            result.append(int(digit_char))
    return result

# Example usage
nums = [13,25,83,77]
print(separate_digits(nums))  # Output: [1, 3, 2, 5, 8, 3, 7, 7]
← Back to All Questions