Skip to main content

Minimum Deletions to Make Alternating Substring - Solution & Explanation

HardStringSegment Tree13 min read
Practice this problem

Problem Statement

You are given a string s of length n consisting only of the characters 'A' and 'B'.

You are also given a 2D integer array queries of length q, where each queries[i] is one of the following:

  • [1, j]: Flip the character at index j of s i.e. 'A' changes to 'B' (and vice versa). This operation mutates s and affects subsequent queries.
  • [2, l, r]: Compute the minimum number of character deletions required to make the substring s[l..r] alternating. This operation does not modify s; the length of s remains n.

A substring is alternating if no two adjacent characters are equal. A substring of length 1 is always alternating.

Return an integer array answer, where answer[i] is the result of the ith query of type [2, l, r].

 

Example 1:

Input: s = "ABA", queries = [[2,1,2],[1,1],[2,0,2]]

Output: [0,2]

Explanation:

i queries[i] j l r s before query s[l..r] Result Answer
0 [2, 1, 2] - 1 2 "ABA" "BA" Already alternating 0
1 [1, 1] 1 - - "ABA" - Flip s[1] from 'B' to 'A' -
2 [2, 0, 2] - 0 2 "AAA" "AAA" Delete any two 'A's to get "A" 2

Thus, the answer is [0, 2].

Example 2:

Input: s = "ABB", queries = [[2,0,2],[1,2],[2,0,2]]

Output: [1,0]

Explanation:

i queries[i] j l r s before query s[l..r] Result Answer
0 [2, 0, 2] - 0 2 "ABB" "ABB" Delete one 'B' to get "AB" 1
1 [1, 2] 2 - - "ABB" - Flip s[2] from 'B' to 'A' -
2 [2, 0, 2] - 0 2 "ABA" "ABA" Already alternating 0

Thus, the answer is [1, 0].

Example 3:

Input: s = "BABA", queries = [[2,0,3],[1,1],[2,1,3]]

Output: [0,1]

Explanation:

i queries[i] j l r s before query s[l..r] Result Answer
0 [2, 0, 3] - 0 3 "BABA" "BABA" Already alternating 0
1 [1, 1] 1 - - "BABA" - Flip s[1] from 'A' to 'B' -
2 [2, 1, 3] - 1 3 "BBBA" "BBA" Delete one 'B' to get "BA" 1

Thus, the answer is [0, 1].

 

Constraints:

  • 1 <= n == s.length <= 105
  • s[i] is either 'A' or 'B'.
  • 1 <= q == queries.length <= 105
  • queries[i].length == 2 or 3
    • queries[i] == [1, j] or,
    • queries[i] == [2, l, r]
    • 0 <= j <= n - 1
    • 0 <= l <= r <= n - 1

Approach Overview

Problem Overview: You are given a string and need the minimum number of deletions required so that the remaining characters form an alternating substring (no two adjacent characters are equal). Deletions can occur at any index, but the relative order of the remaining characters must stay the same.

Approach 1: Brute Force Substring Enumeration (O(n3) time, O(1) space)

Enumerate every possible substring and simulate deletions needed to make that substring alternating. For each substring s[i..j], iterate through characters and count how many adjacent duplicates must be removed to maintain an alternating pattern. This approach checks all O(n^2) substrings and scans each substring in O(n). It works for very small inputs but becomes impractical once the string grows beyond a few hundred characters.

Approach 2: Greedy Alternating Scan (O(n) time, O(1) space)

An alternating string must follow one of two patterns: starting with the first character or starting with its opposite. Traverse the string and track violations where s[i] == s[i-1]. Each violation implies one deletion is required to break the duplicate pair. The key insight is that deleting one character from every equal adjacent pair ensures the resulting sequence alternates. This linear scan works when the task only involves validating or fixing the entire string.

Approach 3: Binary Indexed Tree / Fenwick Tree (O(n log n) time, O(n) space)

For larger inputs or scenarios where substring ranges must be evaluated efficiently, a segment tree or Binary Indexed Tree helps maintain prefix statistics of characters and alternating violations. Store counts of characters or mismatch positions in the Fenwick tree. While iterating the string, query prefix ranges to determine how many deletions are required to enforce alternating order inside a candidate range. Updates and prefix queries both run in O(log n), allowing the algorithm to evaluate optimal deletion strategies without rescanning the entire substring each time.

This structure is particularly useful when the solution needs repeated range queries or dynamic updates. The Fenwick tree compresses the required state into prefix sums and enables fast difference calculations between indices.

Recommended for interviews: Start by explaining the greedy observation that adjacent duplicates force deletions. That demonstrates you understand the alternating constraint. Then move to the Fenwick tree optimization, which handles large inputs and repeated range queries efficiently. Interviewers usually look for the transition from a direct scan to a data-structure-driven solution using string processing combined with indexed trees.

Solution

We can convert the string s into an array nums of length n, where nums[0] = 0, and for 1 leq i < n, if s[i] = s[i-1], then nums[i] = 1, otherwise nums[i] = 0. This way nums[i] represents whether there are adjacent and equal characters at index i. Then calculating the minimum number of character deletions required to make the substring s[l..r] an alternating string in the interval [l, r] is equivalent to calculating the sum of elements in the nums array over the interval [l+1, r].

To handle queries efficiently, we can use a Binary Indexed Tree to maintain the prefix sum of the nums array. For queries of type [1, j], we need to flip nums[j] and nums[j+1] (if j+1 < n), and update the Binary Indexed Tree. For queries of type [2, l, r], we can quickly calculate the sum of elements over the interval [l+1, r] through the Binary Indexed Tree.

The time complexity is O((n + q) log n), and the space complexity is O(n), where n is the length of the string s, and q is the number of queries.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Substring EnumerationO(n^3)O(1)Conceptual baseline or very small strings
Greedy Alternating ScanO(n)O(1)When validating or fixing a single string without range queries
Binary Indexed Tree (Fenwick Tree)O(n log n)O(n)Efficient handling of prefix queries, dynamic updates, or large constraints

Video Solution

Minimum Deletions to Make Alternating Substring | Segment Tree | Leetcode 3777 • Techdose • 506 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Minimum Deletions to Make Alternating Substring easy or hard?
The problem is typically classified as Hard because it combines string constraints with advanced data structures like Fenwick Trees or Segment Trees. While the core alternating rule is simple, optimizing it for large inputs or range queries increases the complexity.
Minimum Deletions to Make Alternating Substring Python/Java solution
The standard solution maintains prefix statistics using a Fenwick Tree while iterating the string. Implementations in Python, Java, C++, Go, and TypeScript follow the same structure: update counts at each index and query prefix ranges to compute required deletions.
How to solve Minimum Deletions to Make Alternating Substring in O(n)?
Traverse the string once and count adjacent duplicates. Whenever s[i] equals s[i-1], one of the characters must be deleted to maintain an alternating sequence. This greedy observation yields an O(n) time and O(1) space solution for the basic version of the problem.
What is the best approach for Minimum Deletions to Make Alternating Substring?
The most scalable approach uses a Binary Indexed Tree (Fenwick Tree). It maintains prefix counts and allows fast range queries to determine how many deletions are required to enforce alternating order. This reduces repeated substring scans and runs in O(n log n) time with O(n) space.
Is Minimum Deletions to Make Alternating Substring asked at Google/Amazon/Meta?
String manipulation and alternating pattern problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants often combine string processing with data structures such as segment trees or Fenwick trees to handle range queries efficiently.
What data structure is used in Minimum Deletions to Make Alternating Substring?
Efficient implementations often use a Binary Indexed Tree (Fenwick Tree) or a Segment Tree. These structures support prefix sums and range queries in O(log n) time, which helps track mismatches or duplicate positions across the string.
What is the time complexity of Minimum Deletions to Make Alternating Substring?
The optimal Fenwick Tree solution runs in O(n log n) time because each update and prefix query costs O(log n). Simpler greedy scans can run in O(n) time when the problem only considers the full string without range operations.

Ready to solve this problem?

Practice Minimum Deletions to Make Alternating Substring with our built-in code editor and test cases.

Practice on FleetCode