Python Solution.
def bin_Search(arr, val):
low = 0
high = len(arr)-1
while low <= high:
mid = (low + high) // 2
if val < arr[mid]:
high = mid - 1
elif val > arr[mid]:
low = mid + 1
else:
return True
else:
return False
first = ["Alice", "Ariel", "Aurora", "Phil", "Peter", "Olaf", "Phoebus", "Ralph", "Robin"]
first.sort()
second = ["Bambi", "Belle", "Bolt", "Mulan", "Mowgli", "Mickey", "Silver", "Simba", "Stitch"]
second.sort()
third = ["Dumbo", "Genit", "Jiminy", "Kuzko", "Kida", "Kenai", "Tarzan", "Tiana", "Winnie"]
third.sort()
n = int(input())
pos = 1
steps = 0
for i in range(n):
name = str(input())
if bin_Search(first, name) == True:
steps += pos - 1
pos = 1
elif bin_Search(second, name) == True:
if (pos - 2) < 0:
steps += ((pos - 2) * -1)
pos = 2
else:
steps += pos - 2
pos = 2
else:
if (pos - 3) < 0:
steps += ((pos - 3) * -1)
pos = 3
else:
steps += pos - 3
pos = 3
print(steps)
In this solution i used binary search