Longest Repeating Character Replacement

Sliding Window / 2 Pointer Longest and Smallest Window Problems Hard
  • This problem is highly relevant in search engine algorithms, particularly those dealing with text analysis and processing
  • The ability to manipulate and understand strings to achieve certain conditions is central to many features, such as autocomplete functions, spell checkers, and text-based recommendation algorithms
  • For example, Google's Search engine may use similar principles to understand and autocorrect your typos to give you accurate search results

Given an integer k and a string s, any character in the string can be selected and changed to any other uppercase English character. This operation can be performed up to k times. After completing these steps, return the length of the longest substring that contains the same letter.

Examples:

Input : s = "BAABAABBBAAA" , k = 2

Output : 6

Explanation : we can change the B present at index 0 , 3 (0 base indexing) to A.

The new string is "AAAAAABBBAAA".

The substring "AAAAAA" is the longest substring having same letter with length 6.

Input : s = "AABABBA" , k = 1

Output : 4

Explanation : The underlined characters are changed in the new string obtained.

The new string is "AABBBBA". The substring "BBBB" is the answer.

There are other ways to achieve this answer.

Input : s = "ABCDEF" k = 1

Constraints

  • 1 <= s.length <= 105
  • 0 <= k <= s.length
  • s contains only English uppercase letters.

Hints

  • Use a sliding window to find the longest substring where at most k characters are replaced to make all characters in the substring the same.
  • Calculate the number of replacements needed to make all characters in the window the same as window_size−max_freq.

Company Tags

Western Digital Pinterest Target Epic Systems Freshworks Texas Instruments Square Byju's Databricks PayPal Cloudflare Boston Consulting Group Zoho Splunk Shopify Riot Games Oracle PwC Micron Technology Roche NVIDIA Flipkart Philips Healthcare Uber HashiCorp Google Microsoft Amazon Meta Apple Netflix Adobe