Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

904. Fruit Into Baskets

Medium45.2% Acceptance
ArrayHash TableSliding Window
Asked by:
A
Amazon
ProblemSolutions (6)VideosCompanies (1)Notes

Problem Statement

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 fruits where fruits[i] is the type of fruit the ith tree produces.

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

  • You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
  • Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
  • Once you reach a tree with fruit that cannot fit in your baskets, you must stop.

Given the integer array fruits, return the maximum number of fruits you can pick.

Example 1:

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2:

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].

Example 3:

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].

Constraints:

  • 1 <= fruits.length <= 105
  • 0 <= fruits[i] < fruits.length
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions

Approach

The key idea in Fruit Into Baskets is to find the longest contiguous subarray containing at most two distinct fruit types. This naturally leads to the Sliding Window technique. As you traverse the array, maintain a window that represents the current set of trees you are collecting fruits from.

Use a hash table (or map) to track the count of each fruit type within the current window. Expand the window by moving the right pointer, and whenever the number of distinct fruit types exceeds two, shrink the window from the left until the constraint is satisfied again. During this process, keep updating the maximum window size found.

This approach works efficiently because each element enters and leaves the window at most once. As a result, the algorithm runs in O(n) time while using O(1) extra space since the map stores at most two fruit types.

Complexity

ApproachTime ComplexitySpace Complexity
Sliding Window with Hash MapO(n)O(1)

Video Solution Available

take U forward

View all video solutions

Solutions (6)

Sliding Window with HashMap

The sliding window technique is effective for problems involving contiguous subarrays. The goal is to maintain two baskets each holding one type of fruit. We'll use a hashmap to track the count of each fruit type in our current window. When encountering a third type of fruit, shrink the window from the left until only two types remain.

Time Complexity: O(n), where n is the length of the fruits array, as each element is processed at most twice (once added and once removed).
Space Complexity: O(1), as the hashmap will hold at most three entries at any time, which is constant space.

PythonC++JavaC#JavaScript
1def totalFruit(fruits):
2    basket = {}
3    left = 0
4    max_fruits = 0
5    for right, fruit in enumerate(fruits):
6        basket[fruit] = basket.get(fruit, 0) + 1
7        while len(basket) > 2:
8            basket[fruits[left]] -= 1
9            if basket[fruits[left]] == 0:
10                del basket[fruits[left]]
11            left += 1
12        max_fruits = max(max_fruits, right - left + 1)
13    return max_fruits

Explanation

This code uses a sliding window approach with a hashmap to keep track of fruit counts. The window expands by incrementing 'right' and shrinks from 'left' when more than two types of fruits are in the window. The 'max_fruits' variable is updated with the size of the largest valid window found.

Two Pointer Technique

This approach employs two pointers to define the current valid subarray and efficiently manage the types of fruits in each basket. By maintaining direct pointers to the position where the current types of fruits change, the solution dynamically adjusts the size of the valid subarray.

Time Complexity: O(n), as we ensure each element is considered just a limited number of times.
Space Complexity: O(1), since the additional storage for control variables is constant.

1def totalFruit(fruits):
2    n = len(fruits)
3

Video Solutions

Watch expert explanations and walkthroughs

L5. Fruit Into Baskets | 2 Pointers and Sliding Window Playlist

take U forward
30:02128,628 views

Asked By Companies

1 companies
A
Amazon

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Two SumEasy
Valid SudokuMedium
Sudoku SolverHard
First Missing PositiveHard
More similar problems

Related Topics

ArrayHash TableSliding Window

Problem Stats

Acceptance Rate45.2%
DifficultyMedium
Companies1

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Fruit Into Baskets asked in FAANG interviews?

Yes, this problem is considered a classic sliding window interview question and has appeared in interviews at large tech companies. It tests understanding of two-pointer techniques, hash maps, and window management.

What data structure is best for Fruit Into Baskets?

A hash map (or dictionary) is commonly used to track the count of fruit types inside the sliding window. It helps quickly determine when more than two distinct fruits are present and when to shrink the window.

What is the optimal approach for Fruit Into Baskets?

The optimal approach uses the sliding window technique with a hash map to track fruit counts. The window expands while there are at most two fruit types and shrinks when the constraint is violated. This ensures linear time processing of the array.

Why is sliding window suitable for Fruit Into Baskets?

Sliding window works well because the problem asks for the longest contiguous segment with a constraint on distinct elements. By dynamically expanding and shrinking the window, you can efficiently maintain valid subarrays without reprocessing elements.

if
n
<
3
:
return
n
4
left
,
right
=
0
,
0
5
basket
=
{
}
6
max_fruits
=
0
7
while
right
<
n
:
8
if
fruits
[
right
]
in
basket
or
len
(
basket
)
<
2
:
9
basket
[
fruits
[
right
]
]
=
right
10
right
+=
1
11
else
:
12
min_index
=
min
(
basket
.
values
(
)
)
13
del
basket
[
fruits
[
min_index
]
]
14
left
=
min_index
+
1
15
max_fruits
=
max
(
max_fruits
,
right
-
left
)
16
return
max_fruits

Explanation

This Python function uses two pointers to dynamically track potential subarrays with at most two different types of fruits. The dict `basket` tracks the latest positions of the current fruit types, allowing direct jumps in the array and optimizing the process of finding a new valid window.