New Year Chaos

Sort by

recency

|

32 Discussions

|

  • + 0 comments

    Required knowladge: Inversions This question requires a rare topic, that I think is very unlikely to come up in interwies. Again a not so great questions for the 3 month prep pack.

  • + 0 comments

    kudos to the author of this site https://csanim.com/tutorials/hackerrank-solution-new-year-chaos

    realy help me with optimized solution

    def minimumBribes(q):
        # Write your code here
        bribes = 0
        q = [0] + q
        for i,val in enumerate(q):       
            if val - i > 2:
                print('Too chaotic')
                return
            
            bribes += sum([i > val for i in q[max(val-1,0):i]])              
        
        print(bribes)
    
  • + 0 comments

    Here are some hints for optimizing the code: 1. start by checking for too much chaos at the start of your loop through q 2. check for how many values skipped in front of each sticker. limiting the section checked to only 2 places in front or less.

  • + 0 comments

    Python 3 O(n) solution: Utilized sorting and then a dictionary for quick lookups:

    def minimumBribes(q):
    
        chaos = ""
        maxNum = len(q)
        allBribes = 0
    
        # Create a dictionary to track the indices of elements in the queue
        index_map = {value: i for i, value in enumerate(q)}
    
        while maxNum > 0:
            indxMaxNum = index_map[maxNum]
            while maxNum - (indxMaxNum + 1) > 0:
                if maxNum - (indxMaxNum + 1) > 2:
                    chaos = "Too chaotic"
                    break
                q[indxMaxNum], q[indxMaxNum + 1] = q[indxMaxNum + 1], maxNum
    
                index_map[q[indxMaxNum]] = indxMaxNum
                index_map[q[indxMaxNum + 1]] = indxMaxNum + 1
    
                indxMaxNum= index_map[maxNum]
                allBribes += 1
            if chaos:
                break
            maxNum -= 1
        print("Too chaotic") if chaos != "" else print(allBribes)
    
  • + 0 comments

    How can the expected output from this q be 7?

    q = [1, 2, 5, 3, 7, 8, 6, 4]