{"id":917,"date":"2025-08-20T12:50:21","date_gmt":"2025-08-20T07:20:21","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=917"},"modified":"2025-08-20T12:53:47","modified_gmt":"2025-08-20T07:23:47","slug":"fruit-into-baskets","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/","title":{"rendered":"Fruit Into Baskets | Leetcode 904 | Optimal Solution using Sliding Window"},"content":{"rendered":"\n<p>The problem&nbsp;<strong>\u201cFruit Into Baskets\u201d<\/strong>&nbsp;asks for the length of the longest contiguous subarray that contains at most&nbsp;<strong>two distinct fruit types<\/strong>. Think of it as carrying fruits in two baskets, each basket can hold only a single type, and you want to collect the&nbsp;<strong>maximum number of fruits<\/strong>&nbsp;from a continuous row of trees.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/fruit-into-baskets\/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>You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array&nbsp;<code>fruits<\/code>&nbsp;where&nbsp;<code>fruits[i]<\/code>&nbsp;is the&nbsp;<strong>type<\/strong>&nbsp;of fruit the&nbsp;<code>i<sup>th<\/sup><\/code>&nbsp;tree produces.<\/p>\n\n\n\n<p>You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You only have&nbsp;<strong>two<\/strong>&nbsp;baskets, and each basket can only hold a&nbsp;<strong>single type<\/strong>&nbsp;of fruit. There is no limit on the amount of fruit each basket can hold.<\/li>\n\n\n\n<li>Starting from any tree of your choice, you must pick&nbsp;<strong>exactly one fruit<\/strong>&nbsp;from&nbsp;<strong>every<\/strong>&nbsp;tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.<\/li>\n\n\n\n<li>Once you reach a tree with fruit that cannot fit in your baskets, you must stop.<\/li>\n<\/ul>\n\n\n\n<p>Given the integer array&nbsp;<code>fruits<\/code>, return&nbsp;<em>the&nbsp;<strong>maximum<\/strong>&nbsp;number of fruits you can pick<\/em>.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> fruits = [1,2,1]<br><strong>Output:<\/strong> 3<br><strong>Explanation:<\/strong> We can pick from all 3 trees.<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> fruits = [0,1,2,2]<br><strong>Output:<\/strong> 3<br><strong>Explanation:<\/strong> We can pick from trees [1,2,2].<br>If we had started at the first tree, we would only pick from trees [0,1].<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> fruits = [1,2,3,2,2]<br><strong>Output:<\/strong> 4<br><strong>Explanation:<\/strong> We can pick from trees [2,3,2,2].<br>If we had started at the first tree, we would only pick from trees [1,2].<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= fruits.length &lt;= 10<sup>5<\/sup><\/code><\/li>\n\n\n\n<li><code>0 &lt;= fruits[i] &lt; fruits.length<\/code><\/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-c47b1d4f-e263-46c6-91ba-83e44a2c8060\" 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\/fruit-into-baskets\/#0-brute-force-check-all-subarrays-\" style=\"\">Brute Force (Check All Subarrays)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#2-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#3-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#4-when-to-use\" style=\"\">When to Use<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#5-better-sliding-window-with-shrink-loop-\" style=\"\">Better (Sliding Window with Shrink Loop)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#6-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#7-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#8-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#9-why-it-works\" style=\"\">Why It Works<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#10-optimal-tight-sliding-window-\" style=\"\">Optimal (Tight Sliding Window)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#11-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#12-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#13-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#14-why-this-is-optimal\" style=\"\">Why This Is Optimal<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#15-common-pitfalls-and-tips-\" style=\"\">Common\u00a0Pitfalls\u00a0and\u00a0Tips<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/fruit-into-baskets\/#16-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-all-subarrays-\">Brute Force (<strong>Check All Subarrays<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For each start index&nbsp;<code>i<\/code>, expand&nbsp;<code>j<\/code>&nbsp;to the right and keep track of distinct fruit types in a set.<\/li>\n\n\n\n<li>If the set size exceeds&nbsp;<strong>2<\/strong>, stop expanding and move to the next start.<\/li>\n\n\n\n<li>Track the&nbsp;<strong>maximum window length<\/strong>&nbsp;while valid.<\/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 totalFruit(self, fruits: List[int]) -&gt; int:\n        n = len(fruits)\n        max_length = 0\n        for i in range(n):\n            my_set = set()\n            for j in range(i, n):\n                my_set.add(fruits[j])\n                if len(my_set) &gt; 2:\n                    break\n                max_length = max(max_length, j - i + 1)\n        return max_length\" 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\">totalFruit<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">fruits<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/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\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(fruits)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        max_length = <\/span><span style=\"color: #B5CEA8\">0<\/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\">            my_set = <\/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\">                my_set.add(fruits[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\">(my_set) &gt; <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">:<\/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\">                max_length = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(max_length, j - i + <\/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\">return<\/span><span style=\"color: #D4D4D4\"> max_length<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong>: O(n^2)<\/li>\n\n\n\n<li><strong>Space<\/strong>: O(1) to O(2) for the set (bounded by 2 distinct types)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-when-to-use\">When to Use<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Good for understanding, but not efficient for large inputs.<\/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=\"5-better-sliding-window-with-shrink-loop-\">Better (<strong>Sliding Window with Shrink Loop<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use two pointers (<code>left<\/code>,&nbsp;<code>right<\/code>) and a frequency dictionary to count fruit types in the window.<\/li>\n\n\n\n<li>Expand&nbsp;<code>right<\/code>&nbsp;and include&nbsp;<code>fruits[right]<\/code>.<\/li>\n\n\n\n<li>While there are more than&nbsp;<strong>2 types<\/strong>, shrink from&nbsp;<code>left<\/code>, decrementing counts and removing types with zero count.<\/li>\n\n\n\n<li>After restoring the constraint (\u22642 types), update the maximum window length.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-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 totalFruit(self, fruits: List[int]) -&gt; int:\n        my_set = {}\n        left = 0\n        right = 0\n        n = len(fruits)\n        max_length = 0\n        while right &lt; n:\n            my_set[fruits[right]] = my_set.get(fruits[right], 0) + 1\n            while len(my_set) &gt; 2:\n                my_set[fruits[left]] -= 1\n                if my_set[fruits[left]] == 0:\n                    del my_set[fruits[left]]\n                left += 1\n            max_length = max(max_length, right - left + 1)\n            right = right + 1\n        return max_length\" 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\">totalFruit<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">fruits<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/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\">        my_set = {}<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        left = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        right = <\/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\">(fruits)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        max_length = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> right &lt; n:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            my_set[fruits[right]] = my_set.get(fruits[right], <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">) + <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(my_set) &gt; <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                my_set[fruits[left]] -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> my_set[fruits[left]] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">del<\/span><span style=\"color: #D4D4D4\"> my_set[fruits[left]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                left += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            max_length = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(max_length, right - left + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            right = right + <\/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\"> max_length<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong>: O(n)<\/li>\n\n\n\n<li><strong>Space<\/strong>: O(2) \u2192 effectively O(1), since at most two distinct types are kept<\/li>\n<\/ul>\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>The window always maintains&nbsp;<strong>at most two types<\/strong>&nbsp;by shrinking when necessary, ensuring linear traversal.<\/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=\"10-optimal-tight-sliding-window-\">Optimal (<strong>Tight Sliding Window<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Same core idea as \u201cBetter,\u201d with slightly tighter checks:\n<ul class=\"wp-block-list\">\n<li>Add&nbsp;<code>fruits[right]<\/code>&nbsp;and, if distinct types exceed&nbsp;<strong>2<\/strong>, shrink once from&nbsp;<code>left<\/code>.<\/li>\n\n\n\n<li>After ensuring \u22642 types, update&nbsp;<code>max_length<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-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 totalFruit(self, fruits: List[int]) -&gt; int:\n        my_set = {}\n        left = 0\n        right = 0\n        n = len(fruits)\n        max_length = 0\n        while right &lt; n:\n            my_set[fruits[right]] = my_set.get(fruits[right], 0) + 1\n            if len(my_set) &gt; 2:\n                my_set[fruits[left]] -= 1\n                if my_set[fruits[left]] == 0:\n                    del my_set[fruits[left]]\n                left += 1\n            if len(my_set) &lt;= 2:\n                max_length = max(max_length, right - left + 1)\n            right = right + 1\n        return max_length\" 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\">totalFruit<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">fruits<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/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\">        my_set = {}<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        left = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        right = <\/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\">(fruits)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        max_length = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> right &lt; n:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            my_set[fruits[right]] = my_set.get(fruits[right], <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">) + <\/span><span style=\"color: #B5CEA8\">1<\/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\">(my_set) &gt; <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                my_set[fruits[left]] -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> my_set[fruits[left]] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">del<\/span><span style=\"color: #D4D4D4\"> my_set[fruits[left]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                left += <\/span><span style=\"color: #B5CEA8\">1<\/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\">(my_set) &lt;= <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                max_length = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(max_length, right - left + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            right = right + <\/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\"> max_length<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong>: O(n)<\/li>\n\n\n\n<li><strong>Space<\/strong>: O(1) (bounded by 2 types)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-why-this-is-optimal\">Why This Is Optimal<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Each index is visited at most twice (by&nbsp;<code>right<\/code>&nbsp;and possibly by&nbsp;<code>left<\/code>), giving&nbsp;<strong>linear time<\/strong>&nbsp;and&nbsp;<strong>constant extra space<\/strong>.<\/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=\"15-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>Always adjust&nbsp;<code>left<\/code>&nbsp;until the window has&nbsp;<strong>\u22642 distinct types<\/strong>.<\/li>\n\n\n\n<li>Use a&nbsp;<strong>frequency map<\/strong>&nbsp;to know when to&nbsp;<strong>delete<\/strong>&nbsp;a type (count reaches zero).<\/li>\n\n\n\n<li>Works for any non-negative integers as fruit types; order matters since we need a&nbsp;<strong>contiguous<\/strong>&nbsp;segment.<\/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=\"16-final-takeaway\">Final Takeaway<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use&nbsp;<strong>Brute Force<\/strong>&nbsp;for learning.<\/li>\n\n\n\n<li>Prefer the&nbsp;<strong>Sliding Window<\/strong>&nbsp;solutions (<strong>Better<\/strong>\/<strong>Optimal<\/strong>) for&nbsp;<strong>O(n)<\/strong>&nbsp;performance and&nbsp;<strong>O(1)<\/strong>&nbsp;space.<\/li>\n\n\n\n<li>This pattern generalizes to \u201clongest subarray with at most K distinct elements\u201d &#8211; here&nbsp;<strong>K = 2<\/strong>, a very common and powerful template in array\/string problems.<\/li>\n<\/ul>\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;\u201cFruit Into Baskets\u201d&nbsp;asks for the length of the longest contiguous subarray that contains at most&nbsp;two distinct fruit types. Think of it as carrying fruits in two baskets, each basket can hold only a single type, and you want to collect the&nbsp;maximum number of fruits&nbsp;from a continuous row of trees. Here&#8217;s the [Problem Link] to<\/p>\n","protected":false},"author":1,"featured_media":918,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[19,40],"class_list":{"0":"post-917","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\/fruit-into-baskets-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\/917","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=917"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/917\/revisions"}],"predecessor-version":[{"id":921,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/917\/revisions\/921"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/918"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=917"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=917"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=917"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}