You are given a list of positive integers nums
. You need to return a list containing the digits of each number separated into individual elements in the same order they appear in the original list.
For example, if the input list is [123, 45, 7]
, the output should be [1, 2, 3, 4, 5, 7]
.
nums
.We maintain the order of digits by sequentially processing numbers and their digits.
O(n * k)
, where n
is the number of integers in the list and k
is the average number of digits per integer. This complexity arises because we need to process each digit of each number.O(n * k)
, as we need additional space to store all digits separately.Here is the implementation of the strategy discussed above:
def separate_digits(nums):
result = []
for num in nums:
result.extend([int(digit) for digit in str(num)])
return result
# Test the function with an example case
print(separate_digits([123, 45, 7])) # Expected output: [1, 2, 3, 4, 5, 7]
This function will iterate over each number in the provided list nums
, convert each number to a string to extract individual digits, then convert those digits back to integers, and add them to the result list. Finally, it returns the consolidated list of separated digits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?