Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2442. Count Number of Distinct Integers After Reverse Operations

Explanation

To solve this problem, we can iterate through the given array nums and for each number, reverse its digits and add it to a new set. We can use a set data structure to store the distinct integers in the final array. By iterating through each number in nums and its reversed version, we can count the number of distinct integers in the final array.

  • Algorithm:

    1. Initialize a set distinctIntegers to store distinct integers.
    2. Iterate through each number in nums:
      • Reverse the digits of the number.
      • Add the original number and its reversed version to the set distinctIntegers.
    3. Return the size of the set distinctIntegers.
  • Time Complexity: O(N * M), where N is the number of elements in nums and M is the maximum number of digits in any element.

  • Space Complexity: O(N), where N is the number of elements in nums.

class Solution {
    public int countDistinct(int[] nums) {
        Set<Integer> distinctIntegers = new HashSet<>();
        for (int num : nums) {
            int reverseNum = 0;
            while (num > 0) {
                reverseNum = reverseNum * 10 + num % 10;
                num /= 10;
            }
            distinctIntegers.add(num);
            distinctIntegers.add(reverseNum);
        }
        return distinctIntegers.size();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.