Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum number of Alternating 1 and 0

I want to find the minimum number of flips required to get an alternating of [0, 1, 0, 1] for example given [1, 1, 0, 1]. so in this case, it is one flip.

def solution(A):
    count = 0
    myDict = {}
    myDict[1] = True
    myDict[0] = False

    next = None
    # first element value
    val = myDict[A[0]]
    if val == True:
        next = False
    else:
        next = True

    for element in A[1:]:
        if next != myDict[element]:
            count += 1
            # do something to update element
            myDict[element] = next
        if myDict[element] == True:
            next = False
        else:
            next = True

    return count

My solution does not work for the input [1, 1, 0, 1, 1]. Because it gives back 3 when the answer it should give back is 2(change the first index and last index elements to 0). How can i solve this?

like image 353
Ninja Dude Avatar asked Nov 28 '25 18:11

Ninja Dude


1 Answers

You could just count the differences for each kind of pattern and take the min

def minFlip(a):
    return min(
        sum(n == i % 2 for i, n in enumerate(a)),
        sum(n == (i + 1) % 2 for i, n in enumerate(a))
    )

minFlip([1, 1, 0, 1, 1])
#2
minFlip([0, 1, 0, 1, 0])
#0
minFlip([1, 1, 1, 1, 1])
#2
minFlip([0, 0, 0, 0, 0])
#2
like image 63
Mark Avatar answered Dec 01 '25 06:12

Mark