Given a string integer X consisting of N digits and an integer K, the task is to find the smallest integer greater than or equal to X which is K periodic (K <= N).
Input: K = 2, X = “1215”
1313 is 2-periodic since digits at positions 1, 3 are ‘1’ and digits at positions 2, 4 are ‘3’. This is the smallest 2-periodic integer greater than or equal to “1215”.
Input: K = 3, X = “299398”
300300 is the smallest possible 3 periodic number.
To solve the problem, the idea is to make Xi = Xi-k for all i > K. Then follow the steps below to solve the problem:
- Check if X greater than or equal to the initial integer. If so, then print the current string as the answer.
- Otherwise, traverse from right to left and find the first digit which is not equal to 9. Then increment that digit by 1 and mark the position by a variable called pos.
- Then set all digits after pos up to the Kth digit to 0. Again make Xi = Xi-k for all i >K.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: 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.
- Smallest number greater than Y with sum of digits equal to X
- Count the number of words having sum of ASCII values less than and greater than k
- Smallest alphabet greater than a given character
- Smallest Greater (than S) String of length K whose letters are subset of S
- Count of alphabets having ASCII value less than and greater than k
- Find words which are greater than given length k
- Find words which are greater than given length k using stringstream
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Count number of rotated strings which have more number of vowels in the first half than second half
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Count number of substrings with numeric value greater than X
- Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
- Smallest odd digits number not less than N
- Find a string such that every character is lexicographically greater than its immediate next character
- Sub-strings having exactly k characters that have ASCII value greater than p
- Count of substrings whose Decimal equivalent is greater than or equal to K
- Count substring of Binary string such that each character belongs to a palindrome of size greater than 1
- Frequency of smallest character in first sentence less than that of second sentence
- Find the lexicographically smallest string which satisfies the given condition
- Smallest non-zero substring which has any permutation divisible by 2^K
Improved By : sapnasingh4991