Skip to content
Advertisement

Is there a simpler solution for Codingbat fix45?

I am trying to solve this CodingBat problem:

(This is a slightly harder version of the fix34 problem.) Return an array that contains exactly the same numbers as the given array, but rearranged so that every 4 is immediately followed by a 5. Do not move the 4’s, but every other number may move. The array contains the same number of 4’s and 5’s, and every 4 has a number after it that is not a 4. In this version, 5’s may appear anywhere in the original array.

JavaScript

I initially used a method which passed all of the sites tests, but I don’t think it would work for longer arrays. The initial method used 2 loops and did not use a new array. I have created a solution which introduces a new array and a 3rd nested loop and I believe will work for all instances of the problem. However, the site states that the problems in this section can be solved with 2 loops, so I am wondering if there actually is a 2 loop solution that will work for anyinstance of the problem. Here is the question and my 3 loop solution:

JavaScript

Advertisement

Answer

Restarting the search for a suitable 5 from one end of the array every time a 4 is found seems wasteful. Part of the array has already been scanned and is known not to contain a 5 that can be moved. This is O(n) time and O(1) space.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement