We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Python 3 O(n) solution: Utilized sorting and then a dictionary for quick lookups:
defminimumBribes(q):chaos=""maxNum=len(q)allBribes=0# Create a dictionary to track the indices of elements in the queueindex_map={value:ifori,valueinenumerate(q)}whilemaxNum>0:indxMaxNum=index_map[maxNum]whilemaxNum-(indxMaxNum+1)>0:ifmaxNum-(indxMaxNum+1)>2:chaos="Too chaotic"breakq[indxMaxNum],q[indxMaxNum+1]=q[indxMaxNum+1],maxNumindex_map[q[indxMaxNum]]=indxMaxNumindex_map[q[indxMaxNum+1]]=indxMaxNum+1indxMaxNum=index_map[maxNum]allBribes+=1ifchaos:breakmaxNum-=1print("Too chaotic")ifchaos!=""elseprint(allBribes)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
New Year Chaos
You are viewing a single comment's thread. Return to all comments →
Python 3 O(n) solution: Utilized sorting and then a dictionary for quick lookups: