2914. Minimum Number of Changes to Make Binary String Beautiful - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Description:
You are given a binary string s. A binary string is defined as beautiful if it does not contain the substring "010". In one operation, you can flip a character from '0' to '1' or from '1' to '0'. Your goal is to return the minimum number of operations required to make the string beautiful.

Examples:

  1. Example 1:

    • Input: s = "010"
    • Output: 1
    • Explanation:
      The string "010" is not beautiful because it contains the substring "010". By flipping the last character from '0' to '1', we obtain "011", which does not contain "010". Hence, only 1 operation is required.
  2. Example 2:

    • Input: s = "01010"
    • Output: 1
    • Explanation:
      Although the string appears to have overlapping "010" patterns, a single flip is sufficient.
      Greedy walkthrough:
      • Scan the string from left to right.
      • At index 0–2, we see "010". Flip the character at index 2 to get "01110".
      • The resulting string "01110" does not contain "010".
        Therefore, only 1 operation is needed.
  3. Example 3:

    • Input: s = "101"
    • Output: 0
    • Explanation:
      The string "101" does not contain the substring "010", so it is already beautiful and no changes are required.

Constraints:

  • The string consists only of the characters '0' and '1'.
  • The length of s is at least 1.

Hints

  • Hint 1:
    Focus on detecting the exact substring "010". Once you find such a pattern, consider which character to flip so that you do not inadvertently create a new "010" pattern in overlapping regions.

  • Hint 2:
    A greedy strategy works well here: When you encounter "010", flip the last '0' to '1'. This choice helps to “fix” the current pattern while preventing potential overlapping issues from affecting subsequent portions of the string.

Approach

Greedy Approach (One-Pass Scan)

Explanation

The idea is to traverse the string from left to right and whenever the exact substring "010" is found, perform an operation to “fix” the pattern. The greedy decision is to flip the last '0' in the pattern to '1'. This choice is effective because:

  • It removes the current occurrence of "010".
  • It minimizes interference with adjacent characters, thereby reducing the risk of creating new "010" patterns that overlap.

Step-by-Step Walkthrough:

  1. Convert to a Mutable Structure:
    Since strings in many languages (like Python and Java) are immutable, convert the string to a character array (or list) for easy in-place modifications.

  2. Initialize a Counter:
    Set a counter (count) to 0 to track the number of changes made.

  3. Traverse the String:
    Start iterating from index 2 (the first possible ending index for a substring of length 3) until the end of the string.

    • For every index i, check if the substring formed by characters at positions i-2, i-1, and i is "010".
    • If yes, increment the count and flip the character at index i (i.e., change it from '0' to '1').
  4. Skip Overlapping Checks:
    After flipping a character, the modified value may affect overlapping patterns. In our greedy solution, since we always flip the third character, the already processed region is fixed, and subsequent checks continue normally.

  5. Return the Result:
    After scanning through the string, return the counter as the minimum number of operations required.

Pseudocode

function minChanges(s):
    Convert s to a mutable array, say charArray
    count = 0
    for i from 2 to length(charArray) - 1:
        if charArray[i-2] == '0' and charArray[i-1] == '1' and charArray[i] == '0':
            count += 1
            charArray[i] = '1'  // Flip the third character
    return count

Code Examples

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:
    The algorithm performs a single pass through the string (from index 2 to n – 1).
    Overall: O(n)

  • Space Complexity:
    In the Python solution, converting the string to a list requires O(n) space.
    In the Java solution, using a character array also requires O(n) space.
    Overall (excluding input): O(n)

Common Mistakes and Edge Cases

Common Mistakes

  • Flipping the Wrong Character:
    Flipping any other character than the third one (the last '0' in "010") might not fix overlapping occurrences optimally.

  • Not Skipping Overlapping Regions:
    Failing to account for overlapping patterns can lead to extra or redundant flips. The greedy approach inherently manages overlaps by fixing the end of each "010" pattern.

Edge Cases

  • Short Strings:
    If the string length is less than 3, it cannot contain "010", so the answer should be 0.

  • Strings with No Occurrence:
    If the string does not contain "010" at all, no changes are needed.

  • Multiple Overlapping Patterns:
    For strings like "01010", careful handling ensures that one flip fixes overlapping patterns.

Alternative Approaches

  • Sliding Window or Regular Expressions:
    Although you could use regular expressions to detect "010", handling overlapping occurrences efficiently is simpler with a greedy scan.

  • Dynamic Programming:
    A DP approach could consider each index and the minimum changes needed up to that point, but the greedy method is both simpler and optimal for this specific pattern.

  • Minimum Flips to Make a Binary String Alternating:
    Transform a binary string into an alternating string (e.g., "0101..." or "1010...").

  • Minimum Operations to Convert String:
    Other problems that ask for the minimum number of operations to reach a target string configuration.

  • Substring Pattern Removal Problems:
    Challenges where the task is to remove or replace occurrences of a given substring pattern.

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How to do LinkedIn interview prep?
Are there any free coding courses?
Which programming language is Meta?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.