Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
For the above example, we will scan both the strings and as soon as we encounter a non-matching character(in above example b and d). we'll store these two characters. Now in string 1(i/p string) we'll find the position of b and d and subtract them to get the number of required shifts. So number of shifts will be 2.
Hence the answer : 2.
Please correct me if the solution fails for any case.
Code in c#:
ENJOY THE CONCEPTTTTTTTTTTTT
.......
static void Main(string[] args)
{
string s = "ABCDEFGH";
string newS = ShiftString(s);
Console.WriteLine(newS);
}
public static string ShiftString(string t)
{
char[] c = t.ToCharArray();
char save = c[0];
for (int i = 0; i < c.Length; i++)
{
if (c[i] != c[0])
c[i] = c[i - 1];
}
Console.WriteLine(c);
String s = new string(c);
return s;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
if (argc != 3)
{
Usage();
}
else
{
char* s1 = argv[1];
char* s2 = argv[2];
if (strlen(s1) != strlen(s2))
{
printf("the two string don't have the same size : \n %s -> %d \n %s -> %d", s1, strlen(s1) , s2, strlen(s2));
}
else
{
int i = 0;
int shift = 0;
while(i < strlen(s1) )
{
int isexisting = find(i, s1, s2);
if (isexisting != -1)
{
s2[isexisting] = ' ';// replace a used charcter in a string by a space in order to don't reuse it
if (isexisting != i)
{
shift++;
}
}
else
{
printf("2 strings don't match");
return 0;
}
i++;
}
printf("shift number: %d\n", shift/2);
}
}
return 0;
}
void Usage()
{
printf("\n ./NeededShift \"string1\" \"string2\" \n");
}
//find s1[pos] in s2 return -1 if not found
int find(int pos, char* s1, char* s2)
{
int i = 0;
while(i < strlen(s2))
{
if (s1[pos] == s2[i])
{
return i;
}
i++;
}
return -1;
}
What is the output for below string
- kunapareddy.sunil May 04, 2013i/p==abcd
o/p==adbc