Back on the topic of possible programming interview questions, you may at some time in your career be asked to reverse words in a string. This is a much simpler problem and may be more likely to appear on a technical phone screening.
In it’s simplest form, you would assume all space separated string collections to be words. To clarify, it doesn’t matter if you’re looking at a true word or just some jumbled text separated by a space character.
This problem can be solved in just a few lines of JavaScript, but our logic will be as follows:
Lucky for us, in Java and JavaScript we don’t have to worry about coming up with our own string splitting algorithm. In both these languages you can do String.split(delimiter)
to split the string into an array.
function StringUtil() {
this.reverseWords = function(str) {
var result = "";
var wordArray = str.split(" ");
for(var i = wordArray.length - 1; i >= 0; i--) {
result += wordArray[i] + " ";
}
return result.trim();
}
}
If you really wanted to go the extra mile and do the grunt work, you could create a split string function that would look like this:
String.prototype.splitStr = function(delimiter) {
var stringArray = [];
var tempStr = "";
for(var i = 0; i < this.length; i++) {
if(this.charAt(i) === delimiter) {
stringArray.push(tempStr);
tempStr = "";
} else {
tempStr += this.charAt(i);
}
}
if(tempStr !== "") {
stringArray.push(tempStr);
}
return stringArray;
}
The above code will be slightly different for Java because you’d be using a StringBuilder
instead, but for the most part it is the same.
This is a small and simple algorithm that is very likely to be asked on a technical phone screening rather than a technical interview. You could take the short route in solving this problem, or take the impressive extra mile approach by designing the split string algorithm.