The Wayback Machine - https://web.archive.org/web/20241005235842/https://www.geeksforgeeks.org/smallest-window-contains-characters-string/
Open In App

Smallest window that contains all characters of string itself

Last Updated : 03 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
  • Given a string, find the smallest window length with all distinct characters of the given string. For eg. str = “aabcbcdbca”, then the result would be 4 as of the smallest window will be “dbca” .

Examples: 

Input: aabcbcdbca
Output: dbca
Explanation:
Possible substrings= {aabcbcd, abcbcd,
bcdbca, dbca....}
Of the set of possible substrings 'dbca'
is the shortest substring having all the
distinct characters of given string.

Input: aaab
Output: ab
Explanation:
Possible substrings={aaab, aab, ab}
Of the set of possible substrings 'ab'
is the shortest substring having all
the distinct characters of given string.

Solution: Above problem states that we have to find the smallest window that contains all the distinct characters of the given string even if the smallest string contains repeating elements. 
For example, in “aabcbcdb”, the smallest string that contains all the characters is “abcbcd”.

Method 1: This is the Brute Force method of solving the problem using HashMap.

Approach : For solving the problem we first have to find out all the distinct characters present in the string. This can be done using a HashMap. The next thing is to generate all the possible substrings. This follows by checking whether a substring generated has all the required characters(stored in the hash_map) or not. If yes, then compare its length with the minimum substring length which follows the above constraints, found till now.
HashMap: HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles. 

Algorithm : 

  1. Store all distinct characters of the given string in a hash_map.
  2. Take a variable count and initialize it with value 0.
  3. Generate the substrings using two pointers.
  4. Now check whether generated substring is valid or not-: 
    1. As soon we find that the character of the substring generated has not been encountered before, increment count by 1.
    2. We can use a visited array of max_chars size to find whether the current character has been encountered before or not.
    3. If count is equal to equal to size of hash_map the substring generated is valid
    4. If it is a valid substring, compare it with the minimum length substring already generated.

Pseudo Code:

maphash_map;
for ( i=0 to str.length())
hash_map[str[i]]++;//finding all distinct characters of string
minimum_size=INT_MAX
Distinct_chars=hash_map.size()
for(i=0 to str.length())
count=0;
sub_str="";
visited[256]={0};
for(j=i to n)
sub_str+=str[j]
if(visited[str[j]]==0)
count++
visited[str[j]]=1;
if(count==Distinct_chars)
end loop

if(sub_str.length()<minimum_size&&
count==Distinct_chars)
ans=sub_str;

return ans

Implementation:

CPP
// C++ program to find the smallest
// window containing all characters
// of a pattern.
#include <bits/stdc++.h>
using namespace std;

const int MAX_CHARS = 256;

// Function to find smallest window containing
// all distinct characters
string findSubString(string str)
{
    int n = str.length();

    // Count all distinct characters.
    int dist_count = 0;
    unordered_map<int, int> hash_map;
    for (int i = 0; i < n; i++) {
        hash_map[str[i]]++;
    }

    dist_count = hash_map.size();
    int size = INT_MAX;
    string res;
    // Now follow the algorithm discussed in below
    for (int i = 0; i < n; i++) {
        int count = 0;
        int visited[256] = { 0 };
        string sub_str = "";
        for (int j = i; j < n; j++) {
            if (visited[str[j]] == 0) {
                count++;
                visited[str[j]] = 1;
            }
            sub_str += str[j];
            if (count == dist_count)
                break;
        }
        if (sub_str.length() < size && count == dist_count)
        {
            res = sub_str;
            size=res.length();
        }
    }
    return res;
}

// Driver Code
int main()
{
    string str = "aabcbcdbca";
    cout << "Smallest window containing all distinct"
            " characters is: "
         << findSubString(str);
    return 0;
}
Java
import java.io.*;
import java.util.*;

// Java program to find the smallest
// window containing all characters
// of a pattern.
class GFG 
{
  
    // Function to find smallest window containing
    // all distinct characters
    public static String findSubString(String str)
    {
        int n = str.length();
      
        // Count all distinct characters.
        int dist_count = 0;
        HashMap<Character, Integer> mp = new HashMap<>();
        for (int i = 0; i < n; i++) 
        {
            if (mp.containsKey(str.charAt(i))) 
            {
                Integer a = mp.get(str.charAt(i));
                mp.put(str.charAt(i),a+1);                   
            }
          else
          {
                 mp.put(str.charAt(i), 1);
            }
        }
        dist_count = mp.size();
        int size = Integer.MAX_VALUE;
        String res = "";
      
        // Now follow the algorithm discussed in below
        for (int i = 0; i < n; i++)
        {
            int count = 0;
            int visited[] = new int[256];
            for(int j = 0; j < 256; j++)
              visited[j] = 0;
            String sub_str = "";
            for (int j = i; j < n; j++)
            {
                if (visited[str.charAt(j)] == 0) 
                {
                    count++;
                    visited[str.charAt(j)] = 1;
                }
                sub_str += str.charAt(j);
                if (count == dist_count)
                    break;
            }
            if (sub_str.length() < size && count == dist_count)
            {
                res = sub_str;
                size=res.length();
            }
        }
        return res;
    }
  
  // Driver code
    public static void main (String[] args)
    {
        String str = "aabcbcdbca";
        System.out.println("Smallest window containing all distinct"+
                " characters is: "+ findSubString(str)) ;
    }
}

// This code is contributed by Manu Pathria
Python
# Python3 code for the same approach
import sys

MAX_CHARS = 256

# Function to find smallest window containing
# all distinct characters
def findSubString(str):

   n = len(str)

   # Count all distinct characters.
   dist_count = 0
   hash_map = {}
   for i in range(n):
      if(str[i] in hash_map):

         hash_map[str[i]] = hash_map[str[i]] + 1

      else:

         hash_map[str[i]] = 1

   dist_count = len(hash_map)
   size = sys.maxsize
   res = 0

    # Now follow the algorithm discussed in below
   for i in range(n):
      count = 0
      visited= [0]*(MAX_CHARS)
      sub_str = ""
      for j in range(i,n):
         if (visited[ord(str[j])] == 0):
            count += 1
            visited[ord(str[j])] = 1

         sub_str += str[j]
         if (count == dist_count):
            break
      if (len(sub_str) < size and count == dist_count):
         res = sub_str
         size = len(res)
   return res

# Driver Code
str = "aabcbcdbca"
print(f"Smallest window containing all distinct characters is: {findSubString(str)}")

# This code is contributed by shinjanpatra.
C#
// Include namespace system
using System;
using System.Collections.Generic;

using System.Collections;

// C# program to find the smallest
// window containing all characters
// of a pattern.
public class GFG
{
  
    // Function to find smallest window containing
    // all distinct characters
    public static String findSubString(String str)
    {
        var n = str.Length;
      
        // Count all distinct characters.
        var dist_count = 0;
        var mp = new Dictionary<char, int>();
        for (int i = 0; i < n; i++)
        {
            if (mp.ContainsKey(str[i]))
            {
                var a = mp[str[i]];
                mp[str[i]] = a + 1;
            }
            else 
            {
                mp[str[i]] = 1;
            }
        }
        dist_count = mp.Count;
        var size = int.MaxValue;
        var res = "";
      
        // Now follow the algorithm discussed in below
        for (int i = 0; i < n; i++)
        {
            var count = 0;
            int[] visited = new int[256];
            for (int j = 0; j < 256; j++)
            {
                visited[j] = 0;
            }
            var sub_str = "";
            for (int j = i; j < n; j++)
            {
                if (visited[str[j]] == 0)
                {
                    count++;
                    visited[str[j]] = 1;
                }
                sub_str += str[j];
                if (count == dist_count)
                {
                    break;
                }
            }
            if (sub_str.Length < size && count == dist_count)
            {
                res = sub_str;
                size = res.Length;
            }
        }
        return res;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        var str = "aabcbcdbca";
        Console.WriteLine("Smallest window containing all distinct" + " characters is: " + GFG.findSubString(str));
    }
}

// This code is contributed by mukulsomukesh.
JavaScript
<script>

