This is the question. I came up with an algorithm but I kept on getting a Wrong Answer status. I need to know what’s wrong with my approach.
Here’s my algorithm:
Traverse the char array s: for i in range(0,len(s))
1. If c = '?' start from p=0 and check if p is present in left or right. If yes then increment it and repeat this step until p != left and p != right.
2. Check if p >= k. If yes then print NO and continue to the next test case.
3. Put the value of p in s[i] and continue
4. If c != '?', then check if c = its left and right digits. If it is, then print NO and continue to the next test case.
There’s a special case I’ve had to handle, when k=2 and s[0] = ‘?’ (do a dry run for the input k = 2, s = ???0 on my algo, the output will turn out to be NO, whereas it should be 1010, so it’s easy to figure out why that’s a special case). For k=2, the digits will alternate. Hence, if the first character is 1, the whole string can be determined. If s[0] is ‘?’, then in the answer s[0] maybe 0 or 1. That’s the special case I’ve considered.
Here’s a little bit of theory on why my program (according to me) would always work correctly.
I’ve handled the cases when k = {1,2} correctly, and for all k >= 3, answer can never be NO, provided the input test case is not already incorrect (having at least 1 pair of same adjacent digits). This is because, any digit (in the circle) will have exactly 2 neighbours, and I will have at least 3 colors to put, hence all cases k>=3 are also handled. Now, according to me my logic isn’t wrong in any way, but when I submit, I’m getting a Wrong Answer.
Just for more details, here’s the C code:
#include <stdio.h>
#include <string.h>
int main()
{
int t; scanf("%d\n",&t);
while(t--)
{
int a=0,k,len; scanf("%d\n",&k);
char s[101]; scanf("%s\n",&s);
len = strlen(s);
if(k==2 && s[0] == '?') // the special test case I was talking about
{
while(s[++a] == '?');
if(a < len && ((a%2 == 0 && s[a] == 49) || (a%2 == 1 && s[a] == 48))) s[0] = 49;
}
for(a=0;a<len;a++)
{
int l = a==0 ? len-1 : a-1, r = a==len-1 ? 0 : a+1, p=0;
if(s[a] == '?')
{
while(s[l]-48 == p || s[r]-48 == p) p++;
if(p >= k) goto NP;
s[a] = p+48;
}
else // checking the validity of input string
{
if(s[a] == s[l] || s[a] == s[r] || s[a] >= k+48) goto NP;
}
}
printf("%s\n",s); continue;
NP:
printf("NO\n");
}
}
From the problem statement:
Run your code with the following input:
That is T=1, K=5, and one piece of cake with one cherry color “2”
What is it supposed to do instead?