Minimum Alarm Window — Problem Statement & Solution Guide

Sliding WindowHardSliding Window / Hash Map
TimeO(N)
|
SpaceO(K)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Sliding Window and solve the Minimum Alarm Window problem optimally.

TopicSliding Window
PatternSliding Window / Hash Map
TimeO(N)
SpaceO(K)

Problem Description

Given a string events composed of uppercase alphabetic characters and an array alarms containing one or more uppercase characters (characters may repeat), determine the length of the smallest contiguous substring of events that includes every character from alarms with at least the same multiplicity. If no such substring exists, return -1. The algorithm must run in linear time relative to the length of events.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimum Alarm Window"

hard

WHY DOES IT MATTER?

The sliding‑window pattern turns a combinatorial search over O(N^2) substrings into a linear scan, which is essential for any service that must process massive streams (logs, DNA sequences, network packets) under strict latency constraints.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that you only need to track *how many* required characters are satisfied, not re‑count the whole window each time. Maintaining a ‘formed’ counter and updating it incrementally when the left or right pointer moves reduces both time and auxiliary space to O(1) per operation.

REAL-WORLD CONNECTION

Think of a security camera that continuously records footage; you need the shortest clip that contains all required faces. Instead of reviewing every possible clip, you slide a window over the timeline, expanding until all faces appear, then contract to trim excess—mirroring the algorithm’s expansion‑contraction cycle.

During an interview, write the frequency maps first, then implement the two‑pointer loop; keep the invariant that the window is valid only when formed == requiredUniqueCount. This makes it easy to debug and guarantees you don’t miss the shrink step.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(K)

Core Theory — Why This Approach?

The problem is a classic instance of the Minimum Window Substring, a sliding‑window pattern where we must find the shortest contiguous segment of a source string that satisfies a multiset requirement. A naive solution would enumerate every possible substring (O(N^2)) and count characters each time, which quickly becomes infeasible for strings of length 10^5 or more because the repeated counting leads to quadratic time. The optimal paradigm maintains two pointers defining a dynamic window and a frequency map of required characters; as the right pointer expands, we update a “have” counter, and when the window satisfies all requirements we try to contract from the left to shrink it while still meeting the constraints. This two‑pointer technique guarantees each character is visited at most twice, yielding linear time overall.

The sliding‑window works because the requirement set (the alarms array) is monotonic: adding more characters to the right can only increase the chance of satisfying the multiset, never invalidate a previously satisfied window. Conversely, moving the left edge can only reduce the window size and possibly break the requirement, prompting a re‑expansion. By keeping exact counts of needed versus current characters, we can decide in O(1) whether the window is valid, enabling the greedy shrink step that produces the minimal length.

The key to linearity is the use of a hashmap (or fixed‑size array for uppercase letters) to store required frequencies and a separate hashmap for the current window frequencies. Each character is processed in constant time for both insertion and removal, and the “formed” counter tracks how many distinct required characters meet their quota, avoiding a full scan of the hashmap on each iteration.

Interview Questions on This Problem

Q1How would you adapt the Minimum Alarm Window solution if the events string could contain Unicode characters beyond uppercase A‑Z?

Replace the fixed‑size 26‑element array with a hash map (e.g., unordered_map<char,int>) for both required and window counts; the rest of the sliding‑window logic stays identical, still O(N) time because each character lookup remains O(1) on average.

Q2In a fintech system, you need to monitor a real‑time stream of transaction codes and trigger an alert when a specific combination appears in order. How does the Minimum Alarm Window algorithm help, and what modification is needed for ordered requirements?

The algorithm efficiently finds the smallest segment containing all required codes regardless of order, which is useful for unordered alert conditions. For ordered alerts, you would switch to a two‑pointer approach that also tracks the next expected character index, essentially turning the problem into a subsequence match rather than a multiset window.

Q3A startup wants to parallelize the minimum window search across multiple shards of a massive log file. What challenges arise, and can the sliding‑window technique be distributed?

Sliding‑window is inherently sequential because the optimal window may span shard boundaries; you must overlap shards by the length of the largest possible window (or by the total required characters) and then merge results. The core O(N) algorithm runs on each overlapped segment, and a final reduction picks the global minimum.

Examples

Example 1

Input

events = "ABDCAB", alarms = ["A","B","C"]

Output

3

Explanation: All required characters are A, B, C each once. Scanning the string, the window "CAB" (positions 4‑6) contains A, B, C and its length is 3, which is the minimum possible.

Example 2

Input

events = "XYZXYZ", alarms = ["X","Y","Z","X"]

Output

4

Explanation: Alarms require two X's, one Y and one Z. The shortest window satisfying this is "XYZX" (positions 1‑4) with length 4. No shorter window can hold two X's together with Y and Z.

Example 3

Input

events = "AAAA", alarms = ["B"]

Output

-1

Explanation: The required character B never appears in the events string, therefore no valid window exists and the answer is -1.

Constraints

  • 1 <= events.length <= 100000
  • 1 <= alarms.length <= 100000
  • events consists only of uppercase English letters
  • alarms consists only of uppercase English letters

Optimal Approach & Strategy

Use a two‑pointer sliding window with frequency maps to expand until the window meets the requirement, then contract from the left to shrink while still valid – O(N) time.

Brute Force Approach

Generate every possible substring, count alarm characters inside each, and keep the minimum length that satisfies the multiplicities – O(N^2) time.

Code Solutions

JavaScript Solution
Time: O(N)
const fs = require('fs');
const input = fs.readFileSync(0,'utf8').trim().split(/\s+/);
let idx=0;
const events = input[idx++];
const m = parseInt(input[idx++]);
const alarms = [];
for(let i=0;i<m;i++) alarms.push(input[idx++]);
function minAlarmWindow(events, alarms){
    if(alarms.length===0) return 0;
    const need = new Map();
    for(const ch of alarms){
        need.set(ch,(need.get(ch)||0)+1);
    }
    const required = need.size;
    const window = new Map();
    let formed=0, l=0, ans=Infinity;
    for(let r=0;r<events.length;r++){
        const c=events[r];
        window.set(c,(window.get(c)||0)+1);
        if(need.has(c) && window.get(c)===need.get(c)) formed++;
        while(l<=r && formed===required){
            if(r-l+1<ans) ans=r-l+1;
            const cl=events[l];
            window.set(cl,window.get(cl)-1);
            if(need.has(cl) && window.get(cl)<need.get(cl)) formed--;
            l++;
        }
    }
    return ans===Infinity?-1:ans;
}
console.log(minAlarmWindow(events,alarms).toString());

Asked in Top Tech Interviews

Google

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.