This is an interview problem that I am stuck on:
Given a string consisting of a, b and c\'s, we can perform the following operation: Take any two adjacent
Pattern matching in Scala makes it easier to pick apart lists of items like this. To reduce the string:
def reduce[T](xs: List[T]): List[T] = {
def reduceImpl(xs1: List[T], accumulator: List[T] = List.empty): List[T] = {
xs1 match {
case w :: x :: y :: tail if (w != x) =>
if (w != x) reduceImpl(y :: tail, accumulator)
else reduceImpl(x :: y :: tail, w :: accumulator)
case remainder =>
remainder.reverse ::: accumulator
}
}
reduceImpl(xs).reverse
}
And then you can just call length on the result.
And yes, I'd give this answer for a Java question. 99 times out of 100 the interviewer couldn't care less what language you use to talk about code, and using things like Scala, Clojure, F# etc are the right way to go. (Or if not, they're the right way to figure out you don't actually want to work there.)
(And also yes, the people who said the answer is a number are correct. However, like everyone else said, this is more about an interview question, and it's probably correct to say that what they asked isn't what they wanted to ask. It's a (small) bad sign for working there if this is a standard question they use more than once. If they're using this question in an automated screen, that's really not a good sign.)