Similar Problems

Similar Problems not available

Separate The Digits In An Array - Leetcode Solution

Companies:

LeetCode:  Separate The Digits In An Array Leetcode Solution

Difficulty: Easy

Topics: array simulation  

Problem Statement:

Given an integer array nums, return an array of the same length containing the digits from all the integers in nums.

You must return the answer in descending order.

Example:

Input: nums = [12,345,6789] Output: [9,8,7,6,5,4,3,2,1,0]

Solution:

The problem statement asks us to extract all digits from all integers in nums, sort them in descending order and return the output in an array.

We can start by declaring an empty list named digits.

Create a for loop to iterate through the elements in the nums list.

Inside the loop, first convert the integer to string using str() function. Now, we have a string of numbers, for example, "123".

Create another for loop to iterate through the characters in the string.

Inside this loop, each character can be appended to the digits list.

Finally, the digits list can be sorted in descending order using sort() method of a list object, and returned to get the desired output.

Code:

class Solution: def separateDigits(self, nums: List[int]) -> List[int]: digits = [] for num in nums: numStr = str(num) for char in numStr: digits.append(int(char)) digits.sort(reverse=True) return digits

Time complexity: O(n log n) in worst case, because of sorting time. Space complexity: O(n), because of the digits list.

Separate The Digits In An Array Solution Code

1