Given a number N, the task is to find the number of pairs (A, B) in range [1, N] such that the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.
Input: N = 25
The pairs are:
(1, 1), (1, 11), (2, 2), (2, 22), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (11, 1), (11, 11), (12, 21), (21, 12), (22, 2), (22, 22)
Input: N = 100
Approach: For each pair of integers (i, j)(0 ≤ i, j ≤ 9), let us define ci, j (1 ≤ k ≤ N) which is the count of first digit of k is equal to i, and the last digit is equal to j. By using ci, j, the answer for the problem can be calculated by ∑i=09 ∑j=09 ci, j * cj, i .
Below is the implementation of the above approach:
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count digits in a factorial | Set 2
- Count of Binary Digit numbers smaller than N
- Count numbers that don't contain 3
- Generate integer from 1 to 7 with equal probability
- Count the number of possible triangles
- Segment Tree | Set 1 (Sum of given range)
- Count numbers with same first and last digits
- Count digits in given number N which divide N
- Count all possible paths from top left to bottom right of a mXn matrix
- Count trailing zeroes in factorial of a number
- Count Possible Decodings of a given Digit Sequence
- Count ways to reach the n'th stair
- Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n
- Count inversions in an array | Set 3 (Using BIT)
- Count numbers from 1 to n that have 4 as a digit
- Count factorial numbers in a given range
- Count of n digit numbers whose sum of digits equals to given sum
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Print all non-increasing sequences of sum equal to a given number x
- Sum of bit differences among all pairs
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.