![]() |
VOOZH | about |
Given two integers a and b. Your task is to count the number of integers between a and b where no two adjacent digits are the same.
Examples:
Input: a=11, b=13
Output: 2
Explanation: The two numbers are 12 and 13.Input: a=123, b=321
Output: 171
The idea is to use digit DP to solve this problem. The dp array dp[n][prev_digit][leading_zero][tight] represents count of valid numbers(whose adjacent digits are not same) formed by the n digits.
The parameters can be described as following:
curr: Represents the current position or digit being processed.prev_digit: Represents the previous digit at the previous position.leading_zero: Indicates whether there is a leading zero in the current number (1 if there is a leading zero, 0 otherwise).tight: Indicates whether the current number formed so far is tight (1 if tight, 0 otherwise).During the transition, the code iterates through possible digits for the current position, checking their validity by ensuring they differ from the previous digit and, if applicable, allowing consecutive leading zeroes. The state is then updated by recursively calling the
memfunction for the next position, adjusting flags likeleading_zeroandtightaccordingly. The count of valid numbers is accumulated by considering different digit choices, and memoization is applied to optimize repetitive calculations.The final answer will be the difference between count of valid numbers from [0,b] and [0,a-1].
Follow the steps to solve the problem:
mem function calculates the count of valid numbers based on the digit DP approach. It takes parameters s (string representation of the number), curr (current position), prev_digit (previous digit), leading_zero (consecutive leading zeroes), and tight (tightness of the number).curr is 0, indicating that the entire number has been processed, the function returns 1. If the result for the current state is already computed, it is directly returned.leading_zero is 0(means there are no leading zeroes) , the current digit must differ from the prev_digit.new_leading_zero and new_tight) based on the current digit.mem function for the next position (curr - 1).count1 represents count of valid numbers from [0,a-1] and count2 represents number of valid numbers from [0,b]. Below is the implementation of above approach:
171
Time Complexity: O(n*100), where n is number of digits of number n.
Auxilary Space: O(n*100)