Skip to content

Practice Replace the Substring for Balanced String

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#1234
LeetCode Problem

Replace the Substring for Balanced String

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. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.

Source: Replace the Substring for Balanced String on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
s = "QWER"
Output
0

# Example 2

Input
s = "QQWE"
Output
1

# Example 3

Input
s = "QQQW"
Output
2

Constraints

n == s.length
4 <= n <= 10^5
n is a multiple of 4.
s contains only 'Q', 'W', 'E', and 'R'.

Related LeetCode Problems

Practice more problems similar to Replace the Substring for Balanced String.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.