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 of Numbers in Range where first digit is equal to last digit of the number
- Count numbers in a range with digit sum divisible by K having first and last digit different
- Last digit of a number raised to last digit of N factorial
- Find the remainder when First digit of a number is divided by its Last digit
- Count non-palindromic array elements having same first and last digit
- Count pairs from a given range whose sum is a Prime Number in that range
- Check if the first and last digit of the smallest number forms a prime
- N digit numbers having difference between the first and last digits as K
- Count of N-digit numbers having digit XOR as single digit
- Last digit of sum of numbers in the given range in the Fibonacci series
- Count of pairs in a given range with sum of their product and sum equal to their concatenated number
- Count the pairs in an array such that the difference between them and their indices is equal
- Count of pairs upto N such whose LCM is not equal to their product for Q queries
- Count numbers with same first and last digits
- Count substrings with same first and last characters
- Count all numbers up to N having M as the last digit
- Ways to form n/2 pairs such that difference of pairs is minimum
- Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
- Pairs with GCD equal to one in the given range
- Total distinct pairs from two arrays such that second number can be obtained by inverting bits of first
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.