educative.io

Alternate solution utilizing casting

string perm(string S, string P){

// convert to numbers
vector s_nums = {};
for (int i = 0; i < S.length(); i++){
int j = (int)S[i];
s_nums.push_back(j);
}

int targetSum = 0;
for (int i = 0; i < P.length(); i++){
int j = (int)P[i];
targetSum += j;
}

int windowStart = 0;
int windowSum = 0;

for(int windowEnd=0; windowEnd < s_nums.size(); windowEnd++){
windowSum += s_nums[windowEnd];
if (windowEnd+1 - windowStart == P.length()){
if (windowSum == targetSum){
return “True”;
}
windowSum -= s_nums[windowStart];
windowStart++;
}
}

return “False”;
}

In this case, I simply converted the characters to their corresponding value. This way the problem can be framed simply as finding a window with the equivalent sum within some window with the equivalent length of the pattern. Is there anything wrong with this reasoning? It passes all the test cases.

This will not work because the string “ac” has the same sum as the string “bb” similar to how 10+12 = 11 + 11 = 22.