Hackerank: Interview Prep Kit: New Year Chaos.

Samuel Ezedi
2 min readJan 17, 2021

Hello friends, we are going to be solving a problem I found on Hackerank, please stay focused as I share the problem and provide an answer. I will be providing answers majorly in Javascript and Dart.

Problem

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. Initial positions increment by 1 from 1 at the front of the line to  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. If anyone has bribed more than two people, the line is too chaotic to compute the answer.

Function Description

Complete the function minimumBribes in the editor below.minimumBribes has the foloowing parameter(s):
* int q[n]: the positions of the people after all bribes

Returns

* No value is returned. Print the minimum number of bribes necessary or Too chaotic if someone has bribed more than 2 people

Input Format

The first line contains an integer t, the number of test cases.
Each of the next t parirs of lines are as follows:
- The first line contains an integer t, the number of people in the queue
- The second line has n space-separated integers describing the final state of the queue.

Sample Input

2
5
2 1 5 3 4
5
2 5 1 3 4

Sample Output

3
Too chaotic

Explanation

Test Case 1

Hackerank
So the final state is 2,1,3,3,4 after three bribing operations.

Test Case 2

No person can bribe more than two people, yet it appears person 5 has done so. It is not possible to achieve the input state.

Solution in JS

Solution in Dart

Thanks for your time. Please take time to review the problem before looking at the solution. Remember this is for educational purposes and nothing more. Also, you can follow me here on Linkedin and, on Twitter.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Samuel Ezedi
Samuel Ezedi

No responses yet

Write a response