Lazy Pasha String Rotation
Problem:
Rotate Array k times left and print char at index j
One of the approach is to rotate and print output at index j
Time :O(n) Rotation * O(q) query
Another One:
If we got to know the index at which new rotated string will be started then it will only take O(q) time.
As per observation
if(index==-1)
index=(n-desired);
else
index=((n-desired)-(n-index)+n)%n;
Implementation
import java.util.*;
import java.lang.*;
import java.io.*;
class ArrayLeftRoatateN
{
public static void fn(char a[],int n,Scanner ab,int q)
{
int index=-1;
while(q-->0)
{
int type=ab.nextInt();
int desired=ab.nextInt()%n;
if(type==1)
{
if(index==-1)
index=(n-desired);
else
index=((n-desired)-(n-index)+n)%n;
}
else
System.out.println(a[(index+desired)%n]);
}
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int q=ab.nextInt();
fn(ab.next().toCharArray(),n,ab,q);
System.out.println();
}
}
}
Rotate Array k times left and print char at index j
One of the approach is to rotate and print output at index j
Time :O(n) Rotation * O(q) query
Another One:
If we got to know the index at which new rotated string will be started then it will only take O(q) time.
As per observation
if(index==-1)
index=(n-desired);
else
index=((n-desired)-(n-index)+n)%n;
Implementation
import java.util.*;
import java.lang.*;
import java.io.*;
class ArrayLeftRoatateN
{
public static void fn(char a[],int n,Scanner ab,int q)
{
int index=-1;
while(q-->0)
{
int type=ab.nextInt();
int desired=ab.nextInt()%n;
if(type==1)
{
if(index==-1)
index=(n-desired);
else
index=((n-desired)-(n-index)+n)%n;
}
else
System.out.println(a[(index+desired)%n]);
}
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int q=ab.nextInt();
fn(ab.next().toCharArray(),n,ab,q);
System.out.println();
}
}
}
0 Comments:
Post a Comment