Amazon Interview Question
Quality Assurance EngineersTeam: Ring
Country: United States
Here is my python solution
def findDistance(sentence:str,start:str,end:str)->int:
if len(sentence) == 0:
return 0
elif start not in sentence or end not in sentence:
return -1
elif start == end and start in sentence and sentence.count(start) > 1:
s_index = sentence.find(start)
e_index = sentence.find(end,s_index+1,len(sentence))
return abs(e_index - s_index)
elif start != end:
return abs(sentence.index(start)-sentence.index(end))
else:
return -1
s = "Ajay is here"
st,en = 'A','h'
print(findDistance(s,st,en))
st,en = 'e','k'
print(findDistance(s,st,en))
st,en = 'g','z'
print(findDistance(s,st,en))
public static void findCharDistance(String str, char a, char b) {
if(str == null ||
!str.contains(Character.toString(a)) ||
!str.contains(Character.toString(b)) ||
str.isBlank()) {
System.out.println("-1");
}else if(a != b){
System.out.println(Math.abs(str.indexOf(a) - str.indexOf(b)));
}else {
System.out.println(Math.abs(str.indexOf(a) - str.lastIndexOf(b)));
}
}
test data:
FindDistance.findCharDistance(null, 'a', 'b');
FindDistance.findCharDistance(" ", 'a', 'b');
FindDistance.findCharDistance("Ajay is here", 'A', 'z');
FindDistance.findCharDistance("Ajay is here", 'z', 'h');
FindDistance.findCharDistance("Ajay is here", 'A', 'h');
FindDistance.findCharDistance("Ajay is here", 'z', 'y');
FindDistance.findCharDistance("Ajay is here", 'A', 'a');
FindDistance.findCharDistance("Ajay is here", 'A', 'A');
FindDistance.findCharDistance("Ajay is here", 'e', 'e');
public class FindDistance {
public static void findCharDistance(String str, char a, char b) {
if(str == null ||
!str.contains(Character.toString(a)) ||
!str.contains(Character.toString(b)) ||
str.isBlank()) {
System.out.println("-1");
}else if(a != b){
System.out.println(Math.abs(str.indexOf(a) - str.indexOf(b)));
}else {
System.out.println(Math.abs(str.indexOf(a) - str.lastIndexOf(b)));
}
}
}
test data :
FindDistance.findCharDistance(null, 'a', 'b');
FindDistance.findCharDistance(" ", 'a', 'b');
FindDistance.findCharDistance("Ajay is here", 'A', 'z');
FindDistance.findCharDistance("Ajay is here", 'z', 'h');
FindDistance.findCharDistance("Ajay is here", 'A', 'h');
FindDistance.findCharDistance("Ajay is here", 'z', 'y');
FindDistance.findCharDistance("Ajay is here", 'A', 'a');
FindDistance.findCharDistance("Ajay is here", 'A', 'A');
FindDistance.findCharDistance("Ajay is here", 'e', 'e');
Both chars present in the string and both unique
- anaghgg September 24, 2020Both absent
Unique, one present and one absent
Same chars
Unique and first occurs after second -> Test for absolute distance