Javascript Program for Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element.
A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning.
For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the given condition is satisfied else print No.
Examples:
Input: x = 123
Output : Yes
The k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2.
Both 312 and 231 are greater than 123.
Input: 2214
Output: No
The k-cyclic shift of 2214 when k=2 is 1422 which is smaller than 2214
Approach: Simply find all the possible k cyclic shifts of the number and check if all are greater than the given number or not.
Below is the implementation of the above approach:
Javascript
<script>
function CheckKCycles(n, s)
{
var ff = true ;
var x = 0;
for (i = 1; i < n; i++)
{
x = (s.substring(i) + s.substring(0, i)).length;
if (x >= s.length)
{
continue ;
}
ff = false ;
break ;
}
if (ff)
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
}
var n = 3;
var s = "123" ;
CheckKCycles(n, s);
</script>
|
Time Complexity: O(N2), where N represents the length of the given string.
The time complexity of the program is O(N2) because first it runs a loop for traversing the string and inside that substring function is used.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Approach 2:
- Define a function CheckKCycles that takes an integer n and a string s as input.
- Initialize a boolean variable isKCycle as true.
- Iterate over the string starting from index 1 up to n-1.
- Compare characters s[i] and s[i % n].
- If the characters are not equal, set isKCycle as false and break the loop.
- After the loop, check the value of isKCycle.
- If it is true, print Yes to indicate a K-Cycle.
- If it is false, print No to indicate it is not a K-Cycle.
Below is the implementation of the above approach:
Javascript
function CheckKCycles(n, s) {
let isKCycle = true ;
for (let i = 1; i < n; i++) {
if (s[i] !== s[i % n]) {
isKCycle = false ;
break ;
}
}
if (isKCycle) {
console.log( "Yes" );
} else {
console.log( "No" );
}
}
let n = 3;
let s = "123" ;
CheckKCycles(n, s);
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Please refer complete article on Check whether all the rotations of a given number is greater than or equal to the given number or not for more details!
Last Updated :
02 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...