Vermicomposting And Worms

Vermicomposting- Is the process of using various species of worms, usually red wigglers, white worms, and other earthworms, to create a mixture of decomposing vegetable or food waste, bedding…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Finding length of longest substring after K replacements in given string

Finding length of longest substring after K replacements in given string

Problem Statement

Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement.

Example 1:

Input: String=”aabccbb”, k=2
Output: 5
Explanation: Replace the two ‘c’ with ‘b’ to have a longest repeating substring “bbbbb”.

Example 2:

Input: String=”abbcb”, k=1
Output: 4
Explanation: Replace the ‘c’ with ‘b’ to have a longest repeating substring “bbbb”.


Example 3:

Input: String=”abccde”, k=1
Output: 3
Explanation: Replace the ‘b’ or ‘d’ with ‘c’ to have the longest repeating substring “ccc”.


Solution

We’ll iterate through the string to add one letter at a time in the window. We’ll also keep track of the count of the maximum repeating letter in any window (let’s call it maxRepeatLetterCount). So at any time, we know that we can have a window which has one letter repeating maxRepeatLetterCount times, this means we should try to replace the remaining letters. If we have more than ‘k’ remaining letters, we should shrink the window as we are not allowed to replace more than ‘k’ letters.

Javascript code below:-

The time complexity of the above algorithm will be O(N) where ’N’ is the number of letters in the input string.

Space Complexity

As we are expecting only the lower case letters in the input string, we can conclude that the space complexity will be O(26), to store each letter’s frequency in the Map, which is asymptotically equal to O(1).

Add a comment

Related posts:

Loading dynamic configurations in Kubernetes Kustomize

Kustomize for Kubernetes is cool! It provides a structured approach to generating Kubernetes resource manifests instead of relying on text-based templating. This eliminates a whole class of bugs…

Meditation Is Not Relaxation

The room is full of people sitting on cushions with their legs crossed. We will sit like this for forty minutes as we meditate together. After about twenty minutes, I hear a snore. I ignore it. It’s…

Jalanku Mengingatmu

Dalam perjalanan yang menyapu waktu habis-habisan. Aku telah terhenti dari deras lajunya pada salah satu titik di bahu jalan saat sedang menuju ke rumahmu. Sejenak saja kepalaku menengok sana sini…