{"id":8050,"date":"2025-07-19T23:34:11","date_gmt":"2025-07-19T18:04:11","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=8050"},"modified":"2025-07-20T17:25:18","modified_gmt":"2025-07-20T11:55:18","slug":"longestrepeatingcharreplacement","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/longestrepeatingcharreplacement\/","title":{"rendered":"Longest Repeating Character Replacement"},"content":{"rendered":"\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style> \n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #f8c291;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2{\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n.wp_blog_explanation h5{\n  color: var(--primary);\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n.wp_blog_explanation code {\n  background: #f9cea6;\n  color: #2d2d2d;\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n}\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0,0,0,0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\"> \n    <h1 class=\"wp_blog_main-heading\"><\/h1>\n    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n\n        <p>You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k<\/code> times.\n        <\/p>\n\n        <p>Return the <i>length of the longest substring containing the same letter you can get after performing the above operations.<\/i><\/p>\n\n                <h2>Examples:<\/h2>\n                <h5>Example 1:<\/h5>\n                <p><strong>Input:<\/strong> s = &#8220;ABAB&#8221;, k = 2<\/p>\n                <p><strong>Output:<\/strong> 2<\/p>\n                <p>\n                  <strong>Explanation:<\/strong>\n                  Replace the two &#8216;A&#8217;s with two &#8216;B&#8217;s or vice versa.\n                <\/p>\n\n                <h5>Example 2:<\/h5>\n                <p><strong>Input:<\/strong> s = &#8220;AABABBA&#8221;, k = 1<\/p>\n                <p><strong>Output:<\/strong> 4<\/p>\n                <p><strong>Explanation:<\/strong> Replace the one &#8216;A&#8217; in the middle with &#8216;B&#8217; and form &#8220;AABBBBA&#8221;.\n                The substring &#8220;BBBB&#8221; has the longest repeating letters, which is 4.\n                There may exists other ways to achieve this answer too.<\/p>\n\n                    <h2>Constraints:<\/h2>\n                    <ul>\n                      <li><code>0 <= s.length <= 10<sup>5<\/sup><\/code><\/li>\n                      <li><code>s<\/code> consists of English letters, digits, symbols and spaces.<\/li>\n                      <li><code>0 <= k <= s.length<\/code><\/li>\n                    <\/ul>\n\n                <h2>Approach<\/h2>\n                <ul>\n                  <li>Use a sliding window with two pointers <code>i<\/code> and <code>j<\/code> to represent the current window.<\/li>\n                  <li>Maintain a frequency array <code>map<\/code> of size 26 for uppercase letters.<\/li>\n                  <li>At each step, check if the window is valid:\n                    <ul>\n                      <li>A window is valid if total letters - max frequent letter \u2264 <code>k<\/code> (i.e., we can change \u2264 k chars to make all same).<\/li>\n                    <\/ul>\n                  <\/li>\n                    <li>\n                      If valid, expand the window <code>(j++)<\/code>, else shrink from left <code>(i++)<\/code>.\n                    <\/li>\n\n                    <li>Track the maximum valid window size throughout.<\/li>\n                <\/ul>\n\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(26 x n) \u2248 O(n)<\/strong>\n                  <\/li>\n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(m)<\/strong><\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2> <div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\"> <p><strong>Input:<\/strong> <code>s = \"AABABBA\", k = 1<\/code><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\"> Initialize: i = 0, j = 0 map = Array(26).fill(0) map['A'] \u2192 map[0] = 1 (first char) maxWindow = 0\n\/\/ Start while loop: j < s.length\n\nj = 0 \u2192 s[j] = 'A'\n\u2192 map = [1,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 1, maxCount = 1\n\u2192 1 - 1 \u2264 1 \u2192 valid\n\u2192 maxWindow = max(0, 0-0+1) = 1\n\u2192 j++, j = 1\n\u2192 map['A']++ \u2192 map[0] = 2\n\nj = 1 \u2192 s[j] = 'A'\n\u2192 map = [2,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 2, maxCount = 2\n\u2192 2 - 2 \u2264 1 \u2192 valid\n\u2192 maxWindow = max(1, 1-0+1) = 2\n\u2192 j++, j = 2\n\u2192 map['B']++ \u2192 map[1] = 1\n\nj = 2 \u2192 s[j] = 'B'\n\u2192 map = [2,1,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 3, maxCount = 2\n\u2192 3 - 2 = 1 \u2264 1 \u2192 valid\n\u2192 maxWindow = max(2, 2-0+1) = 3\n\u2192 j++, j = 3\n\u2192 map['A']++ \u2192 map[0] = 3\n\nj = 3 \u2192 s[j] = 'A'\n\u2192 map = [3,1,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 4, maxCount = 3\n\u2192 4 - 3 = 1 \u2264 1 \u2192 valid\n\u2192 maxWindow = max(3, 3-0+1) = 4\n\u2192 j++, j = 4\n\u2192 map['B']++ \u2192 map[1] = 2\n\nj = 4 \u2192 s[j] = 'B'\n\u2192 map = [3,2,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 5, maxCount = 3\n\u2192 5 - 3 = 2 > 1 \u2192 invalid\n\u2192 shrink window:\n\u2192 map['A']-- \u2192 map[0] = 2\n\u2192 i++, i = 1\n\n\u2192 isWindowValid(map, 1):\ntotalCount = 4, maxCount = 2\n\u2192 4 - 2 = 2 > 1 \u2192 invalid\n\u2192 map['A']-- \u2192 map[0] = 1\n\u2192 i++, i = 2\n\n\u2192 isWindowValid(map, 1):\ntotalCount = 3, maxCount = 2\n\u2192 3 - 2 = 1 \u2192 valid\n\u2192 maxWindow = max(4, 4-2+1) = 4\n\u2192 j++, j = 5\n\u2192 map['B']++ \u2192 map[1] = 3\n\nj = 5 \u2192 s[j] = 'B'\n\u2192 map = [1,3,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 4, maxCount = 3\n\u2192 4 - 3 = 1 \u2192 valid\n\u2192 maxWindow = max(4, 5-2+1) = 4\n\u2192 j++, j = 6\n\u2192 map['A']++ \u2192 map[0] = 2\n\nj = 6 \u2192 s[j] = 'A'\n\u2192 map = [2,3,...]\n\u2192 isWindowValid(map, 1):\ntotalCount = 5, maxCount = 3\n\u2192 5 - 3 = 2 > 1 \u2192 invalid\n\u2192 shrink window:\n\u2192 map['B']-- \u2192 map[1] = 2\n\u2192 i++, i = 3\n\n\u2192 isWindowValid(map, 1):\ntotalCount = 4, maxCount = 2\n\u2192 4 - 2 = 2 > 1 \u2192 invalid\n\u2192 map['A']-- \u2192 map[0] = 1\n\u2192 i++, i = 4\n\n\u2192 isWindowValid(map, 1):\ntotalCount = 3, maxCount = 2\n\u2192 3 - 2 = 1 \u2192 valid\n\u2192 maxWindow = max(4, 6-4+1) = 4\n\u2192 j++, j = 7 \u2192 exit loop\n\nFinal map: [1,2,...]\nFinal maxWindow: 4\n<\/pre>\n\n<p><strong>Output:<\/strong> <code>Result: 4<\/code><\/p> <\/div>\n                \n        <!-- <h2>Visualisation:<\/h2>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-19-at-5.23.43\u202fPM.png\" alt=\"longest\" \/> -->\n    <\/div>\n    \n\n    <div class=\"wp_blog_code-tabs-container\">\n        <div class=\"wp_blog_code-tabs-header\">\n            <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n        <\/div>\n\n        <!-- JavaScript -->\n        <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n            <pre><code class=\"language-javascript\">\nvar characterReplacement = function(s, k) {\n    let i = 0, j = 0;\n    let map = Array(26).fill(0);\n    map[s.charCodeAt(0) - 65] = 1;\n    let maxWindow = 0;\n    while (j < s.length) {\n        if (isWindowValid(map, k)) {\n            maxWindow = Math.max(maxWindow, j - i + 1);\n            ++j;\n            ++map[s.charCodeAt(j) - 65];\n        } else {\n            --map[s.charCodeAt(i) - 65];\n            ++i;\n        }\n    }\n    return maxWindow;  \n};\nvar isWindowValid = function(map, k) {\n    let totalCount = 0;\n    let maxCount = 0;\n    for (let i = 0; i < 26; i++) {\n        totalCount += map[i];\n        maxCount = Math.max(maxCount, map[i]);\n    }\n    return (totalCount - maxCount <= k);\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- Python -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\ndef is_window_valid(counts, k):\n    total = sum(counts)\n    max_count = max(counts)\n    return (total - max_count) <= k\ndef characterReplacement(s, k):\n    i = j = 0\n    counts = [0] * 26\n    counts[ord(s[0]) - ord('A')] = 1\n    max_window = 0\n    while j < len(s):\n        if is_window_valid(counts, k):\n            max_window = max(max_window, j - i + 1)\n            j += 1\n            if j < len(s):\n                counts[ord(s[j]) - ord('A')] += 1\n        else:\n            counts[ord(s[i]) - ord('A')] -= 1\n            i += 1\n    return max_window\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- Java -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n            <pre><code class=\"language-java\">\nimport java.util.HashMap;\npublic class Solution {\n    public int characterReplacement(String s, int k) {\n        int[] map = new int[26];\n        int i = 0, j = 0, maxWindow = 0;\n        map[s.charAt(0) - 'A'] = 1;\n        while(j < s.length()) {\n            if(isWindowValid(map, k)) {\n                maxWindow = Math.max(maxWindow, j - i + 1);\n                ++j;\n                if(j < s.length()) map[s.charAt(j) - 'A']++;\n            } else {\n                map[s.charAt(i) - 'A']--;\n                ++i;\n            }\n        }\n        return maxWindow;\n    }\n    private boolean isWindowValid(int[] map, int k) {\n        int totalCount = 0, maxCount = 0;\n        for(int count : map) {\n            totalCount += count;\n            maxCount = Math.max(maxCount, count);\n        }\n        return (totalCount - maxCount <= k);\n    }\n}\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- C++ -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n            <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\nbool isWindowValid(vector<int>& map, int k) {\n    int totalCount = 0, maxCount = 0;\n    for(int i = 0; i < 26; i++) {\n        totalCount += map[i];\n        maxCount = max(maxCount, map[i]);\n    }\n    return (totalCount - maxCount <= k);\n}\nint characterReplacement(string s, int k) {\n    int i = 0, j = 0, maxWindow = 0;\n    vector<int> map(26, 0);\n    map[s[0] - 'A'] = 1;\n    while(j < s.length()) {\n        if(isWindowValid(map, k)) {\n            maxWindow = max(maxWindow, j - i + 1);\n            ++j;\n            if(j < s.length()) ++map[s[j] - 'A'];\n        } else {\n            --map[s[i] - 'A'];\n            ++i;\n        }\n    }\n    return maxWindow;\n}\n    <\/code><\/pre>\n        <\/div>\n\n        <!-- C -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n            <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\nint isWindowValid(int map[26], int k) {\n    int totalCount = 0, maxCount = 0;\n    for(int i = 0; i < 26; i++) {\n        totalCount += map[i];\n        if(map[i] > maxCount) maxCount = map[i];\n    }\n    return (totalCount - maxCount <= k);\n}\nint characterReplacement(const char* s, int k) {\n    int map[26] = {0};\n    int i = 0, j = 0, maxWindow = 0;\n    map[s[0] - 'A'] = 1;\n    int len = strlen(s);\n    while(j < len) {\n        if(isWindowValid(map, k)) {\n            if(maxWindow < j - i + 1) maxWindow = j - i + 1;\n            ++j;\n            if(j < len) map[s[j] - 'A']++;\n        } else {\n            map[s[i] - 'A']--;\n            ++i;\n        }\n    }\n    return maxWindow;\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C# -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n            <pre><code class=\"language-csharp\">\nusing System;\n\npublic class Solution {\n    public int CharacterReplacement(string s, int k) {\n        int[] map = new int[26];\n        int i = 0, j = 0, maxWindow = 0;\n        map[s[0] - 'A'] = 1;\n\n        while (j < s.Length) {\n            if (IsWindowValid(map, k)) {\n                maxWindow = Math.Max(maxWindow, j - i + 1);\n                ++j;\n                if (j < s.Length) map[s[j] - 'A']++;\n            } else {\n                map[s[i] - 'A']--;\n                ++i;\n            }\n        }\n        return maxWindow;\n    }\n\n    private bool IsWindowValid(int[] map, int k) {\n        int totalCount = 0, maxCount = 0;\n        foreach (int count in map) {\n            totalCount += count;\n            maxCount = Math.Max(maxCount, count);\n        }\n        return (totalCount - maxCount <= k);\n    }\n}\n       <\/code><\/pre>\n        <\/div>\n    <\/div>\n<\/div>\n\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\n        const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n        const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n        buttons.forEach((button) => {\n            button.addEventListener(\"click\", () => {\n                const lang = button.getAttribute(\"data-lang\");\n\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n\n                button.classList.add(\"active\");\n                document\n                    .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-8050","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms-and-data-structures","7":"category-c-c-plus-plus","8":"category-csharp","9":"category-cplusplus","10":"category-data-structures","11":"category-data-structures-and-algorithms","12":"category-dsa","13":"category-java","14":"category-javascript","15":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8050","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=8050"}],"version-history":[{"count":4,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8050\/revisions"}],"predecessor-version":[{"id":8077,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8050\/revisions\/8077"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=8050"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=8050"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=8050"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}