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

Leetcode #1234: Replace the Substring for Balanced String

In this guide, we solve Leetcode #1234 Replace the Substring for Balanced 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

You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'. A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: String, Sliding Window

Intuition

We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.

Expanding and shrinking the window lets us maintain validity without restarting the scan.

Approach

Grow the window with a right pointer, and shrink from the left only when the constraint is violated.

Track the best window as you go to keep the solution linear.

Steps:

  • Expand the right end of the window.
  • While invalid, move the left end to restore constraints.
  • Update the best window found.

Example

Input: s = "QWER" Output: 0 Explanation: s is already balanced.

Python Solution

class Solution: def balancedString(self, s: str) -> int: cnt = Counter(s) n = len(s) if all(v <= n // 4 for v in cnt.values()): return 0 ans, j = n, 0 for i, c in enumerate(s): cnt[c] -= 1 while j <= i and all(v <= n // 4 for v in cnt.values()): ans = min(ans, i - j + 1) cnt[s[j]] += 1 j += 1 return ans

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(C)O(C)O(C). The space complexity is O(C)O(C)O(C).

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