This question is asked by Google. Given a string, reverse all of its characters and return the resulting string.
“Cat”, return “taC”
“The Daily Byte”, return "etyB yliaD ehT”
“civic”, return “civic”
🗣️ Discussion:
Thinking about the problem in real life (when possible) always seems to help. If you were asked to reverse a sequence of characters on paper, one of the approaches you might opt to take could involve moving backwards through the sequence, one letter at a time, concatenating (joining) characters together. Let’s start there and see what that kind of solution might look like.
🎯 Solution C# 6.0
public string reverse(string s) {
string reversed = "";
for (int i = s.Length - 1; i >= 0; i--) {
reversed += s.charAt(i);
}
return reversed;
}
Runtime: O(N) where N is the number of characters in our string s (because we only have to scan the string once to reverse it)Space complexity: O(N) as well (because we must create a new string with N characters in it to solve the problem).