Question:
How to make an Array of distinct digits from a mixed array?

Summary:

We have an array of N lengths with all positive integers in it. We have to find all distinct digits present in the array and create a new array of numbers using Java


Here we are taking an array of integers (nums) as input and returning an array containing unique digits present across all the numbers. Here's a detailed explanation:


Solution:

//User function Template for Java


class Solution

{

    public int[] common_digits(int[] nums)

    {

        // {111, 222, 333, 4444, 555, 666};

        // {1, 2, 3, 4, 5, 6}

        

        Set<Integer> set = new HashSet<>();

        

        for(int i=0; i<nums.length; i++) {

            

            while(nums[i] > 0) {

                int currEle = nums[i] % 10;

                nums[i] = nums[i] / 10;

                set.add(currEle);

            }

        }

        

        int[] res = new int[set.size()];

        int k = 0;

        for(Integer i: set) {

            res[k++] = i;

        }

        return res;

    }

}


Explanation:

  • The method uses a HashSet (set) to store unique digits encountered across all numbers.

  • It iterates through each number in the array (nums).

  • Inside the loop, it extracts individual digits from the current number by repeatedly dividing by 10 and adding the remainder to the set.

  • The set ensures that only unique digits are stored.

  • Finally, it creates a new array (res) to store the unique digits and populates it by converting the set to an array.


Example:

If the input array nums is [111, 222, 333, 4444, 555, 666], the method would return an array [1, 2, 3, 4, 5, 6], representing the unique digits present across all numbers.


Answered By: >riteshsinharts221

Credit: >Geeksforgeeks


Suggested blogs:

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks

>How to replace a value by another in certain columns of a 3d Numpy array?

>How to fix "segmentation fault" issue when using PyOpenGL on Mac?



Ritu Singh

Ritu Singh

Submit
0 Answers