Program to count k length substring that occurs more than once in the given string in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s and a number k, we have to find the number of k-length substrings of s, that occur more than once in s.

So, if the input is like s = "xxxyyy", k = 2, then the output will be 2

To solve this, we will follow these steps −

  • seen := a new list
  • for i in range 0 to size of s - k, do
    • t := substring of s [from index i to i + k - 1]
    • insert t at the end of seen
  • mp := a map for all distinct element in seen and their occurrences
  • return sum of all occurrences of each element in mp where occurrence is more than 1

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, k):
      from collections import Counter
      seen = []
      for i in range(len(s) - k + 1):
         t = s[i : i + k]
         seen.append(t)
         s = Counter(seen)
      return sum(1 for x in s.values() if x > 1)
ob = Solution()
print(ob.solve("xxxyyy",2))

Input

"xxxyyy",2

Output

2
raja
Published on 07-Oct-2020 17:06:00
Advertisements