Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Counting K-Length Strings with Fixed Character in a Unique String
Next article icon

Count Substrings with all Unique Digits in Range [0, K]

Last Updated : 23 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S of length N (1 <= N <= 107) and a positive integer K, where the string contains only numbers in the range [0, 9], the task is to determine the count of substrings that include at least one occurrence of all the unique digits within the specified range [0, K].

Example:

Input: S = "4250163456", K = 3
Output: 5
Explanation: The substrings containing at least one occurrence of all first three unique digits in the range [0, 3] are "4250163", "42501634", "425016345", "4250163456", "250163", "250163", "2501634", "25016345", "250163456".

Input: S = "978623", K = 5
Output: 0

Count Substrings with All Unique Digits in Range [0, K] using Hashing:

Begin with two pointers, start and end, both at the string's beginning. For each start, find the first valid substring starting at start and ending at end. Since this is the first valid substring from start, we can also include the remaining characters from the end index, meeting the minimum validity criteria. There will be (N - end) valid substrings for this start index. Add up all these counts to the result and return it.

Step-by-step approach:

  • Create a character frequency map unmap and variables start, end, n (string size), and result to 0.
  • Create through the string s until the end is less than its size n.
  • If the character at end is in the range [0, K], increment its frequency count in unmap.
  • Check if unmap contains K+1 unique characters. If it does, initiate a loop until unmap contains K unique characters:
    • Increment result by the count of valid substrings, which is (n - end).
    • Decrement the frequency count of the character at start if it's in the range [0, K].
    • If the frequency count becomes 0, remove that character from unmap.
    • Increment start.
  • Increment end and continue.
  • Return result as the final count of valid substrings.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to find the number of substrings int countSubstrings(string s, int K) {     // Initilize a map for keeping     // frequency of characters     unordered_map<char, int> unmap;      // Initilize a variable start = 0,     // end = 0 and result = 0     int start = 0, end = 0, n = s.size(), result = 0;      // Do while end is less than size     // of given string     while (end < n) {          // Increment the frequency of         // character at end, if is lies in         // the range [0, K].         if (s[end] <= (K + '0'))             unmap[s[end]]++;          // Check if the size of         // map becomes K         if (unmap.size() == K + 1) {              // Initiate a while loop             // unless map size is             // equals to K             while (unmap.size() == K + 1) {                  // Increment the value of                 // result by n - end, because                 // (n - end) substring are valid                 // that satisfy the given                 // condition                 result += n - end;                  // Decrement the frequency                 // count of character at                 // start, if it participate                 // previously in map                 if (s[start] <= (K + '0'))                     unmap[s[start]]--;                  // Check if frequency count                 // of character at start in                 // map becomes 0.                 // If true, then remove this                 // character from the map                 if (unmap[s[start]] == 0)                     unmap.erase(s[start]);                  // Move the start pointer                 // to right by incrementing                 // its value by 1                 start++;             }              // Increment the end pointer.             end++;         }          // Otherwise, Increment         // the end pointer by 1.         else {             end++;         }     }      // Return the value of result     return result; }  // Driver code int main() {     string S = "4250163456";     int K = 3;      // Function Call     cout << countSubstrings(S, K);      return 0; } 
Java
import java.util.HashMap; import java.util.Map;  public class SubstringCount {      // Function to find the number of substrings     static int countSubstrings(String s, int K)     {         // Initialize a map for keeping frequency of         // characters         Map<Character, Integer> map = new HashMap<>();          // Initialize variables start = 0, end = 0, and         // result = 0         int start = 0, end = 0, n = s.length(), result = 0;          // Iterate while end is less than the size of the         // given string         while (end < n) {             // Increment the frequency of the character at             // end if it is less than or equal to K             if (s.charAt(end) <= (K + '0')) {                 map.put(s.charAt(end),                         map.getOrDefault(s.charAt(end), 0)                             + 1);             }              // Check if the size of the map becomes K + 1             if (map.size() == K + 1) {                 // Initiate a while loop unless map size is                 // equal to K                 while (map.size() == K + 1) {                     // Increment the value of result by (n -                     // end) because (n - end) substrings are                     // valid that satisfy the given                     // condition                     result += n - end;                      // Decrement the frequency count of the                     // character at start if it participated                     // previously in the map                     if (s.charAt(start) <= (K + '0')) {                         map.put(s.charAt(start),                                 map.get(s.charAt(start))                                     - 1);                         if (map.get(s.charAt(start)) == 0) {                             map.remove(s.charAt(start));                         }                     }                      // Move the start pointer to the right                     // by incrementing its value by 1                     start++;                 }                  // Increment the end pointer                 end++;             }             else {                 // Increment the end pointer by 1                 end++;             }         }          // Return the value of result         return result;     }      // Driver code     public static void main(String[] args)     {         String S = "4250163456";         int K = 3;          // Function Call         System.out.println(countSubstrings(S, K));     } } 
Python3
# Python code to implement the approach def countSubstrings(s, K):     # Initialize a dictionary to keep     # frequency of characters     unmap = {}      # Initialize variables: start = 0,     # end = 0, and result = 0     start, end, n, result = 0, 0, len(s), 0      # Loop until end is less than the     # size of the given string     while end < n:         # Increment the frequency of character         # at end if it's in the range [0, K]         if s[end] <= chr(K + ord('0')):             unmap[s[end]] = unmap.get(s[end], 0) + 1          # Check if the size of the map becomes K + 1         if len(unmap) == K + 1:             # While loop until map size is equal to K             while len(unmap) == K + 1:                 # Increment the value of result by                 # n - end because (n - end) substrings                 # are valid satisfying the condition                 result += n - end                  # Decrement the frequency count of                 # character at start if it's                 # in the range [0, K]                 if s[start] <= chr(K + ord('0')):                     unmap[s[start]] = unmap.get(s[start], 0) - 1                      # If frequency count becomes 0,                     # remove the character from the map                     if unmap[s[start]] == 0:                         del unmap[s[start]]                  # Move the start pointer to the                 # right by incrementing its value by 1                 start += 1              # Increment the end pointer             end += 1          # Otherwise, increment the end         # pointer by 1         else:             end += 1      # Return the value of result     return result   # Driver code S = "4250163456" K = 3  # Function Call print(countSubstrings(S, K)) 
C#
using System; using System.Collections.Generic;  public class SubstringCount {     // Function to find the number of substrings     static int CountSubstrings(string s, int K)     {         // Initialize a dictionary for keeping frequency of         // characters         Dictionary<char, int> map             = new Dictionary<char, int>();          // Initialize variables start = 0, end = 0, and         // result = 0         int start = 0, end = 0, n = s.Length, result = 0;          // Iterate while end is less than the size of the         // given string         while (end < n) {             // Increment the frequency of the character at             // end if it is less than or equal to K             if (s[end] <= (K + '0')) {                 map[s[end]]                     = map.GetValueOrDefault(s[end], 0) + 1;             }              // Check if the size of the map becomes K + 1             if (map.Count == K + 1) {                 // Initiate a while loop unless map size is                 // equal to K                 while (map.Count == K + 1) {                     // Increment the value of result by (n -                     // end) because (n - end) substrings are                     // valid that satisfy the given                     // condition                     result += n - end;                      // Decrement the frequency count of the                     // character at start if it participated                     // previously in the map                     if (s[start] <= (K + '0')) {                         map[s[start]] = map[s[start]] - 1;                         if (map[s[start]] == 0) {                             map.Remove(s[start]);                         }                     }                      // Move the start pointer to the right                     // by incrementing its value by 1                     start++;                 }                  // Increment the end pointer                 end++;             }             else {                 // Increment the end pointer by 1                 end++;             }         }          // Return the value of result         return result;     }      // Driver code     public static void Main(string[] args)     {         string S = "4250163456";         int K = 3;          // Function Call         Console.WriteLine(CountSubstrings(S, K));     } } 
JavaScript
function GFG(s, K) {     // Initialize a map for keeping frequency of the characters     const unmap = new Map();     let start = 0,         end = 0,         n = s.length,         result = 0;     // Do while end is less than the size of the given string     while (end < n) {         if (s[end] <= String(K)) {             unmap.set(s[end], (unmap.get(s[end]) || 0) + 1);         }         // Check if the size of the map becomes K + 1         if (unmap.size === K + 1) {             // Initiate a while loop unless map size is equal to K             while (unmap.size === K + 1) {                 // Increment the value of result by n - end,                 // because (n - end) substrings are valid that                 result += n - end;                 // Decrement the frequency count of the character at start if it participated                 if (s[start] <= String(K)) {                     unmap.set(s[start], unmap.get(s[start]) - 1);                 }                 // Check if the frequency count of the                 // character at start in the map becomes 0                 if (unmap.get(s[start]) === 0) {                     unmap.delete(s[start]);                 }                 start++;             }             // Increment the end pointer             end++;         } else {             // Otherwise, increment the end pointer by 1             end++;         }     }     // Return the value of result     return result; } // Driver code const S = "4250163456"; const K = 3; console.log(GFG(S, K)); 

Output
8

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Counting K-Length Strings with Fixed Character in a Unique String

K

krishna_g
Improve
Article Tags :
  • Strings
  • Geeks Premier League
  • DSA
  • Hash
  • Geeks Premier League 2023
Practice Tags :
  • Hash
  • Strings

Similar Reads

  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Counting K-Length Strings with Fixed Character in a Unique String
    Given a string S of length n containing distinct characters and a character C , the task is to count k-length strings that can be formed using characters from the string S, ensuring each string includes the specified character C, and no characters from the given string S are used more than once. Ret
    9 min read
  • Count of numbers with all digits same in a given range
    Given two integers L and R denoting the starting and end values of a range, the task is to count all numbers in that range whose all digit are same, like 1, 22, 444, 3333, etc.Example: Input: L = 12, R = 68 Output: 5 Explanation: { 22, 33, 44, 55, 66} are the numbers with same digits in the given ra
    10 min read
  • Longest substring with k unique characters
    Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them. Note:- Source(Google Interview Question). Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max subs
    13 min read
  • Find all substrings containing exactly K unique vowels
    Given string str of length N containing both uppercase and lowercase letters, and an integer K. The task is to find all substrings containing exactly K distinct vowels. Examples: Input: str = "aeiou", K = 2Output: "ae", "ei", "io", "ou"Explanation: These are the substrings containing exactly 2 disti
    8 min read
  • Count of unique Subsequences of given String with lengths in range [0, N]
    Given a string S of length N, the task is to find the number of unique subsequences of the string for each length from 0 to N. Note: The uppercase letters and lowercase letters are considered different and the result may be large so print it modulo 1000000007. Examples: Input: S = "ababd"Output: Num
    15 min read
  • Count numbers with unit digit k in given range
    Here given a range from low to high and given a number k.You have to find out the number of count which a number has same digit as kExamples: Input: low = 2, high = 35, k = 2 Output: 4 Numbers are 2, 12, 22, 32 Input: low = 3, high = 30, k = 3 Output: 3 Numbers are 3, 13, 23 A naive approach is to t
    7 min read
  • Count of unique digits in a given number N
    Given a number N, the task is to count the number of unique digits in the given number. Examples: Input: N = 22342 Output: 2 Explanation:The digits 3 and 4 occurs only once. Hence, the output is 2. Input: N = 99677 Output: 1Explanation:The digit 6 occurs only once. Hence, the output is 1. Naive Appr
    6 min read
  • Count substrings with k distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
    10 min read
  • Count of N digit numbers with at least one digit as K
    Given a number N and a digit K, The task is to count N digit numbers with at least one digit as K. Examples: Input: N = 3, K = 2Output: 252Explanation: For one occurrence of 2 - In a number of length 3, the following cases are possible:=>When first digit is 2 and other two digits can have 9 value
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences