Count Number of Distinct Integers After Reverse Operations

In this article I’ll solve Count Number of Distinct Integers After Reverse Operations problem in Leetcode. I’ll use Go , C++ , Python to solve this question.

Code Samples (C++ , Go , Python)

// Function for reverse digits in array
func reverse_digits(num int) int {
	reversed := 0
	for num > 0 {
		reversed = reversed*10 + num%10
		num /= 10
	}
	return reversed
}

func countDistinctIntegers(nums []int) int {
    // hashmap for save num in nums and reversed versions of these numbers
	distinct := make(map[int]bool)
        
    // If reversed number is equal a number in nums it won't affect distinct hashmap
	for _, num := range nums {
		distinct[num] = true
		distinct[reverse_digits(num)] = true
	}
        
    // Return hashmap length
	return len(distinct)
}
class Solution:
    def reverse_digits(self, num: int) -> int:
        # Function to reverse digits in a number
        reversed_num = 0
        while num > 0:
            reversed_num = reversed_num * 10 + num % 10
            num //= 10
        return reversed_num

    def countDistinctIntegers(self, nums: List[int]) -> int:
        # Function to count distinct integers and their reversed versions in a list
        distinct = set()  # Create a set to store distinct numbers
        for num in nums:
            distinct.add(num)  # Add the original number to the set
            distinct.add(self.reverse_digits(num))  # Add the reversed version to the set
        return len(distinct)  # Return the length of the set, which represents the count of distinct integers
class Solution {
public:
    int reverseDigits(int num) {
        int reversedNum = 0;
        while (num > 0) {
            reversedNum = reversedNum * 10 + num % 10;
            num /= 10;
        }
        return reversedNum;
    }

    int countDistinctIntegers(vector<int>& nums) {
        unordered_set<int> distinct; // Create an unordered_set to store distinct numbers
        for (int num : nums) {
            distinct.insert(num); // Add the original number to the set
            distinct.insert(reverseDigits(num)); // Add the reversed version to the set
        }
        return distinct.size(); // Return the size of the set, which represents the count of distinct integers
    }
};

Algorithm Sample for This Problem

  1. Create an empty hashmap to store unique integers.
  2. Iterate through each number in the input slice.
  3. For each number:
    • Reverse its digits.
    • Set both the original number and its reversed version as keys in the hashmap with a boolean value set to true.
  4. Return the count of unique keys in the hashmap.

Leave a Reply

Your email address will not be published. Required fields are marked *