HackerRank 'New Year Chaos' Solution

Martin Kysel · May 5, 2019

Short Problem Definition:

It’s New Year’s Day and everyone’s in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by 1 from 1 at the front of the line to N at the back.

Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original places in line. One person can bribe at most two others. For example, if n = 8 and Person 5 bribes Person 4, the queue will look like this: 1, 2, 3, 5, 4, 6, 7, 8.

Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state!

New Year Chaos

Complexity:

time complexity is O(N^2)

space complexity is O(1)

Execution:

This task is solvable in O(N), but I first attempted to solve the Naive way. This same solution times if the inner loop is allowed to start at 0. Limiting the search to one position ahead of the original position passes all HR tests cases.

The moral of the story? Why write 100 lines of code, if 8 are enough.

Solution:
def minimumBribes(q):
    moves = 0
    for pos, val in enumerate(q):
        if (val-1) - pos > 2:
            return "Too chaotic"
        for j in xrange(max(0,val-2), pos):
            if q[j] > val:
                moves+=1
    return moves

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.