Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
I found the map solution a bit hard to follow. Here is an alternative if it help...

Jeff Goyette

Nov 10, 2022

I found the map solution a bit hard to follow. Here is an alternative if it helps anyone. In this, I use a list to keep track of the added fruit, and a set to keep track of types of fruit. Functionally this isn't much different than using a map. This does get rid of the windows though.

char[] fruitArr1 = new char[] {'A', 'B', 'C', 'B', 'B', 'C'};

int maxLength = 0;

List fruitBasket = new ArrayList(); Set uniqueFruit = new HashSet();

for (char fruit1 : fruitArr1) { fruitBasket.add(fruit1); uniqueFruit.add(fruit1);

while (uniqueFruit.size() > 2) { uniqueFruit.remove(fruitBasket.remove(0)); } maxLength = Math.max(maxLength, fruitBasket.size()); System.out.println(fruitBasket); System.out.println(maxLength); }

0

0

Comments
Comments
A
Anthony DiFede3 years ago

this is pretty nice

On this page