1898. Maximum Number of Removable Characters - Explanation

Problem Link



1. Brute Force

class Solution:
    def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:
        n, m = len(s), len(p)
        marked = set()
        res = 0

        for removeIdx in removable:
            marked.add(removeIdx)

            sIdx = pIdx = 0
            while pIdx < m and sIdx < n:
                if sIdx not in marked and s[sIdx] == p[pIdx]:
                    pIdx += 1
                sIdx += 1
            if pIdx != m:
                break
            res += 1

        return res

Time & Space Complexity

  • Time complexity: O(k(n+m))O(k * (n + m))
  • Space complexity: O(k)O(k)

Where nn and mm are the lengths of the given strings ss and pp respectively. kk is the size of the array removableremovable.


2. Binary Search + Hash Set

class Solution:
    def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:
        def isSubseq(s, subseq, removed):
            i1 = i2 = 0
            while i1 < len(s) and i2 < len(subseq):
                if i1 in removed or s[i1] != subseq[i2]:
                    i1 += 1
                    continue
                i1 += 1
                i2 += 1
            return i2 == len(subseq)

        res = 0
        l, r = 0, len(removable) - 1
        while l <= r:
            m = (l + r) // 2
            removed = set(removable[:m + 1])
            if isSubseq(s, p, removed):
                res = max(res, m + 1)
                l = m + 1
            else:
                r = m - 1

        return res

Time & Space Complexity

  • Time complexity: O((n+m)logk)O((n + m) * \log k)
  • Space complexity: O(k)O(k)

Where nn and mm are the lengths of the given strings ss and pp respectively. kk is the size of the array removableremovable.


class Solution:
    def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:
        l, r = 0, len(removable)
        n, m = len(s), len(p)

        def isSubseq(tmpS):
            i1 = i2 = 0
            while i1 < n and i2 < m:
                if tmpS[i1] == p[i2]:
                    i2 += 1
                i1 += 1
            return i2 == m

        while l < r:
            mid = l + (r - l) // 2
            tmpS = list(s)

            for i in range(mid + 1):
                tmpS[removable[i]] = '#'

            if isSubseq(tmpS):
                l = mid + 1
            else:
                r = mid

        return l

Time & Space Complexity

  • Time complexity: O((n+m)logk)O((n + m) * \log k)
  • Space complexity: O(n)O(n)

Where nn and mm are the lengths of the given strings ss and pp respectively. kk is the size of the array removableremovable.