Minimum number of operations to insert in sorted queue

Viewed 234

The given scenario is: There is a container that is open from both ends and that always is in sorted order. To insert an element, its position is determined, then each of the elements to the left or right of that position is removed. The new element is inserted, then the removed elements are added back. Each removal or insertion is an operation. Determine the minimum number of operations after inserting a list of integers into an empty list.

Example: An ordered array of integers has been created containing the values [2,5,6,10]. The value 3 must be inserted. It is determined that 3 goes between 2 and 5. Either remove the 2, insert the 3 and insert 2 for a total of 3 operations or remove the 5,6, and 10, insert 3, and insert 5,6,10 for a total of 7 operations. The minimal value, 3, is the result chosen.

For case of [10,6,2,3,7,1,2] answer is 13

Insert 10,Insert 6,Insert 2,Remove 2,Insert 3,Insert 2,Remove 10,Insert 7,Insert 10,Insert 1,Remove 1,Insert 2,Insert 2

Constraints are 1 <= n, arr[i] <= 10^5

Only python is supposed to be used and it doesn't have ordered sets that can handle duplicates. How to code it in an optimal way? time complexity could be o(nlogn) but I'm not aware of how to manage insertion in a sorted/ordered list in logN using python. Need some help.

def getIndex(arr,val):
    low=0
    high=len(arr)
    while(low<high):
        mid = (int)((low + high)/2)
        if (arr[mid]<val):
            low=mid+1
        else:
            high=mid
    return low
        
def get(arr):
    if len(arr)<=2:
        return len(arr)
    ele=[arr[0]]    
    count=1
    for i in range(1,len(arr)):
        # print("count:",count,"arr[i]:",arr[i],"ele:",ele)
        if arr[i]<=ele[0]:
            ele = [arr[i]]+ele
            count+=1
            continue
        if arr[i]>=ele[-1]:
            ele = ele+[arr[i]]
            count+=1
            continue
        ind = getIndex(ele,arr[i])
        indToAppend = min(ind,len(ele)-ind)
        count+=(indToAppend)*2+1
        # print("indToAppend: ", indToAppend,"count:" ,count, "arr[i]:",arr[i])
        ele = ele[0:indToAppend]+[arr[i]]+ele[indToAppend:len(arr)-1]
    # print(count,ele)
    return count
print(get([10,6,2,3,7,1,2]))
0 Answers
Related