Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #761: Special Binary String

In this guide, we solve Leetcode #761 Special Binary String in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Special binary strings are binary strings with the following two properties: The number of 0's is equal to the number of 1's. Every prefix of the binary string has at least as many 1's as 0's.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Recursion, String

Intuition

We need to scan characters while tracking positions or counts.

A simple state machine keeps the logic precise.

Approach

Iterate through the string once and update the state for each character.

Use a map or array if you need fast lookups.

Steps:

  • Iterate through characters.
  • Maintain necessary state.
  • Build or validate the output.

Example

Input: s = "11011000" Output: "11100100" Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped. This is the lexicographically largest string possible after some number of swaps.

Python Solution

class Solution: def makeLargestSpecial(self, s: str) -> str: if s == '': return '' ans = [] cnt = 0 i = j = 0 while i < len(s): cnt += 1 if s[i] == '1' else -1 if cnt == 0: ans.append('1' + self.makeLargestSpecial(s[j + 1 : i]) + '0') j = i + 1 i += 1 ans.sort(reverse=True) return ''.join(ans)

Complexity

The time complexity is O(n). The space complexity is O(1) to O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy