algoadvance

Leetcode 2553. Separate the Digits in an Array

Problem Statement

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.

Example:

Input: nums = [13, 25, 83, 77]
Output: [1, 3, 2, 5, 8, 3, 7, 7]
Explanation: 
- The digits of 13 are [1, 3]
- The digits of 25 are [2, 5]
- The digits of 83 are [8, 3]
- The digits of 77 are [7, 7]
Hence, the answer is [1, 3, 2, 5, 8, 3, 7, 7]

Clarifying Questions

  1. Are all numbers in the input array nums positive integers?
    • Yes, based on the problem, all integers in nums are positive.
  2. Do we need to maintain the order of digits as they appear in each number?
    • Yes, we should maintain the order of digits as they appear in each individual number in the array.
  3. Can the array nums be empty?
    • Based on the problem constraints, it is possible but unlikely. If it’s empty, we would return an empty array as well.

Strategy

  1. Initialize an empty list answer that will store the separated digits.
  2. Iterate through each number in the given array nums.
  3. For each number, convert it to a string to easily access each digit.
  4. Convert each character back to an integer and append it to the answer list.
  5. Return the answer list.

Code

Here’s how we can achieve this in Java:

import java.util.ArrayList;
import java.util.List;

public class SeparateDigits {
    public static List<Integer> separateDigits(int[] nums) {
        List<Integer> answer = new ArrayList<>();
        for (int num : nums) {
            String numStr = String.valueOf(num);
            for (char digitChar : numStr.toCharArray()) {
                answer.add(Character.getNumericValue(digitChar));
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        int[] nums = {13, 25, 83, 77};
        System.out.println(separateDigits(nums)); // Output: [1, 3, 2, 5, 8, 3, 7, 7]
    }
}

Time Complexity

This solution efficiently separates the digits while maintaining the order and handles all constraints provided by the problem.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI