Min Num of Reversals to Make Sequence

Nerly Ton
2 min readMay 3, 2021

This week I completed a timed coding challenge. I was extremely nervous because this is a test to see how I have improved on my DS&A. Even though I was not able to complete two out of four questions on time, I felt happy and excited because I noticed my improvement. The studying has been paying off. Now because I don't want to just barely pass by I want to be successful I will definitely keep focusing on getting better so that next time it will be 4 out of 4!

The two that I did not finish have been on my mind all week! I want to solve them!! Today we are going to talk about one of them. During the challenge, I focused on solving it with brute force. I was close to completing it but it would not solve the test cases. So I decided to go ahead and try solving it in my own IDE. I implemented the same logic I was going for in the coding challenge to try to understand what I was missing.

Problem:

Find the minimum number of coins that must be reversed in an array to make a sequence.

Example:

[1,1,1,0] = 1 you would need to reverse index 2 with 0 to make [1,0,1,0]

Solution:

With my brute force solution, I was able to pass 3 out of 4 test cases.

const head = 1
const tails = 0
let start = 0
let next = 1
let counter = 0
makePattern = (input) => {

while (next < input.length) {
if(input[start] === head && input[next] === tails){ start ++ next ++ } else if(input[start] === head && input[next] === head) { input[next] = tails counter += 1 start ++ next ++ } else if(input[start] === tails && input[next] === head) { start ++ next ++ } else { input[next] = head counter += 1 start ++ next ++ } } return counter}

This is when I realized I am focusing on making a sequence. But not on the MINIMUM. So in order to get the minimum, you would need to have something to compare it to. I know that I will need to go ahead and solve to make two sequences and then return the minimum one. I am excited to keep going and completing my solution! I hope this small walkthrough was helpful to reach an understanding of this problem. I am going to now work on getting the Minimum.

--

--