 # TSTROBOT - EDITORIAL

Tester: Aleksa Plasvic
Editorialist: Taranpreet Singh

Cakewalk.

None.

# PROBLEM:

Given a robot and its starting point X and N commands each being either move left or mode right, Find out the number of distinct positions visited by the robot after performing all operations.

# QUICK EXPLANATION

• Start position does not affect the final answer since by choosing a different start point only the set of points differ.
• So we can simply simulate all the steps with any start point and maintain a list of visited position, adding a new position every time we enter the new position.
• To avoid negative position, we can simply choose any start point > N as within N steps, Robot cannot go to any negative position.

# EXPLANATION

First thing, the start point do not affect the number of points. So, even if we change the start point, to say 0, Answer remains the same.

Now, since the number of operations is quite small, we can just simulate the operations. Let’s choose a start point, say 0. Now, we move one step to the left every time we encounter a Left command and move right every time we encounter the right command. We can just keep a set and add all the positions visited including the start position.

After executing all commands, the size of the set is the number of distinct positions visited.

In case you choose to record visited position using the boolean array, you need to take care of negative index. Taking starting point > N automatically handles that.

This solution has time as well as memory complexity O(N) and is good enough to pass. But we can reduce memory complexity to O(1) by noticing the fact that the positions visited always form a consecutive range from some min value to some max value, thus containing max-min+1 positions in the range. So, during simulation, we can just keep track of the minimum and maximum position reached and print out the number of positions, leading to memory complexity O(1).

Bonus Problems

Given robot, at a start point, X, execute following commands and print the number of distinct positions visited.

The first problem - Move y steps to direction D step by step.
Second problem - Jump y steps to direction D.

Solve both these problems and prove why your solutions are optimal (If they are :P).

# Time Complexity

Time complexity is O(N) per test case.

# SOLUTIONS:

Setter's Solution
``````#include <iostream>
#include <algorithm>
#include <string>
#include <assert.h>
using namespace std;

long long readInt(long long l,long long r,char endd){
long long x=0;
int cnt=0;
int fi=-1;
bool is_neg=false;
while(true){
char g=getchar();
if(g=='-'){
assert(fi==-1);
is_neg=true;
continue;
}
if('0'<=g && g<='9'){
x*=10;
x+=g-'0';
if(cnt==0){
fi=g-'0';
}
cnt++;
assert(fi!=0 || cnt==1);
assert(fi!=0 || is_neg==false);

assert(!(cnt>19 || ( cnt==19 && fi>1) ));
} else if(g==endd){
assert(cnt>0);
if(is_neg){
x= -x;
}
assert(l<=x && x<=r);
return x;
} else {
assert(false);
}
}
}
string readString(int l,int r,char endd){
string ret="";
int cnt=0;
while(true){
char g=getchar();
assert(g!=-1);
if(g==endd){
break;
}
cnt++;
ret+=g;
}
assert(l<=cnt && cnt<=r);
return ret;
}
long long readIntSp(long long l,long long r){
}
long long readIntLn(long long l,long long r){
}
string readStringLn(int l,int r){
}
string readStringSp(int l,int r){
}

int T;
string s;
int n;

int main(){
//freopen("00.txt","r",stdin);
//freopen("00o.txt","w",stdout);
int x0;
while(T--){
int mn=x0,mx=x0;
for(int i=0;i<n;i++){
assert(s[i]=='L' || s[i]=='R');
}
for(int i=0;i<n;i++){
if(s[i]=='L'){
x0--;
} else {
x0++;
}
mn=min(mn,x0);
mx=max(mx,x0);
}
cout<<mx-mn+1<<endl;
}
assert(getchar()==-1);

}
``````
Tester's Solution
``````#include<bits/stdc++.h>

using namespace std;

void solve()
{
int n,x0;
string s;

cin>>n>>x0;
cin>>s;

int mi=0;
int mx=0;
int cur = 0;
for (int i=0;i<n;i++){
if (s[i]=='L') cur--; else
cur++;
mx = max(mx, cur);
mi = min(mi, cur);
}

cout<<mx-mi+1<<endl;
}
int main()
{
int t;
cin>>t;

while(t--)
solve();
return 0;
}
``````
Editorialist's Solution
``````import java.util.*;
import java.io.*;
import java.text.*;
//Solution Credits: Taranpreet Singh
class TSTROBOT{
//SOLUTION BEGIN
void pre() throws Exception{}
void solve(int TC) throws Exception{
int n = ni(), x= ni();
int min = x, max = x;
String s = n();
for(int i = 0; i< n; i++){
if(s.charAt(i)=='L')x--;
else x++;
min = Math.min(min, x);
max = Math.max(max, x);
}
pn(max-min+1);
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
long mod = (long)1e9+7, IINF = (long)1e18;
final int INF = (int)1e9, MX = (int)3e5+2;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8;
static boolean multipleTC = true, memory = false;
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC)?ni():1;
//Solution Credits: Taranpreet Singh
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new TSTROBOT().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new TSTROBOT().run();
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}

StringTokenizer st;
}

public FastReader(String s) throws Exception{
}

String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException  e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}

String nextLine() throws Exception{
String str = "";
try{
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
}
``````

Feel free to Share your approach, If it differs. Suggestions are always welcomed. 5 Likes

For Bonus problem 1: Solution is same as the main problem. just increase/decrease curr variable by y instead of 1.
Expected time complexity: O(N)
Expected memory: O(1)
For Bonus problem 2: use a map/dict/set and insert that position if not already present and print size.
Expected time complexity: O(N)
Expected memory: O(N)
Is there effiecient memory wise solution for Bonus problem 2?

4 Likes
``````	for(it=s.begin();it!=s.end();it++)
{
if(*it=='L')
countl++;
else if(*it=='R')
countr++;
}
if(countr>countl)
c=2*countr-countl-1;
else
c=2*countl-countr-1;
cout<<c<<endl;
``````

what is the issue in using this equation?

what if any of count is 0?

Here is the solution of the problem using set STL property,which will store the unique elements collection.

``````  #include <bits/stdc++.h>

using namespace std;

int main() {
int t;
cin>>t;
while(t--)
{
int len , start;
cin>>len>>start;
set<int >se;
string inst;
cin>>inst;
se.insert(start);
for(int i=0;i<len;i++)
{
if(inst[i] == 'L')
{
start--;
se.insert(start);

}
else
{

start++;
se.insert(start);
}

}

cout<<se.size()<<endl;
}
}``````
1 Like

t=int(input())
for i in range(t):
N,X=input().split(’ ')
N,X=int(N),int(X)
S=input()
a,b=0,0
a=S.count(‘R’)
b=S.count(‘L’)
if(a<=b):
a=a+(b-a)+1
print(a)
elif(b<a):
b=b+(a-b)+1
print(b)

include <stdio.h>
#include<string.h>
int main(void) {
int T;
scanf("%d",&T);
for(int i=0;i<T;i++)
{
int N,X,netpos;
scanf("%d %d",&N,&X);
char arr[N],pos[N];
pos= X;
netpos=N+1;
int current=X;
scanf("%s",arr);
for(int j=0;j<N;j++)
{
if(arr[j]==‘R’)
{ current=current +1;
pos[j+1]=current;

``````         }
if(arr[j]=='L')
{
current=current-1;
pos[j+1]=current;

}
}

int count=0;
for(int u=0;u<N+1;u++)
{
for(int y=u+1;y<N+1;y++)
{
if(pos[u]==pos[y])
{
count++;
}

}
}
printf("%d",N+1-count);
printf("\n");
``````

}

``````return 0;
``````

}

By this approach i am getting correct solution , codechef isn’t accepting it?

In this approach i have made an array of positions traveled by robot , and counted the distinct number of positions from it ???

why it gives me wrong answer?********************
#include <stdio.h>
int main()
{
int xx, a, s, d, f, g, h, o, n = 0, m = 0, z = 1, x = 1, sum = 0, max = 0;
scanf("%d", &xx);

``````while (xx--)

{

sum = n = m = max,z,x = 1;

scanf("%d%d", &a, &s);

char q[a + 1];

scanf("%s", q);

for (int i = 0; i < a - 1; i++)

if (q[i] == 'L' && q[i + 1] == 'L')

{

z++;

z > n ? n = z : 1;

x = 1;

}

else if (q[i] == 'R' && q[i + 1] == 'R')

{

x++;

x > m ? m = x : 1;

z = 1;

}

printf("%d\n", n > m ? ++n : ++m);

}

return 0;
``````

}