Minimum Changes To Make Alternating Binary String

🏠 ⬅️ ➡️

You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.

The string is called alternating if no two adjacent characters are equal. For example, the string "010 " is alternating, while the string "0100 " is not.

Return the minimum number of operations needed to make s alternating.

Example 1:

Input: s = "0100 " Output: 1 Explanation: If you change the last character to '1', s will be "0101 ", which is alternating.

Example 2:

Input: s = "10 " Output: 0 Explanation: s is already alternating.

Example 3:

Input: s = "1111 " Output: 2 Explanation: You need two operations to reach "0101 " or "1010 ".

Constraints:

  • 1 <= s.length <= 104
  • s[i] is either '0' or '1'.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    integer :: i, j, k, n, m
    character(len=100) :: s

    ! Examples
    write (*,*) "Example 1:"
    s = "0100 "
    call solve(s)
    write (*,*) "Expected: 1"
    write (*,*) "Actual:", s

    write (*,*) "Example 2:"
    s = "10 "
    call solve(s)
    write (*,*) "Expected: 0"
    write (*,*) "Actual:", s

    write (*,*) "Example 3:"
    s = "1111 "
    call solve(s)
    write (*,*) "Expected: 2"
    write (*,*) "Actual:", s

contains

    subroutine solve(s)
        implicit none
        character(len=*), intent(inout) :: s

        ! Variables
        integer :: i, j, k, n, m

        ! Initialize variables
        n = len(s)
        m = 0

        ! Check if string is already alternating
        do i = 1, n - 1
            if (s(i) == s(i+1)) then
                exit
            end if
        end do

        if (i == n) then
            return
        end if

        ! Find first non-alternating character
        do i = 1, n
            if (s(i) /= s(i+1)) then
                exit
            end if
        end do

        ! Change character to opposite value
        if (s(i) == '0') then
            s(i) = '1'
        else
            s(i) = '0'
        end if

        ! Update counter
        m = m + 1

        ! Recursively call function until string is alternating
        call solve(s)

    end subroutine solve

end program main
Compiled
Executed
Correct
module alternating_string

implicit none

contains

integer function min_operations(s) result(res)

! Given a string s consisting only of the characters '0' and '1', return the minimum number of operations needed to make s alternating.

character(len=*), intent(in) :: s

integer :: i, n

! Initialize variables

n = len(s)
res = 0

! Check if the string is already alternating

if (mod(n, 2) == 0) then

! If the length of the string is even, check if all characters are equal

if (count(s == '0') == n/2) then

res = 1

else

! If the length of the string is even and not all characters are equal, check if the first and last characters are equal

if (s(1) == s(n)) then

res = 1

else

res = 2

endif

endif

else

! If the length of the string is odd, check if the first and last characters are equal

if (s(1) == s(n)) then

res = 1

else

res = 2

endif

endif

! If the string is not alternating, perform operations to make it alternating

if (res > 0) then

do i = 1, n-1

if (s(i) /= s(i+1)) then

res = res + 1

s(i) = s(i+1)

exit

endif

enddo

endif

end function min_operations

end module alternating_string

program test_alternating_string

use alternating_string

implicit none

! Test case 1:

call test("0100 ", 1)

! Test case 2:

call test("10 ", 0)

! Test case 3:

call test("1111 ", 2)

contains

subroutine test(s, expected)

character(len=*), intent(in) :: s
integer, intent(in) :: expected

integer :: res

res = min_operations(s)

if (res /= expected) then

write (*,*) "Error: min_operations(", s, ") returned ", res, " but expected ", expected

stop

endif

end subroutine test

end program test_alternating_string
🌐 Data from online sources
from typing import List

def canDistribute(nums: List[int], quantity: List[int]) -> bool:
    counts = [0] * 51
    for num in nums:
        counts[num] += 1

    quantity.sort(reverse=True)

    def dfs(idx: int) -> bool:
        if idx == len(quantity):
            return True
        for i in range(1, 51):
            if counts[i] >= quantity[idx]:
                counts[i] -= quantity[idx]
                if dfs(idx + 1):
                    return True
                counts[i] += quantity[idx]
        return False

    return dfs(0)
1. Count the occurrences of each unique value in the `nums` list and store them in an array `counts`.
  1. Sort the quantity array in descending order.
  2. Define a depth-first search function dfs that takes the index idx of the current customer. a. If idx reaches the total number of customers, all orders have been fulfilled so return true. b. For each unique value, if its count in counts is greater than or equal to the current customer's order quantity, subtract the order quantity from its count and call dfs for the next customer (idx + 1). c. If the quantity can be distributed successfully for the next customers, return true. Otherwise, restore the count in counts and continue to check the next unique value.
  3. Return the result of dfs(0) for the first customer's order fulfillment.
🌐 Data from online sources
#include <vector>
#include <algorithm>
using namespace std;

bool canDistribute(vector<int>& nums, vector<int>& quantity) {
    vector<int> counts(51, 0);
    for (int num : nums) {
        counts[num]++;
    }

    sort(quantity.rbegin(), quantity.rend());

    function<bool(int)> dfs = [&](int idx) {
        if (idx == quantity.size()) {
            return true;
        }
        for (int i = 1; i <= 50; ++i) {
            if (counts[i] >= quantity[idx]) {
                counts[i] -= quantity[idx];
                if (dfs(idx + 1)) {
                    return true;
                }
                counts[i] += quantity[idx];
            }
        }
        return false;
    };

    return dfs(0);
}
1. Count the occurrences of each unique value in the `nums` list and store them in an array `counts`.
  1. Sort the quantity array in descending order.
  2. Define a depth-first search function dfs that takes the index idx of the current customer. a. If idx reaches the total number of customers, all orders have been fulfilled so return true. b. For each unique value, if its count in counts is greater than or equal to the current customer's order quantity, subtract the order quantity from its count and call dfs for the next customer (idx + 1). c. If the quantity can be distributed successfully for the next customers, return true. Otherwise, restore the count in counts and continue to check the next unique value.
  3. Return the result of dfs(0) for the first customer's order fulfillment.