VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-window-contains-characters-string/

⇱ Smallest window that contains all characters of string itself - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest window that contains all characters of string itself

Last Updated : 14 Mar, 2026

Given a string str, find the smallest window length that contains all the characters of the given string at least one time.

Examples:

Input: str = "aabcbcdbca"
Output: 4
Explanation: Sub-string -> "dbca"

Input: str = "aaab"
Output: 2
Explanation: Sub-string -> "ab"

[Naive Approach] - Generating All Substrings - O(n ^ 2) Time and O(1) Space

  • Use a count array to identify all the unique characters in the string.
  • Generate substrings using two pointers and track characters using a visited array.
  • Check whether the current substring contains all distinct characters.
  • If it does, update the minimum length of the substring found so far.

Output
4

[Expected Approach] - Using Sliding Window - O(n) Time and O(1) Space

  • Count total distinct characters in the string using a visited array.
  • Use a sliding window with two pointers (start and i) to expand the window and include characters.
  • Track character frequencies in the window using cur[] and update cnt when a new distinct character appears.
  • When the window contains all distinct characters, shrink it from the left and update the minimum window length.


👁 Smallest-window-that-contains-all-characters-of-string-itself



Output
4

Related Article:

Comment