#3639

Minimum Time to Activate String

Medium
ArrayBinary SearchBinary SearchDynamic Programming
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)

This approach uses binary search on time t and calculates valid substrings efficiently by counting non-'*' segments. It reduces unnecessary computations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use binary search to find the minimum time t where valid substrings >= k.
  2. 2Step 2: For each mid in binary search, mark the first mid+1 positions in order as '*'.
  3. 3Step 3: Count valid substrings by subtracting the count of non-'*' segments from total substrings.
solution.py24 lines
1def minTimeToActivate(s, order, k):
2    n = len(s)
3    def count_valid(mid):
4        modified = [''] * n
5        for i in range(mid + 1):
6            modified[order[i]] = '*'
7        count = 0
8        length = 0
9        for char in modified:
10            if char == '*':
11                count += (length * (length + 1)) // 2
12                length = 0
13            else:
14                length += 1
15        count += (length * (length + 1)) // 2
16        return (n * (n + 1)) // 2 - count
17    left, right = 0, n - 1
18    while left <= right:
19        mid = (left + right) // 2
20        if count_valid(mid) >= k:
21            right = mid - 1
22        else:
23            left = mid + 1
24    return left if left < n else -1

Complexity note: Binary search reduces the number of checks to O(log n), while counting valid substrings takes O(n).

  • 1The number of valid substrings increases as more '*' are added.
  • 2Binary search efficiently narrows down the time needed to activate the string.

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