I was doing the Hackerrank "New Year chaos" problem. Here is the description:
It is New Year's Day and people are in line for the Wonderland rollercoaster ride. Each person wears a sticker indicating their initial position in the queue from
1
ton
. Any person can bribe the person directly in front of them to swap positions, but they still wear their original sticker. One person can bribe at most two others.Determine the minimum number of bribes that took place to get to a given queue order. Print the number of bribes, or, if anyone has bribed more than two people, print
"Too chaotic"
.
The function is called with the desired permutation as its argument: minimumBribes([1,2,5,3,4])
.
My solution below times out:
def minimumBribes(q):
num_swaps = 0
for i, p in enumerate(q):
if p - (i+1) > 2:
print('Too chaotic')
return
if i+1 != p:
for j in range(min(i+1, len(q)), len(q)):
if p > q[j]:
num_swaps += 1
While this solution, that I found online, passes:
def minimumBribes(q): bribes = 0 for i, o in enumerate(q): cur = i + 1 if o - cur > 2: print("Too chaotic") return for k in q[max(o - 2, 0):i]: if k > o: bribes += 1 print(bribes)
I'm trying to understand what the difference is. Intuitive, my solution was "If an element is out of position, count how many elements behind it are smaller." I interpret the solution I found online as "If an element is out of position, count how many elements in front of it are larger."
I'd imagined these would be logically equivalent, but apparently not. Can anybody fill me in on what I'm missing?