BackhardSliding WindowGoogle

Minimum Alarm Window Solution

Problem Statement

Given a string of event codes events and an array of alarm codes alarms, find the shortest continuous segment of events that contains all alarm codes in alarms. Return the length of the segment if found, otherwise return -1.

Example 1
Input
events = "abcabc", alarms = ['a', 'b']
Output
3

Explanation: Step-by-step: We start from index 0 and find the shortest continuous segment 'abc' that contains both 'a' and 'b'. The length of this segment is 3.

Example 2
Input
events = "abcabc", alarms = ['a', 'c']
Output
6

Explanation: Step-by-step: We start from index 0 and find the shortest continuous segment 'abcabc' that contains both 'a' and 'c'. The length of this segment is 6.

Constraints

  • 1 <= s.length, t.length <= 10^5
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Minimum Alarm Window — Problem Statement & Solution Guide

Sliding WindowHardSliding Window / Hash Map
TimeO(n)
|
SpaceO(1)

Problem Description

Given a string of event codes events and an array of alarm codes alarms, find the shortest continuous segment of events that contains all alarm codes in alarms. Return the length of the segment if found, otherwise return -1.

Examples

Example 1

Input

events = "abcabc", alarms = ['a', 'b']

Output

3

Explanation: Step-by-step: We start from index 0 and find the shortest continuous segment 'abc' that contains both 'a' and 'b'. The length of this segment is 3.

Example 2

Input

events = "abcabc", alarms = ['a', 'c']

Output

6

Explanation: Step-by-step: We start from index 0 and find the shortest continuous segment 'abcabc' that contains both 'a' and 'c'. The length of this segment is 6.

Constraints

  • 1 <= s.length, t.length <= 10^5

Optimal Approach & Strategy

Two HashMaps/arrays. One for required chars, one for current window. Expand right. When window has all chars of t, shrink left to minimize. Keep track of smallest window. Time O(N), Space O(1) (256 ASCII chars).

Brute Force Approach

Check every substring of s. Time O(N^3).

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.