Count Distinct Integers After Reverse Operations

Add the digit reversal of every number to an array, then count how many different values it holds.

You are given an array nums of positive integers. For each number in it, write its digits in reverse order and add the new number to the end of the array. Only the original numbers are reversed, not the ones just added. Each number is at most 1,000,000. Return how many different values the final array contains.

Example 1
Input: nums = [1, 13, 10, 12, 31]
Output: 6
Explanation: the reversed numbers are 1, 31, 1, 21 and 13 (10 reversed is 01, which is 1). The different values are 1, 10, 12, 13, 21 and 31.
Example 2
Input: nums = [2, 2, 2]
Output: 1
Explanation: every number reverses to 2, so the final array holds six 2s.
Solution

The Idea

Reversing a number means reading its digits from right to left: 13 becomes 31, and 12 becomes 21. A number like 10 reads as 01, and a zero in front of a number does not count, so 10 reversed is just 1.

Take Example 1. The array starts as 1, 13, 10, 12, 31, and reversing each number adds 1, 31, 1, 21, 13 to the end. That makes ten numbers, but many of them repeat. Look at the picture below.

The original numbers 1, 13, 10, 12, 31 each point down to their reversed numbers 1, 31, 1, 21, 13. 10 reversed is 01, which is 1. Only 21 is a new value, so the distinct values are 1, 10, 12, 13, 21 and 31: 6 values.

The top row holds the original numbers, and each arrow leads to that number reversed. The orange arrow starts at 10, whose reversal 01 is 1. Most reversed numbers, drawn dashed and marked "already there", are values the array already holds: 1 is the first number, and 31 and 13 are both in the top row. Only 21, in green, is a new value. The bottom row lists every different value once, six in all.

So the question is not really about building the final, longer array. It asks how many different values we meet while looking at each number and its reversal. The different values of a list, each counted once however often it repeats, are called its distinct values, and their number is the answer.

Solution Approach

Turning that idea into code means settling two things: how to count each value only once, and how to reverse a number.

Counting each value once

Do we need to build the longer array at all? The simple way is to build it and then, for each value, check whether it appeared earlier. For 10,000 numbers the longer array has 20,000 values, and checking each one against all the values before it takes about 200 million comparisons.

A HashSet does better. It is a Java collection that keeps each value at most once: adding a value it already holds changes nothing. Checking and adding take about the same short time however many values it holds. So we add every original number and every reversed number, and the size of the set at the end is the answer. The longer array is never built.

Reversing a number

How do we reverse the digits? Turning the number into a String and back works, but plain arithmetic is simpler and creates no extra objects. Take the digits off the end of the number x one at a time, and put each on the end of a new number r, which starts at 0. Each round has three small steps:

  • x % 10 is the last digit of x, the remainder after dividing by 10.
  • r * 10 + digit shifts the digits of r one place left and puts the digit at the end.
  • x / 10 drops the last digit from x, because integer division throws away the remainder.

For 13, the first round gives r = 3 and x = 1, and the second gives r = 31 and x = 0, so no digits are left to move. The zero in front of a reversed number disappears on its own: for 10 the first round gives r = 0 * 10 + 0 = 0, and the second gives r = 0 * 10 + 1 = 1.

Java Solution

The method countDistinctIntegers works in these steps:

  1. First, create an empty HashSet called seen to hold the distinct values.
  2. Loop over the array, taking each number x in turn, and add x itself to seen.
  3. Also add reverse(x). The helper method reverse starts r at 0 and, while x is above 0, moves the last digit of x to the end of r, then returns r.
  4. When the loop is done, return seen.size(), the number of distinct values.

The main method runs both examples, then [10], [100, 1], the palindrome [121] (a number that reads the same both ways), and [1000000], and finally prints a few reversals on their own.

Java
import java.util.HashSet;
import java.util.Set;

public class CountDistinctIntegersAfterReverseOperations {

    public static int countDistinctIntegers(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        for (int x : nums) {
            seen.add(x);
            seen.add(reverse(x));
        }
        return seen.size();
    }

    private static int reverse(int x) {
        int r = 0;
        while (x > 0) {
            r = r * 10 + x % 10;              // move the last digit of x to the end of r
            x /= 10;
        }
        return r;
    }

    public static void main(String[] args) {
        System.out.println(countDistinctIntegers(new int[] {1, 13, 10, 12, 31}));
        System.out.println(countDistinctIntegers(new int[] {2, 2, 2}));
        System.out.println(countDistinctIntegers(new int[] {10}));
        System.out.println(countDistinctIntegers(new int[] {100, 1}));
        System.out.println(countDistinctIntegers(new int[] {121}));
        System.out.println(countDistinctIntegers(new int[] {1000000}));
        System.out.println(reverse(13) + " " + reverse(10) + " " + reverse(120) + " " + reverse(7));
    }
}

Running it prints:

Output
6
1
2
2
1
2
31 1 21 7

The 6 and the 1 at the top match the two examples. The third line, 2, comes from [10]: its reversal 1 is new, and 10 still counts, because the reversed numbers are added to the array and do not replace the originals.

The fourth line is also 2. Both 100 and 1 reverse to 1, so the set holds only 100 and 1. The palindrome 121 gives 1, since its reversal is 121 again. The sixth line, 2, comes from [1000000]: its six zeros all vanish when reversed, so the set holds 1000000 and 1. The last line shows the reversals themselves: 120 becomes 21, and a single digit such as 7 stays 7.

Complexity

The work is one pass over the array, with a short digit loop and two set additions for each number.

  • Time: O(n × d), where n is the length of the array and d is the number of digits in the largest number. reverse runs its loop once per digit, and each HashSet addition takes constant time on average. Numbers up to 1,000,000 have at most 7 digits, so this is close to O(n).
  • Space: O(n) for the set, which holds at most 2n values, one original and one reversal per number.

The same digit reversal also decides whether a number is a palindrome: see Palindrome Number.