// JavaScript program to find the smallest
// window containing all characters
// of a pattern.
const MAX_CHARS = 256;

// Function to find smallest window containing
// all distinct characters
function findSubString(str)
{
    let n = str.length;

    // Count all distinct characters.
    let dist_count = 0;
    let hash_map = new Map();
    for (let i = 0; i < n; i++) {
        if(hash_map.has(str[i])){
            hash_map.set(str[i],hash_map.get(str[i])+1);
        }
        else hash_map.set(str[i],1);
    }

    dist_count = hash_map.size;
    let size = Number.MAX_VALUE;
    let res;
    // Now follow the algorithm discussed in below
    for (let i = 0; i < n; i++) {
        let count = 0;
        let visited= new Array(MAX_CHARS).fill(0);
        let sub_str = "";
        for (let j = i; j < n; j++) {
            if (visited[str.charCodeAt(j)] == 0) {
                count++;
                visited[str.charCodeAt(j)] = 1;
            }
            sub_str += str[j];
            if (count == dist_count)
                break;
        }
        if (sub_str.length < size && count == dist_count)
        {
            res = sub_str;
            size = res.length;
        }
    }
    return res;
}

// Driver Code
let str = "aabcbcdbca";
document.write("Smallest window containing all distinct characters is: " + findSubString(str),"</br>");

// This code is contributed by shinjanpatra.
</script>

Output
Smallest window containing all distinct characters is: dbca

Complexity Analysis: 

  • Time Complexity: O(N^2). 
    This time is required to generate all possible sub-strings of a string of length “N”.
  • Space Complexity: O(N). 
    As a hash_map has been used of size N.

Method 2: Here we have used Sliding Window technique to arrive at the solution. This technique shows how a nested for loop in few problems can be converted to single for loop and hence reducing the time complexity.

Approach: Basically a window of characters is maintained by using two pointers namely start and end. These start and end pointers can be used to shrink and increase the size of window respectively. Whenever the window contains all characters of given string, the window is shrinked from left side to remove extra characters and then its length is compared with the smallest window found so far. 
If in the present window, no more characters can be deleted then we start increasing the size of the window using the end until all the distinct characters present in the string are also there in the window. Finally, find the minimum size of each window.

Algorithm : 

  1. Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string).
  2. Take two pointers start and end which will mark the start and end of window.
  3. Take a counter=0 which will be used to count distinct characters in the window.
  4. Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1.
  5. If the counter is equal to total number of distinct characters, Try to shrink the window.
  6. For shrinking the window -: 
    1. If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.
    2. Now compare the length of present window with the minimum window length.

Implementation:

C++
// C++ program to find the smallest
// window containing all characters
// of a pattern.
#include <bits/stdc++.h>
using namespace std;

const int MAX_CHARS = 256;

// Function to find smallest window containing
// all distinct characters
string findSubString(string str)
{
    int n = str.length();

    // if string is empty or having one char
    if (n <= 1)
        return str;

    // Count all distinct characters.
    int dist_count = 0;
    bool visited[MAX_CHARS] = { false };
    for (int i = 0; i < n; i++) {
        if (visited[str[i]] == false) {
            visited[str[i]] = true;
            dist_count++;
        }
    }

    // Now follow the algorithm discussed in below
    // post. We basically maintain a window of characters
    // that contains all characters of given string.
    int start = 0, start_index = -1, min_len = INT_MAX;

    int count = 0;
    int curr_count[MAX_CHARS] = { 0 };
    for (int j = 0; j < n; j++) {
        // Count occurrence of characters of string
        curr_count[str[j]]++;

        // If any distinct character matched,
        // then increment count
        if (curr_count[str[j]] == 1)
            count++;

        // if all the characters are matched
        if (count == dist_count) {
            // Try to minimize the window i.e., check if
            // any character is occurring more no. of times
            // than its occurrence in pattern, if yes
            // then remove it from starting and also remove
            // the useless characters.
            while (curr_count[str[start]] > 1) {
                if (curr_count[str[start]] > 1)
                    curr_count[str[start]]--;
                start++;
            }

            // Update window size
            int len_window = j - start + 1;
            if (min_len > len_window) {
                min_len = len_window;
                start_index = start;
            }
        }
    }

    // Return substring starting from start_index
    // and length min_len
    return str.substr(start_index, min_len);
}

