Count Number of Distinct Integers After Reverse Operations — LeetCode 2442 Python Solution

MediumArrayHash TableMathCounting
Problem
#2442
Reading time
2 min

The problem

You are given an array nums consisting of positive integers. You have to take each integer in the array, reverse its digits, and add it to the end of the array.

Example

Input
nums = [1,13,10,12,31]
Output
6
Explanation
After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13].

Python solution

Python
class Solution:
    def countDistinctIntegers(self, nums: List[int]) -> int:
        s = set(nums)
        for x in nums:
            y = int(str(x)[::-1])
            s.add(y)
        return len(s)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2442. Count Number of Distinct Integers After Reverse Operations is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2442. Count Number of Distinct Integers After Reverse Operations?
LeetCode 2442. Count Number of Distinct Integers After Reverse Operations is rated Medium on LeetCode.
What is the time complexity of LeetCode 2442. Count Number of Distinct Integers After Reverse Operations?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2442. Count Number of Distinct Integers After Reverse Operations?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2442. Count Number of Distinct Integers After Reverse Operations cover?
LeetCode 2442. Count Number of Distinct Integers After Reverse Operations is tagged Array, Hash Table, Math and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview