New Year Chaos

Sort by

recency

|

73 Discussions

|

  • + 0 comments

    It’s important to note that during processing, instead of letting the wrong person move back, the focus should be on bringing the correct person forward. After each step of the iteration, the person in the current scanning position should be sorted.

    For example, given [2 3 1 4 5]: If '2' is moved back, the result will be: [3 2 1 5 4]

    This accidentally allows '3' to gain an additional bribe. Been struggling with this for a while, hope this helps.

  • + 0 comments

    For anyone who is struggling but doesn't want the full solution. The question is essentially a reverse bubble sort, just make sure the Too chaotic condition is found first.

  • + 0 comments

    pyhton 3

    def minimumBribes(q):
        # Write your code here
        total_steps = 0
        n = len(q)
        for i in range(n):
            # Check if the element has moved more than two positions forward
            if q[i] - (i + 1) > 2:
                return print("Too chaotic")
                
            for j in range(max(0, q[i] - 2), i):
                    if q[j] > q[i]:
                        total_steps += 1
        
        return print(total_steps )
    
  • + 0 comments

    Javascript

    It's essentially a reverse insertion sort. You just keep looping through the array doing a single swap until it's sorted. Count how many times you had to make a swap to get it sorted. Break if the value of any element is more than two higher than its original position.

    function minimumBribes(q: number[]): void {
      let totalBribes = 0;
      
      let sorted = false;
      
      while (sorted === false) {
        sorted = true;
        
        for (let i=0; i < q.length-1; i++) {
          if (q[i] > q[i+1]) {
            if (q[i] - (i+1) > 2) {
              console.log('Too chaotic');
              return;
            }
            const temp = q[i];
            q[i] = q[i+1];
            q[i+1] = temp;
            sorted = false;
            totalBribes++;
          }
        }
      }
      
      console.log(totalBribes);
    }
    
  • + 0 comments

    Here is HackerRank New year chaos problem solution in Python, java, C++, C and javascript