Interview Camp: Level: Medium
Interview Camp: Level: Medium
Interview Camp
Note: This solution uses Enums and Exceptions. While optional, it always looks good if you use them in an
interview.
You're given a list of Marbles. Each marble can have one of 3 colors (Red, White or Blue).
Arrange the marbles in order of the colors (Red -> White -> Blue).
Colors are represented as follows:
0 - Red
1 - White
2 - Blue
Questions to Clarify:
Q. What to do if the input has an unknown color?
A. Throw an Exception
Q. Do I need to move around the existing elements of the array, or can I count the elements (for
example, 4 zeros) and then fill them up in a new array?
A. Yes, you need to move elements around. A marble is represented as an integer in this problem, but
in
reality there might be more information about a marble in each element.
Solution:
This is very similar to the Dutch National Flag problem. You will use the same solution,
with 2 pointers - one tracking low_boundary and one tracking high_boundary.
Only white marbles will be left in the middle.
Pseudocode:
(Note: Never write pseudocode in an actual interview. Unless you're writing a
few lines quickly to plan out your solution. Your actual solution should be in
a real language and use good syntax.)
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Test Cases:
Edge Cases: empty array, null array, invalid color
Base Cases: single element, two elements
Regular Cases: list has element with - all 3 colors, only 2 colors, only 1 color
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Color(int colorId) {
this.colorId = colorId;
}
© 2017 Interview Camp (interviewcamp.io)