DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Permutation in String

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1's permutations is the substring of s2.

Example 1:

Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

Input: s1 = "ab", s2 = "eidboaoo"
Output: false

Constraints:

  • 1 <= s1.length, s2.length <= 104
  • s1 and s2 consist of lowercase English letters.

SOLUTION:

class Solution:
    def checkInclusion(self, p: str, s: str) -> bool:
        np = len(p)
        ns = len(s)
        if np > ns:
            return False
        pctr = [0] * 26
        for c in p:
            pctr[ord(c) - ord('a')] += 1
        sctr = [0] * 26
        for i in range(np):
            sctr[ord(s[i]) - ord('a')] += 1
        i = 0
        while i < ns - np:
            if pctr == sctr:
                return True
            sctr[ord(s[i]) - ord('a')] -= 1
            sctr[ord(s[i + np]) - ord('a')] += 1
            i += 1
        if pctr == sctr:
            return True
        return False
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay