educative.io

Educative

Cant we take a sum of pattern as required_sum and treat this problem as substring of given sum and given length

def find_permutation(str, pattern):

TODO: Write your code here

#lets get the required number:

sum_required = 0

for i in range(len(pattern)):

sum_required += ord(pattern[i])

len_required = len(pattern)

start = 0

sum_arr = 0

for end in range(len(str)):

sum_arr += ord(str[end])

if end >= len_required-1:

  if sum_arr == sum_required:

    return True

  else:

    sum_arr -= ord(str[start])

    start += 1

return False

This is a good (and clever!) idea but it fails some edge cases. For example, this one: str = 'bbb' and pattern = 'abc'. The problem is that these two strings share the same sum and length but are different.

print(sum([ord(char) for char in 'abc']) == sum([ord(char) for char in 'bbb'])) # True
print(len('abc') == len('bbb')) # True
print('abc' == 'bbb') # False

thanks Lakshay. Appreciate the response