#3777

Minimum Deletions to Make Alternating Substring

Hard
StringSegment TreeFenwick TreeSegment Tree
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Use a Fenwick tree to efficiently track and update adjacent duplicates, allowing quick calculations for deletions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array eq where eq[i] = 1 if s[i] == s[i-1], else 0.
  2. 2Step 2: Use a Fenwick tree to maintain prefix sums of eq for quick range queries.
  3. 3Step 3: For a query of type [2, l, r], return the sum of eq from l to r.
solution.py36 lines
1class FenwickTree:
2    def __init__(self, size):
3        self.size = size
4        self.tree = [0] * (size + 1)
5    def update(self, index, delta):
6        while index <= self.size:
7            self.tree[index] += delta
8            index += index & -index
9    def query(self, index):
10        total = 0
11        while index > 0:
12            total += self.tree[index]
13            index -= index & -index
14        return total
15
16def min_deletions_optimal(s, queries):
17    n = len(s)
18    eq = [0] * n
19    for i in range(1, n):
20        eq[i] = 1 if s[i] == s[i - 1] else 0
21    fenwick = FenwickTree(n)
22    for i in range(1, n):
23        fenwick.update(i, eq[i])
24    results = []
25    for query in queries:
26        if query[0] == 1:
27            idx = query[1]
28            s = s[:idx] + ('B' if s[idx] == 'A' else 'A') + s[idx + 1:]
29            if idx > 0:
30                fenwick.update(idx, 1 if s[idx] == s[idx - 1] else -1)
31            if idx < n - 1:
32                fenwick.update(idx + 1, 1 if s[idx + 1] == s[idx] else -1)
33        else:
34            l, r = query[1], query[2]
35            results.append(fenwick.query(r) - fenwick.query(l))
36    return results

Complexity note: Fenwick tree allows efficient updates and queries, making it optimal for this problem.

  • 1Use data structures like Fenwick trees for efficient range queries.
  • 2Flipping characters can be managed with careful updates to auxiliary structures.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.