LeetCode 2442: Count Number of Distinct Integers After Reverse Operations Solution

Master LeetCode problem 2442 (Count Number of Distinct Integers After Reverse Operations), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2442. Count Number of Distinct Integers After Reverse Operations

Problem Explanation

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.

Solution Code

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();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2442 (Count Number of Distinct Integers After Reverse Operations)?

This page provides optimized solutions for LeetCode problem 2442 (Count Number of Distinct Integers After Reverse Operations) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2442 (Count Number of Distinct Integers After Reverse Operations)?

The time complexity for LeetCode 2442 (Count Number of Distinct Integers After Reverse Operations) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2442 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2442 in Java, C++, or Python.

Back to LeetCode Solutions