Intro to Tutorial Challenges

  • + 0 comments

    My solution using Python.

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'introTutorial' function below.
    #
    # The function is expected to return an INTEGER.
    # The function accepts following parameters:
    #  1. INTEGER V
    #  2. INTEGER_ARRAY arr
    #
    
    def search(arr, V, low, high):
        if low == high:
            if arr[low] == V:
                return low
            else:
                return -1
        
        third = (high - low + 1) // 3
        mid1 = low + third
        mid2 = high - third
        
        if arr[mid1] == V:
            return mid1
        if arr[mid2] == V:
            return mid2
        
        if V < arr[mid1]:
            return search(arr, V, low, mid1 - 1)
        elif V > arr[mid2]:
            return search(arr, V, mid2 + 1, high)
        else:
            return search(arr, V, mid1 + 1, mid2 - 1)
    
    def introTutorial(V, arr):
        # Write your code here
       return search(arr, V, 0, len(arr) - 1)
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        V = int(input().strip())
    
        n = int(input().strip())
    
        arr = list(map(int, input().rstrip().split()))
    
        result = introTutorial(V, arr)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()