LeetCode #3639 — MEDIUM

Minimum Time to Activate String

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given a string s of length n and an integer array order, where order is a permutation of the numbers in the range [0, n - 1].

Starting from time t = 0, replace the character at index order[t] in s with '*' at each time step.

A substring is valid if it contains at least one '*'.

A string is active if the total number of valid substrings is greater than or equal to k.

Return the minimum time t at which the string s becomes active. If it is impossible, return -1.

Example 1:

Input: s = "abc", order = [1,0,2], k = 2

Output: 0

Explanation:

t order[t] Modified s Valid Substrings Count Active
(Count >= k)
0 1 "a*c" "*", "a*", "*c", "a*c" 4 Yes

The string s becomes active at t = 0. Thus, the answer is 0.

Example 2:

Input: s = "cat", order = [0,2,1], k = 6

Output: 2

Explanation:

t order[t] Modified s Valid Substrings Count Active
(Count >= k)
0 0 "*at" "*", "*a", "*at" 3 No
1 2 "*a*" "*", "*a", "*a*", "a*", "*" 5 No
2 1 "***" All substrings (contain '*') 6 Yes

The string s becomes active at t = 2. Thus, the answer is 2.

Example 3:

Input: s = "xy", order = [0,1], k = 4

Output: -1

Explanation:

Even after all replacements, it is impossible to obtain k = 4 valid substrings. Thus, the answer is -1.

Constraints:

  • 1 <= n == s.length <= 105
  • order.length == n
  • 0 <= order[i] <= n - 1
  • s consists of lowercase English letters.
  • order is a permutation of integers from 0 to n - 1.
  • 1 <= k <= 109
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a string s of length n and an integer array order, where order is a permutation of the numbers in the range [0, n - 1]. Starting from time t = 0, replace the character at index order[t] in s with '*' at each time step. A substring is valid if it contains at least one '*'. A string is active if the total number of valid substrings is greater than or equal to k. Return the minimum time t at which the string s becomes active. If it is impossible, return -1.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Binary Search

Example 1

"abc"
[1,0,2]
2

Example 2

"cat"
[0,2,1]
6

Example 3

"xy"
[0,1]
4
Step 02

Core Insight

What unlocks the optimal approach

  • Binary-search on <code>t</code> and for each <code>t</code> mark the first <code>t+1</code> positions in <code>order</code> as <code>*</code>, then in one pass subtract from <code>n(n+1)/2</code> the substrings of each non-<code>*</code> run of length <code>L</code> (<code>L(L+1)/2</code>) and check if the remainder >= <code>k</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3639: Minimum Time to Activate String
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3639: Minimum Time to Activate String
// package main
// 
// import "sort"
// 
// // https://space.bilibili.com/206214
// func minTime1(s string, order []int, k int) int {
// 	n := len(s)
// 	if n*(n+1)/2 < k { // 全改成星号也无法满足要求
// 		return -1
// 	}
// 
// 	star := make([]int, n) // 避免在二分内部反复创建/初始化列表
// 	ans := sort.Search(n-1, func(m int) bool {
// 		m++
// 		for _, j := range order[:m] {
// 			star[j] = m
// 		}
// 		cnt := 0
// 		last := -1 // 上一个 '*' 的位置
// 		for i, x := range star {
// 			if x == m { // s[i] 是 '*'
// 				last = i
// 			}
// 			cnt += last + 1
// 			if cnt >= k { // 提前退出循环
// 				return true
// 			}
// 		}
// 		return false
// 	})
// 	return ans
// }
// 
// func minTime(s string, order []int, k int) int {
// 	n := len(s)
// 	cnt := n * (n + 1) / 2
// 	if cnt < k { // 全改成星号也无法满足要求
// 		return -1
// 	}
// 
// 	// 数组模拟双向链表
// 	prev := make([]int, n+1)
// 	next := make([]int, n)
// 	for i := range n {
// 		prev[i] = i - 1
// 		next[i] = i + 1
// 	}
// 
// 	for t := n - 1; ; t-- {
// 		i := order[t]
// 		l, r := prev[i], next[i]
// 		cnt -= (i - l) * (r - i)
// 		if cnt < k {
// 			return t
// 		}
// 		// 删除链表中的 i
// 		if l >= 0 {
// 			next[l] = r
// 		}
// 		prev[r] = l
// 	}
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Boundary update without `+1` / `-1`

Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.

Usually fails on: Two-element ranges never converge.

Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.