GATE 2013 CS (CS1) – Question 60
A has length five; oldc,newc each have length three. The intended operation replaces each original A character at most once using the corresponding mapping.
void find_and_replace(char *A, char *oldc, char *newc) {
for (int i=0; i<5; i++)
for (int j=0; j<3; j++)
if (A[i]==oldc[j]) A[i]=newc[j];
}Tests: (1) oldc="abc",newc="dab"; (2) "cde","bcd"; (3) "bca","cda"; (4) "abc","bac". Across every five-character string over {a,b,c,d,e}, allowing duplicates, how many of the four mappings can expose the flaw?
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (B) Only two
Explanation
The flaw is replacing a newly written character again later in the same inner loop. In test three, b→c at j=0 then c→d at j=1, exposing b→d instead of c. In test four, a→b then b→a, undoing a’s intended replacement. Tests one and two map to an earlier oldc position, so no later rematch changes the result. Exactly two tests expose it, B.