But it doesn't have to end here! Sign up for the 7-day coding interview crash course and you'll get a free Interview Cake problem every week.
You're in!
You're running the tasting table at a bakery festival.
Cupcakes ride past on a conveyor belt, and each one has a one-letter flavor label: c for chocolate, v for vanilla, s for strawberry, l for lemon, r for red velvet, m for mocha, and so on. The labels come to you as a string, in the order the cupcakes are lined up on the belt.
Our pickiest taster wants to eat a run of cupcakes that are next to each other on the belt, and refuses to taste the same flavor twice in one run.
Write a method longestNoRepeatRun that takes the string of flavor labels and returns the length of the longest run of consecutive cupcakes with no repeated flavor. In other words, find the length of the longest substring without repeating characters.
For example:
If the belt is empty (an empty string), return 0.
The cupcakes in a run have to be next to each other on the belt. We're looking for a substring, not a subsequence: the taster can't skip a cupcake to avoid a repeat.
Try your method on "cvvc". The answer is 2. Does yours get it?
Make sure your method handles an empty string.
We can do this in O(n) time.
Log in or sign up with one click to get immediate access to free mock interview questions
We'll never post on your wall or message your friends.
Actually, we don't support password-based login. Never have. Just the OAuth methods above. Why?
Log in or sign up with one click to get immediate access to free mock interview questions
We'll never post on your wall or message your friends.
Actually, we don't support password-based login. Never have. Just the OAuth methods above. Why?
O(n) time and O(min(n, m)) space, where n is the number of cupcakes on the belt and m is the number of different flavor labels there could be.
We go through the loop once per cupcake, and each time through we do a constant amount of work: a lookup and an update in lastSeen (each O(1) on average in a hash map) and a little arithmetic.
lastSeen holds one entry for each different flavor we've seen. That's never more than n (if every cupcake is different), and never more than m (there are only so many flavors). So it's O(min(n, m)).
If we knew the labels were always lowercase letters, we could make lastSeen an array of 26 indexes instead, one for each letter. That takes O(1) space, since its size doesn't depend on the input.
Log in or sign up with one click to get immediate access to free mock interview questions
We'll never post on your wall or message your friends.
Actually, we don't support password-based login. Never have. Just the OAuth methods above. Why?
Reset editor