Earlier quoted context omitted.
It might be an incredibly common interview question, but it's not an incredibly common day-to-day task, particularly when there are methods built in to classes that perform this function. An interesting task? Perhaps. But not reflection of the dev's skills, per se. You're not asking about syntax with this. It's a problem solving question and at the end of the day, the only real metric here is not whether a dev could…
I don't see how reversing a string is a "puzzle" - I'd put its difficulty on par (or maybe slightly harder than) fizzbuzz. In most mainstream languages, it requires 2 pieces of knowledge: 1) That a string is implemented as an array of characters. 2) How to reverse an array. The implementation is straightforward and should be trivial for just about anyone who's done much development. I don't know that the question is…
Here's my solution:
def reverse() {
def a = "Can a fella get a job?"
StringBuilder b = new StringBuilder()
for (int i = a.length(); i > 0; i--) {
b.append(a.charAt(i-1))
}
print b.toString()
}But it doesn't use arrays because quite frankly, I haven't used an array in years. I despise the noise of the brackets. :-)
Seriously, I use ArrayLists instead of arrays. But even on this FizzBuzz lite exercise, I got tripped up. My "i > 0" was off by one. And I started down the path of a.substring, but that was a bad move. I quickly switched to charAt.
But about the only relevant piece of this: on an IDE, I was able to place a breakpoint, see where I'm at, what my variables look like, and make adjustments.
That's real life. My original cut of this would have disqualified me. Actually, even the cut above would disqualify me since I didn't use arrays.
But I need to confess. What you see above is literally the first time I've ever reversed a string in this manner. It's just not something I do. And it didn't roll off the tongue so to speak. I knew I had to process the string from the end and work backwards, but it still felt like trivia and not a substantive inquisition into my skills or experience.
Trivial? A bit. It took me about 5 min. The off by one was killing me. It hits you in two places: the i > 0 and the charAt(i-1).