{"id":931,"date":"2025-08-20T13:34:02","date_gmt":"2025-08-20T08:04:02","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=931"},"modified":"2025-08-20T13:40:13","modified_gmt":"2025-08-20T08:10:13","slug":"number-of-substrings-containing-all-three-characters","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/","title":{"rendered":"Number of Substrings Containing All Three Characters | Leetcode 1358 | Optimal Solution using Sliding Window"},"content":{"rendered":"\n<p>The problem&nbsp;<strong>\u201cNumber of&nbsp;Substrings Containing All Three&nbsp;Characters\u201d<\/strong>&nbsp;asks: given a string&nbsp;<code>s<\/code>&nbsp;consisting&nbsp;only of the characters&nbsp;<strong>&#8216;a&#8217;<\/strong>,&nbsp;<strong>&#8216;b&#8217;<\/strong>, and&nbsp;<strong>&#8216;c&#8217;<\/strong>, count&nbsp;how many substrings contain&nbsp;<strong>at least one of&nbsp;each<\/strong>&nbsp;of these&nbsp;three characters. This is a classic&nbsp;substring counting&nbsp;problem that&nbsp;can be solved&nbsp;progressively, starting with&nbsp;a&nbsp;<strong>brute force<\/strong>&nbsp;approach, improved&nbsp;with a&nbsp;<strong>pruning trick<\/strong>, and finally&nbsp;achieving an&nbsp;<strong>O(n)<\/strong>&nbsp;optimal&nbsp;solution using&nbsp;<strong>last-seen indices<\/strong>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/number-of-substrings-containing-all-three-characters\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>Given a string&nbsp;<code>s<\/code>&nbsp;consisting only of characters&nbsp;<em>a<\/em>,&nbsp;<em>b<\/em>&nbsp;and&nbsp;<em>c<\/em>.<\/p>\n\n\n\n<p>Return the number of substrings containing&nbsp;<strong>at least<\/strong>&nbsp;one occurrence of all these characters&nbsp;<em>a<\/em>,&nbsp;<em>b<\/em>&nbsp;and&nbsp;<em>c<\/em>.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> s = \"abcabc\"<br><strong>Output:<\/strong> 10<br><strong>Explanation:<\/strong> The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;<em>a<\/em>,&nbsp;<em>b<\/em>&nbsp;and&nbsp;<em>c are \"<\/em>abc<em>\", \"<\/em>abca<em>\", \"<\/em>abcab<em>\", \"<\/em>abcabc<em>\", \"<\/em>bca<em>\", \"<\/em>bcab<em>\", \"<\/em>bcabc<em>\", \"<\/em>cab<em>\", \"<\/em>cabc<em>\" <\/em>and<em> \"<\/em>abc<em>\" <\/em>(<strong>again<\/strong>)<em>. <\/em><\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> s = \"aaacb\"<br><strong>Output:<\/strong> 3<br><strong>Explanation:<\/strong> The substrings containing&nbsp;at least&nbsp;one occurrence of the characters&nbsp;<em>a<\/em>,&nbsp;<em>b<\/em>&nbsp;and&nbsp;<em>c are \"<\/em>aaacb<em>\", \"<\/em>aacb<em>\" <\/em>and<em> \"<\/em>acb<em>\". <\/em><\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> s = \"abc\"<br><strong>Output:<\/strong> 1<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>3 &lt;= s.length &lt;= 5 x 10^4<\/code><\/li>\n\n\n\n<li><code>s<\/code>&nbsp;only consists of&nbsp;<em>a<\/em>,&nbsp;<em>b<\/em>&nbsp;or&nbsp;<em>c&nbsp;<\/em>characters.<\/li>\n<\/ul>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-fb42a82c-6aad-468c-940c-0f96e03c988a\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#0-brute-force-check-every-substring\" style=\"\">Brute Force (Check Every Substring)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#1-intuition-and-approach-\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#2-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#3-why-it-works\" style=\"\">Why It Works<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#4-complexity\" style=\"\">Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#5-limitations\" style=\"\">Limitations<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#6-better-prune-with-suffix-count-once-valid\" style=\"\">Better (Prune With Suffix Count Once Valid)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#7-intuition-and-approach-\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#8-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#9-why-it-works\" style=\"\">Why It Works<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#10-complexity\" style=\"\">Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#11-benefit\" style=\"\">Benefit<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#12-optimal-single-pass-using-last-seen-indices-%E2%80%94-on\" style=\"\">Optimal (Single Pass Using\u00a0Last Seen Indices) \u2014 O(n)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#13-core-insight-\" style=\"\">Core Insight<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#14-code-\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#15-why-it-works\" style=\"\">Why It Works<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#16-complexity\" style=\"\">Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#17-dry-run-quick\" style=\"\">Dry Run (Quick)<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#18-comparison-summary\" style=\"\">Comparison Summary<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#19-common-pitfalls-and-tips-\" style=\"\">Common\u00a0Pitfalls\u00a0and\u00a0Tips<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/number-of-substrings-containing-all-three-characters\/#20-final-takeaway\" style=\"\">Final Takeaway<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-check-every-substring\">Brute Force (Check Every Substring)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach-\"><strong>Intuition and Approach<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For every start&nbsp;<code>i<\/code>, expand the end pointer&nbsp;<code>j<\/code>&nbsp;and keep a&nbsp;<strong>set<\/strong>&nbsp;of distinct characters.<\/li>\n\n\n\n<li>If the set size reaches&nbsp;<strong>3<\/strong>, the current substring&nbsp;<code>[i..j]<\/code>&nbsp;contains&nbsp;<code>'a'<\/code>,&nbsp;<code>'b'<\/code>, and&nbsp;<code>'c'<\/code>\u2014increment the count.<\/li>\n\n\n\n<li>Continue checking for all&nbsp;<code>i<\/code>&nbsp;and&nbsp;<code>j<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def numberOfSubstrings(self, s: str) -&gt; int:\n        count = 0\n        n = len(s)\n        for i in range(n):\n            chars = set()\n            for j in range(i, n):\n                chars.add(s[j])\n                if len(chars) == 3:\n                    count += 1\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">numberOfSubstrings<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">s<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(s)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            chars = <\/span><span style=\"color: #4EC9B0\">set<\/span><span style=\"color: #D4D4D4\">()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                chars.add(s[j])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(chars) == <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-why-it-works\">Why It Works<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The&nbsp;<strong>set<\/strong>&nbsp;tracks how many unique characters are in the current substring. When size is 3, the substring qualifies.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-complexity\">Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>&nbsp;O(n^2) (nested loops; set inserts O(1))<\/li>\n\n\n\n<li><strong>Space:<\/strong>&nbsp;O(1) (set size \u2264 3)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-limitations\">Limitations<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Continues scanning even after finding the first valid&nbsp;<code>j<\/code>&nbsp;for a given&nbsp;<code>i<\/code>, missing a large counting shortcut.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-better-prune-with-suffix-count-once-valid\">Better (Prune With Suffix Count Once Valid)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-intuition-and-approach-\"><strong>Intuition and Approach<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Same nested iteration, but employ a&nbsp;<strong>smart counting trick<\/strong>:\n<ul class=\"wp-block-list\">\n<li>For a fixed&nbsp;<code>i<\/code>, as soon as the substring&nbsp;<code>[i..j]<\/code>&nbsp;contains all three chars, then every substring ending at positions&nbsp;<code>j, j+1, ..., n-1<\/code>&nbsp;is also valid.<\/li>\n\n\n\n<li>So add&nbsp;<strong>(n \u2212 j)<\/strong>&nbsp;to the answer and&nbsp;<strong>break<\/strong>&nbsp;early to move to the next&nbsp;<code>i<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def numberOfSubstrings(self, s: str) -&gt; int:\n        count = 0\n        n = len(s)\n        for i in range(n):\n            chars = set()\n            for j in range(i, n):\n                chars.add(s[j])\n                if len(chars) == 3:\n                    count += n - j\n                    break\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">numberOfSubstrings<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">s<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(s)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            chars = <\/span><span style=\"color: #4EC9B0\">set<\/span><span style=\"color: #D4D4D4\">()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                chars.add(s[j])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(chars) == <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    count += n - j<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">break<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-why-it-works\">Why It Works<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Once&nbsp;<code>[i..j]<\/code>&nbsp;is valid, extending the right end keeps the substring valid. Hence count all such extensions in O(1) time.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-complexity\">Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>&nbsp;O(n^2) in worst case, but typically faster due to early breaks<\/li>\n\n\n\n<li><strong>Space:<\/strong>&nbsp;O(1)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-benefit\">Benefit<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Much faster in practice than pure brute force, especially on strings where the three characters appear frequently.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"12-optimal-single-pass-using-last-seen-indices-%E2%80%94-on\">Optimal (Single Pass Using&nbsp;<strong>Last Seen Indices<\/strong>) \u2014 O(n)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-core-insight-\"><strong>Core Insight<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Track the&nbsp;<strong>latest index<\/strong>&nbsp;where each of&nbsp;<code>'a'<\/code>,&nbsp;<code>'b'<\/code>, and&nbsp;<code>'c'<\/code>&nbsp;appeared.<\/li>\n\n\n\n<li>At each position&nbsp;<code>i<\/code>, if all three have appeared at least once (i.e., all indices are non-negative), then the number of valid substrings&nbsp;<strong>ending at&nbsp;<code>i<\/code><\/strong>&nbsp;is determined by the&nbsp;<strong>leftmost last-seen index<\/strong>&nbsp;among the three.\n<ul class=\"wp-block-list\">\n<li>Let&nbsp;<code>last['a']<\/code>,&nbsp;<code>last['b']<\/code>,&nbsp;<code>last['c']<\/code>&nbsp;be the last indices seen so far.<\/li>\n\n\n\n<li>If all are \u2265 0, then the earliest starting point for a valid substring ending at&nbsp;<code>i<\/code>&nbsp;is&nbsp;<code>min(last.values())<\/code>.<\/li>\n\n\n\n<li>Any start index&nbsp;<code>s<\/code>&nbsp;in&nbsp;<code>[0..min(last.values())]<\/code>&nbsp;ensures the substring&nbsp;<code>s..i<\/code>&nbsp;contains all three chars.<\/li>\n\n\n\n<li>So add&nbsp;<code>min(last.values()) + 1<\/code>&nbsp;to the total for this&nbsp;<code>i<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p>This turns the problem into a tight&nbsp;<strong>O(n)<\/strong>&nbsp;scan with constant extra space.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-code-\">Code <\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def numberOfSubstrings(self, s: str) -&gt; int:\n        count = 0\n        n = len(s)\n        i = 0\n        numbers = {&quot;a&quot;: -1, &quot;b&quot;: -1, &quot;c&quot;: -1}\n        while i &lt; n:\n            numbers[s[i]] = i\n            if numbers[&quot;a&quot;] &gt;= 0 and numbers[&quot;b&quot;] &gt;= 0 and numbers[&quot;c&quot;] &gt;= 0:\n                count += min(numbers.values()) + 1\n            i += 1\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">numberOfSubstrings<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">s<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(s)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        i = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        numbers = {<\/span><span style=\"color: #CE9178\">&quot;a&quot;<\/span><span style=\"color: #D4D4D4\">: -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;b&quot;<\/span><span style=\"color: #D4D4D4\">: -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #CE9178\">&quot;c&quot;<\/span><span style=\"color: #D4D4D4\">: -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">}<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt; n:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            numbers[s[i]] = i<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> numbers[<\/span><span style=\"color: #CE9178\">&quot;a&quot;<\/span><span style=\"color: #D4D4D4\">] &gt;= <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> numbers[<\/span><span style=\"color: #CE9178\">&quot;b&quot;<\/span><span style=\"color: #D4D4D4\">] &gt;= <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> numbers[<\/span><span style=\"color: #CE9178\">&quot;c&quot;<\/span><span style=\"color: #D4D4D4\">] &gt;= <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                count += <\/span><span style=\"color: #DCDCAA\">min<\/span><span style=\"color: #D4D4D4\">(numbers.values()) + <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            i += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-why-it-works\">Why It Works<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>At index&nbsp;<code>i<\/code>, the substring must include all three last-seen positions. The start index&nbsp;<code>s<\/code>&nbsp;must be \u2264 the&nbsp;<strong>minimum<\/strong>&nbsp;of those last-seen indices so that all three are included. Hence the number of valid starts is&nbsp;<code>min_last + 1<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"16-complexity\">Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>&nbsp;O(n) &#8211; single pass, O(1) work per character<\/li>\n\n\n\n<li><strong>Space:<\/strong>&nbsp;O(1) &#8211; only tracking three indices<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"17-dry-run-quick\">Dry Run (Quick)<\/h3>\n\n\n\n<p>Consider&nbsp;<code>s = \"abcabc\"<\/code>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>i=0 (\u2018a\u2019): last = {a:0, b:-1, c:-1} \u2192 not all present<\/li>\n\n\n\n<li>i=1 (\u2018b\u2019): last = {a:0, b:1, c:-1} \u2192 not all present<\/li>\n\n\n\n<li>i=2 (\u2018c\u2019): last = {a:0, b:1, c:2} \u2192 all present \u2192 min=0 \u2192 add 0+1=1 (substring \u201cabc\u201d)<\/li>\n\n\n\n<li>i=3 (\u2018a\u2019): last = {a:3, b:1, c:2} \u2192 min=1 \u2192 add 2 (substrings starting at 0..1: \u201cabca\u201d, \u201cbca\u201d)<\/li>\n\n\n\n<li>i=4 (\u2018b\u2019): last = {a:3, b:4, c:2} \u2192 min=2 \u2192 add 3 (starts 0..2)<\/li>\n\n\n\n<li>i=5 (\u2018c\u2019): last = {a:3, b:4, c:5} \u2192 min=3 \u2192 add 4 (starts 0..3)<\/li>\n<\/ul>\n\n\n\n<p>Total = 1 + 2 + 3 + 4 =&nbsp;<strong>10<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"18-comparison-summary\">Comparison Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Brute Force:<\/strong>&nbsp;Simple to understand; O(n^2) time; no pruning.<\/li>\n\n\n\n<li><strong>Better:<\/strong>&nbsp;Early break per start index by adding&nbsp;<strong>(n \u2212 j)<\/strong>; still O(n^2) worst-case but faster in practice.<\/li>\n\n\n\n<li><strong>Optimal:<\/strong>&nbsp;Tracks&nbsp;<strong>last seen indices<\/strong>&nbsp;of&nbsp;<code>'a'<\/code>,&nbsp;<code>'b'<\/code>,&nbsp;<code>'c'<\/code>; counts valid substrings ending at each index in O(1); total&nbsp;<strong>O(n)<\/strong>&nbsp;time,&nbsp;<strong>O(1)<\/strong>&nbsp;space.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"19-common-pitfalls-and-tips-\">Common&nbsp;<strong>Pitfalls<\/strong>&nbsp;and&nbsp;<strong>Tips<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ensure the string contains only&nbsp;<strong>&#8216;a&#8217;<\/strong>,&nbsp;<strong>&#8216;b&#8217;<\/strong>,&nbsp;<strong>&#8216;c&#8217;<\/strong>; the logic relies on exactly three characters.<\/li>\n\n\n\n<li>In the optimal approach, initialize last-seen to&nbsp;<strong>-1<\/strong>&nbsp;to mark \u201cnot seen yet.\u201d<\/li>\n\n\n\n<li>The counting formula&nbsp;<code>min(last.values()) + 1<\/code>&nbsp;is critical: it counts all valid starting indices for substrings ending at&nbsp;<code>i<\/code>.<\/li>\n\n\n\n<li>This pattern generalizes: when counting substrings that require a set of required characters, tracking&nbsp;<strong>last indices<\/strong>&nbsp;and taking the&nbsp;<strong>minimum<\/strong>&nbsp;is often a powerful technique.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"20-final-takeaway\">Final Takeaway<\/h2>\n\n\n\n<p>The optimal solution leverages&nbsp;<strong>index tracking<\/strong>&nbsp;to convert a naive O(n^2) enumeration into a slick&nbsp;<strong>O(n)<\/strong>&nbsp;scan. By updating the&nbsp;<strong>last seen positions<\/strong>&nbsp;of&nbsp;<code>'a'<\/code>,&nbsp;<code>'b'<\/code>, and&nbsp;<code>'c'<\/code>&nbsp;at each step and summing&nbsp;<code>min_last + 1<\/code>, it counts all substrings that end at every position and contain&nbsp;<strong>all three characters<\/strong>. This approach is both&nbsp;<strong>clean<\/strong>&nbsp;and&nbsp;<strong>highly efficient<\/strong> &#8211; perfect for interviews and production code.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The problem&nbsp;\u201cNumber of&nbsp;Substrings Containing All Three&nbsp;Characters\u201d&nbsp;asks: given a string&nbsp;s&nbsp;consisting&nbsp;only of the characters&nbsp;&#8216;a&#8217;,&nbsp;&#8216;b&#8217;, and&nbsp;&#8216;c&#8217;, count&nbsp;how many substrings contain&nbsp;at least one of&nbsp;each&nbsp;of these&nbsp;three characters. This is a classic&nbsp;substring counting&nbsp;problem that&nbsp;can be solved&nbsp;progressively, starting with&nbsp;a&nbsp;brute force&nbsp;approach, improved&nbsp;with a&nbsp;pruning trick, and finally&nbsp;achieving an&nbsp;O(n)&nbsp;optimal&nbsp;solution using&nbsp;last-seen indices. Here&#8217;s the [Problem Link] to begin with. Given a string&nbsp;s&nbsp;consisting only of characters&nbsp;a,&nbsp;b&nbsp;and&nbsp;c. Return<\/p>\n","protected":false},"author":1,"featured_media":932,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[19,40],"class_list":{"0":"post-931","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-medium","10":"tag-sliding-window-and-two-pointers"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/number-of-substrings-containing-all-three-characters-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/931","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=931"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/931\/revisions"}],"predecessor-version":[{"id":935,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/931\/revisions\/935"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/932"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=931"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=931"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=931"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}