New Year Chaos — HackerRank Medium

iAwale
1 min readMar 15, 2020

Link to problem

Github link to solution

To solve this problem efficiently, we store the each value and their positions into a HashMap. Then we pop off the largest value in the HashMap as we put it in the correct position of array while counting swaps along the way. Using a HashMap reduces the time complexity to linear time or O(n).

One important thing to keep in mind is that we must start from the highest item in the list because the question says “Any person in the queue can bribe the person directly in front of them to swap positions.”

A simple example would be the following case:

1 2 5 3 7 8 6 4 

Here if we start from the smaller value, when we reach 4, it is 4 swaps away from its correct position. Thus resulting in a “Too chaotic” condition. Thus we need to start from 8. Which would give us the correct answer of 7.

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

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet