2553. Separate the Digits in an Array

Post by ailswan Aug. 24, 2024

2553. Separate the Digits in an Array

Problem Statement

link: LeetCode.cn LeetCode Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.

To separate the digits of an integer is to get all the digits it has in the same order.

For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].

Example:

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

Input: nums = [7,1,3,9] Output: [7,1,3,9]

Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 105

Solution Approach

Iterate through each number, extract its digits in reverse order, and then reverse the extracted digits to maintain their original order before appending to the result list.

Algorithm

  1. Digit Extraction: For each number in the array, extract its digits by repeatedly taking the last digit and removing it from the number.
  2. Reverse Digits: Store the digits in reverse order and then reverse them back to their original order to maintain the correct sequence.
  3. Concatenate Results: Append the correctly ordered digits to the result list in the same sequence as the numbers appear in the input array.

Implement

    class Solution:
    def separateDigits(self, nums: List[int]) -> List[int]:
        answer = []
        index = 0
        for num in nums:
            start = index
            temp = num
            while temp != 0:
                answer.append(temp % 10)
                index += 1
                temp //= 10
            self.reverse(answer, start, index - 1)
        return answer
        
    def reverse(self, answer: List[int], start: int, end: int) -> None:
        i, j = start, end
        while i < j:
            answer[i], answer[j] = answer[j], answer[i]
            i += 1
            j -= 1