//brute force approach: O(N^2)
class Solution {
public int numberOfSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
int hash[] = new int[3];// for a,b and c only
for (int j = i; j < s.length(); j++) {
char c = s.charAt(j);
hash[c-'a']++;
if(hash[0]>=1 && hash[1] >=1 && hash[2]>=1){
count++;
}
}
}
return count;
}
}
//a little bit of optimization on the brute force approach: but in worst case the time complexity will still be O(n^2)
class Solution {
public int numberOfSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
int hash[] = new int[3];// for a,b and c only
for (int j = i; j < s.length(); j++) {
char c = s.charAt(j);
hash[c-'a']++;
if(hash[0]>=1 && hash[1] >=1 && hash[2]>=1){
/*If we have already found a substring that satisfies the condition,
then all the other substrings that will come after this (will include this substring as well) will also
be valid strings, hence no need to create the rest of the strings we can break out*/
count+= s.length()-j;
break;
}
}
}
return count;
}
}
Optimal approach: O(n)
This involves finding out what is the smallest substring that we can create that satisfies the given condition.
for more understanding refer to striver solution: here
class Solution {
public int numberOfSubstrings(String s) {
//WITH EVERY CHARACTER THERE IS A SUBSTRING THAT ENDS
int hash[] = new int[3];// it will keep track of last seen indexes of a,b,c
Arrays.fill(hash,-1); //initializing the index value of all the a,b and c to -1
int count =0;
for(int i =0;i<s.length();i++){
char c = s.charAt(i);
hash[c-'a'] = i;
if(hash[0]!=-1 && hash[1]!=-1 && hash[2]!=-1){
//we choose min because whichever seems last, all the character before the last seen character will form a substring
count+= 1 + Integer.min(hash[0],Integer.min(hash[1],hash[2]));// get the last seen index of (a or b or c), since it is 0 based indexing
//hence if the last index was at index 2 then there will be 3 substrings satisfying the condition, substring starting from 0, 1, and finally 2 itself
}
}
return count;
}
}
Top comments (0)