1227. Reversed Twin Pairs

Easy1.5 points estimatedHash TableMathsCountingArray3 hints

A ticket office prints each ticket number and also its mirror image, the number read backwards. Define rev(x) as the decimal digits of x written in reverse order with leading zeros dropped, so rev(120) = 21 and rev(7) = 7.

Given the array nums, return the number of index pairs i < j such that nums[i] == rev(nums[j]). Note the direction: the earlier number must equal the reversal of the later one. Return the count as a 64-bit integer.

Sweep j from left to right, look up rev(nums[j]) in a hash map of counts of the values seen so far, then record nums[j]. This takes O(n * d) time for d digits, effectively O(n), and O(n) space.

Example 1

Input:
nums = [12,21,5,50,5]
Output:
3
Explanation:

Pairs are (12, 21), (5, 50) and (5, 5 at the end): the earlier value equals the reversal of the later one, so 3.

Example 2

Input:
nums = [21,120]
Output:
1
Explanation:

rev(120) = 21, which equals the earlier value 21, so there is 1 pair.

Example 3

Input:
nums = [7,7,7]
Output:
3
Explanation:

Every number reverses to itself, giving the pairs (0,1), (0,2), (1,2): 3 in total.

Constraints

1 ≤ n ≤ 1000

1 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…