// Driver code
int main()
{
    string str = "aabcbcdbca";
    cout << "Smallest window containing all distinct"
            " characters is: "
         << findSubString(str);
    return 0;
}
Java
// Java program to find the smallest window containing
// all characters of a pattern.
import java.util.Arrays;
public class GFG {

    static final int MAX_CHARS = 256;

    // Function to find smallest window containing
    // all distinct characters
    static String findSubString(String str)
    {
        int n = str.length();

        // if string is empty or having one char
        if (n <= 1)
            return str;

        // Count all distinct characters.
        int dist_count = 0;

        boolean[] visited = new boolean[MAX_CHARS];
        Arrays.fill(visited, false);
        for (int i = 0; i < n; i++) {
            if (visited[str.charAt(i)] == false) {
                visited[str.charAt(i)] = true;
                dist_count++;
            }
        }

        // Now follow the algorithm discussed in below
        // post. We basically maintain a window of
        // characters that contains all characters of given
        // string.
        int start = 0, start_index = -1;
        int min_len = Integer.MAX_VALUE;

        int count = 0;
        int[] curr_count = new int[MAX_CHARS];
        for (int j = 0; j < n; j++) {
            // Count occurrence of characters of string
            curr_count[str.charAt(j)]++;

            // If any distinct character matched,
            // then increment count
            if (curr_count[str.charAt(j)] == 1)
                count++;

            // if all the characters are matched
            if (count == dist_count) {
                // Try to minimize the window i.e., check if
                // any character is occurring more no. of
                // times than its occurrence in pattern, if
                // yes then remove it from starting and also
                // remove the useless characters.
                while (curr_count[str.charAt(start)] > 1) {
                    if (curr_count[str.charAt(start)] > 1)
                        curr_count[str.charAt(start)]--;
                    start++;
                }

                // Update window size
                int len_window = j - start + 1;
                if (min_len > len_window) {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }
        // Return substring starting from start_index
        // and length min_len
        return str.substring(start_index,
                             start_index + min_len);
    }

    // Driver code
    public static void main(String args[])
    {
        String str = "aabcbcdbca";
        System.out.println(
            "Smallest window containing all distinct"
            + " characters is: " + findSubString(str));
    }
}
// This code is contributed by Sumit Ghosh
Python
# Python program to find the smallest
# window containing
# all characters of a pattern
from collections import defaultdict

MAX_CHARS = 256

# Function to find smallest window
# containing all distinct characters


def findSubString(strr):

    n = len(strr)

    # if string is empty or having one char
    if n <= 1:
        return strr

    # Count all distinct characters.
    dist_count = len(set([x for x in strr]))

    curr_count = defaultdict(lambda: 0)
    count = 0
    start = 0
    min_len = n

    # Now follow the algorithm discussed in below
    # post. We basically maintain a window of characters
    # that contains all characters of given string.
    for j in range(n):
        curr_count[strr[j]] += 1

        # If any distinct character matched,
        # then increment count
        if curr_count[strr[j]] == 1:
            count += 1

        # Try to minimize the window i.e., check if
        # any character is occurring more no. of times
        # than its occurrence in pattern, if yes
        # then remove it from starting and also remove
        # the useless characters.
        if count == dist_count:
            while curr_count[strr[start]] > 1:
                if curr_count[strr[start]] > 1:
                    curr_count[strr[start]] -= 1

                start += 1

            # Update window size
            len_window = j - start + 1

            if min_len > len_window:
                min_len = len_window
                start_index = start

    # Return substring starting from start_index
    # and length min_len """
    return str(strr[start_index: start_index +
                    min_len])


# Driver code
if __name__ == '__main__':

    print("Smallest window containing "
          "all distinct characters is: {}".format(
              findSubString("aabcbcdbca")))

# This code is contributed by
# Subhrajit
C#
// C# program to find the smallest window containing
// all characters of a pattern.
using System;

class GFG {

    static int MAX_CHARS = 256;

    // Function to find smallest window containing
    // all distinct characters
    static string findSubString(string str)
    {
        int n = str.Length;

        // if string is empty or having one char
        if (n <= 1)
            return str;

        // Count all distinct characters.
        int dist_count = 0;
        bool[] visited = new bool[MAX_CHARS];
        for (int i = 0; i < n; i++) {
            if (visited[str[i]] == false) {
                visited[str[i]] = true;
                dist_count++;
            }
        }

        // Now follow the algorithm discussed in below
        // post. We basically maintain a window of
        // characters that contains all characters of given
        // string.
        int start = 0, start_index = -1,
            min_len = int.MaxValue;

        int count = 0;
        int[] curr_count = new int[MAX_CHARS];
        for (int j = 0; j < n; j++) {
            // Count occurrence of characters of string
            curr_count[str[j]]++;

            // If any distinct character matched,
            // then increment count
            if (curr_count[str[j]] == 1)
                count++;

            // if all the characters are matched
            if (count == dist_count) {
                // Try to minimize the window i.e., check if
                // any character is occurring more no. of
                // times than its occurrence in pattern, if
                // yes then remove it from starting and also
                // remove the useless characters.
                while (curr_count[str[start]] > 1) {
                    if (curr_count[str[start]] > 1)
                        curr_count[str[start]]--;
                    start++;
                }

                // Update window size
                int len_window = j - start + 1;
                if (min_len > len_window) {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }

        // Return substring starting from start_index
        // and length min_len
        return str.Substring(start_index, min_len);
    }

    // Driver code
    public static void Main(String[] args)
    {
        string str = "aabcbcdbca";
        Console.WriteLine(
            "Smallest window containing all distinct"
            + " characters is: " + findSubString(str));
    }
}

// This code contributed by Rajput-Ji
JavaScript
<script>

// JavaScript program to find the smallest
// window containing all characters
// of a pattern.
const MAX_CHARS = 256;

// Function to find smallest window containing
// all distinct characters
function findSubString(str)
{
    let n = str.length;

    // if string is empty or having one char
    if (n <= 1)
        return str;

    // Count all distinct characters.
    let dist_count = 0;
    let visited = new Array(MAX_CHARS).fill(false);
    for (let i = 0; i < n; i++) {
        if (visited[str.charCodeAt(i)] == false) {
            visited[str.charCodeAt(i)] = true;
            dist_count++;
        }
    }

    // Now follow the algorithm discussed in below
    // post. We basically maintain a window of characters
    // that contains all characters of given string.
    let start = 0, start_index = -1, min_len = Number.MAX_VALUE;

    let count = 0;
    let curr_count = new Array(MAX_CHARS).fill(0);
    for (let j = 0; j < n; j++) {
        // Count occurrence of characters of string
        curr_count[str.charCodeAt(j)]++;

        // If any distinct character matched,
        // then increment count
        if (curr_count[str.charCodeAt(j)] == 1)
            count++;

        // if all the characters are matched
        if (count == dist_count) {
            // Try to minimize the window i.e., check if
            // any character is occurring more no. of times
            // than its occurrence in pattern, if yes
            // then remove it from starting and also remove
            // the useless characters.
            while (curr_count[str.charCodeAt(start)] > 1) {
                if (curr_count[str.charCodeAt(start)] > 1)
                    curr_count[str.charCodeAt(start)]--;
                start++;
            }

            // Update window size
            let len_window = j - start + 1;
            if (min_len > len_window) {
                min_len = len_window;
                start_index = start;
            }
        }
    }

    // Return substring starting from start_index
    // and length min_len
    return str.substring(start_index, min_len + start_index);
}

// Driver code
let str = "aabcbcdbca";
document.write("Smallest window containing all distinct characters is: " + 
findSubString(str),"</br>");

// This code is contributed by shinjanpatra.
</script>

Output
Smallest window containing all distinct characters is: dbca

Complexity Analysis: 

  • Time Complexity: O(N). 
    As the string is traversed using two pointers only once.
  • Space Complexity: O(1) if we consider character set as constant. We can also say O(MAX_CHARS) 

Related Article: 

  1. Length of the smallest sub-string consisting of maximum distinct characters
  2. https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/



Similar Reads

Smallest window in a String containing all characters of other String
Given two strings S (length m) and P (length n), the task is to find the smallest substring in S that contains all characters of P, including duplicates. If no such substring exists, return "-1". If multiple substrings of the same length are found, return the one with the smallest starting index. Examples: Input: S = "timetopractice", P = "toc"Outp
15+ min read
Minimal moves to form a string by adding characters or appending string itself
Given a string S, we need to write a program to check if it is possible to construct the given string S by performing any of the below operations any number of times. In each step, we can: Add any character at the end of the string.or, append the string to the string itself.The above steps can be applied any number of times. We need to write a prog
8 min read
Count nodes having smallest value in the path from root to itself in a Binary Tree
Given a Binary Tree, the task is to count the number of nodes in the given Binary Tree such that the path from the root to that node contains node with value greater than or equal to that node. Examples: Input: 6 / \ 7 4 / \ / \ 3 7 1 2 Output: 5 Explanation: Root node 6 is considered as its the only node in the path from root to itself. Node 4 has
8 min read
Check if String can be generated by concatenating character or String itself
Given a target string S consisting of lowercase alphabets, the task is to make this string by performing some operation on an empty string such that: The first operation is to append a lower case alphabet to string S and The second operation is to append a copy of S to itself. Note: The first operation cannot be used continuously two times. Example
6 min read
Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = "abcdefababaef", B = "abf"Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = "abcdefababaef", B = "aef"Output: 3 Recommended: Please solve it on "PRACT
12 min read
Find length of smallest substring of a given string which contains another string as subsequence
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. If there are multiple such substrings in A, return the substring that has the smallest starting index. Examples : Input : A = "abcedbaced" B = "bed"Output : "bced"Explanation : The substring A[2 : 5] is the shortest substring that contains the stri
15 min read
Python program to check if a string contains all unique characters
To implement an algorithm to determine if a string contains all unique characters. Examples: Input : s = "abcd" Output: True "abcd" doesn't contain any duplicates. Hence the output is True. Input : s = "abbd" Output: False "abbd" contains duplicates. Hence the output is False. One solution is to create an array of boolean values, where the flag at
3 min read
String matching where one string contains wildcard characters
Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. * --> Matches with 0 or more instances of any character or set of characters. ? --> Matches with any one charac
9 min read
Sum of GCD of all numbers upto N with N itself
Given an integer N, the task is to find the sum of Greatest Common Divisors of all numbers up to N with N itself.Examples: Input: N = 12 Output: 40 Explanation: GCD of [1, 12] = 1, [2, 12] = 2, [3, 12] = 3, [4, 12] = 4, [5, 12] = 1, [6, 12] = 6, [7, 12] = 1, [8, 12] = 4, [9, 12] = 3, [10, 12] = 2, [11, 12] = 1, [12, 12] = 12. The sum is (1 + 2 + 3
9 min read
Print all permutations of a number N greater than itself
Given a number N, our task is to print those permutations of integer N which are greater than N.Examples: Input: N = 534 Output: 543Input: N = 324 Output: 342, 423, 432 Approach: To solve this problem, we can obtain all the lexicographically larger permutations of N using next_permutation() method in C++. After getting all such numbers, print them.
6 min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Encode given string by replacing substrings with prefix same as itself with *
Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are replaced by a *. Generate the encrypted string. Note: If the string can be encrypted in multiple ways, find the smallest encrypted string. Examples: Input: str = "ababcababcd"Output: ab*c*
9 min read
Minimum window size containing atleast P primes in every window of given range
Given three integers X, Y and P, the task is to find the minimum window size K such that every window in the range [X, Y] of this size have atleast P prime numbers.Examples: Input: X = 2, Y = 8, P = 2 Output: 4 Explanation: In the range [2, 8], window size of 4 contains atleast 2 primes in each window. Possible Windows - {2, 3, 4, 5} - No of Primes
15+ min read
Maximum possible sum of a window in an array such that elements of same window in other array are unique
Given two arrays A and B of equal number of elements. The task is to find the maximum sum possible of a window in array B such that elements of same window in A[] are unique. Examples: Input: A = [0, 1, 2, 3, 0, 1, 4] B = [9, 8, 1, 2, 3, 4, 5] Output: sum = 20 The maximum sum possible in B[] such that all corresponding elements in A[] are unique is
10 min read
Find smallest subarray that contains all elements in same order
Given two arrays of integers of size m and n. The task is to find the minimum length subarray in the first array that contains all the elements of second array. Note: element of second array may be present in the large array in non-contiguous but order must same. ( m < n ) Examples : Input : A[] = {2, 2, 4, 5, 8, 9} B[] = {2, 5, 9} Output : 5 Sm
14 min read
Length of the smallest substring which contains all vowels
Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1. Example: Input: str = "babeivoucu" Output: 7 Explanation: Smallest substring which contains each vowel atleast once is "abeivou" of length 7. Input: str = "
15+ min read
Maximize count of non overlapping substrings which contains all occurrences of its characters
Given string str consisting of lowercase letters, the task is to find the maximum number of non-overlapping substrings such that each substring contains all occurrences of its characters from the entire string. If multiple solutions with the same number of substrings exist, then print the one with the minimum total length. Examples: Input: str = "a
12 min read
Smallest string containing all unique characters from given array of strings
Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are used across all the strings of the given array. Inp
9 min read
Find smallest string with whose characters all given Strings can be generated
Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the string which contains
5 min read
Lexicographically smallest String using all of the first K letters of alphabet and no two adjacent characters are same
Given two integers N and K, the task is to form a string of size N using the first K characters of the alphabet following the given conditions: No two adjacent characters of the string are the same.All of the K characters are present at least once in the string. If no such string is possible, print -1. Examples: Input: N = 3, K = 2Output: "aba"Expl
7 min read
Swap all occurrences of two characters to get lexicographically smallest string
Given string str of lower case English alphabets. One can choose any two characters in the string and replace all the occurrences of the first character with the second character and replace all the occurrences of the second character with the first character. Find the lexicographically smallest string that can be obtained by doing this operation a
9 min read
Minimum Cost of deletions such that string does not contains same consecutive characters
Content Removed
1 min read
Check if a String contains any index with more than K active characters
Given a string S, containing lowercase English alphabets, and an integer K, the task is to find any index of the string which consists of more than K active characters. If found, print Yes. Otherwise, print No. Count of active characters for any index is the number of characters having previous occurrences before or at the current index and last oc
6 min read
Lexicographically smallest string formed by appending a character from the first K characters of a given string
Given a string S consisting of lowercase alphabets. The task is to find the lexicographically smallest string X of the same length only that can be formed using the operation given below: In a single operation, select any one character among the at most first K characters of string S, remove it from string S and append it to string X. Apply this op
7 min read
Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
Given a string str consisting of lowercase alphabets and an integer K, you can perform the following operations on str Initialize an empty string X = "".Take any character from the first K characters of str and append it to X.Remove the chosen character from str.Repeat the above steps while there are characters left in str. The task is to generate
6 min read
Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Modify string by replacing all occurrences of given characters by specified replacing characters
Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[][2], the task is to modify the given string S by replacing all occurrences of character P[i][0] with character P[i][1]. Examples: Input: S = "aabbgg", P[][2] = {{a, b}, {b, g}, {g, a}}Output: bbggaaExplanation:Replace 'a' by 'b' in the original string. Now t
12 min read
Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings
Given a binary string S, and two integers A, which denotes the cost of reversing a substring, and B, which denotes the cost of flipping all characters of a substring, the task is to find the minimum cost to reduce the string S to 1s only. Examples: Input: S = "01100", A = 1, B = 5Output: 6Explanation: One possible way to make all characters equal t
8 min read
Minimum characters to be replaced in given String to make all characters same
Given a string str of size N consisting of lowercase English characters, the task is to find the minimum characters to be replaced to make all characters of string str same. Any character can be replaced by any other character. Example: Input: str="geeksforgeeks"Output: 9Explanation: Replace all the characters except 'e' of the string with 'e'. Inp
7 min read
Min flips of continuous characters to make all characters same in a string
Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input : 010101100011Output : 4Method 1 (Change in value
8 min read