On Interviewer Mindset
Today on AlgoDaily, we're going to reverse a string. Reversing a string is one of the most common technical interview questions that candidates get. Interviewers love it because it's deceptively simple. After all, as a software engineer, you'd probably call the #reverse
method on your favorite String
class and call it a day!
So don't overlook this one-- it appears a surprising amount as a warm-up or build-up question. Many interviewers will take the approach of using an easy question like this one, and actually judge much more harshly. You'll want to make you sure really nail this.
How We'll Begin Solving
We want the string reversed, which means that we end up with all our letters positioned backwards. If you need a quick review of string
s, check out our lesson on arrays and strings.
We know that string
s can be thought of as character arrays-- that is, each element in the array is a single character. And if we can assume that, then we know the location (array position) of each character, as well as the index when the array
ends.
There's a caveat to thinking of strings as character arrays-- it's not always true. As readers and viewers have pointed out, a string represents text formed from graphemes (the smallest functional unit of a writing system)-- formed by combining character sequences in unicode.
Though strings and arrays contain similar methods like length
, concat
, and character position access-- they are not identical. As an example, arrays are mutable and strings usually are not. Before we can operate on the string as an array, we'll need to separate the units (in JS by calling the .split()
method, or bypass this property by generating a brand new string instead of trying to operate on the original.
However, after the split
operation, we can apply that paradigm to operating on this string. Thus we can step through each of its indices. Stepping through the beginning of the string, we'll make these observations at each point:

1str = "JAKE"
2# position 0 - "J"
3# position 1 - "A"
4# ...
Since a reversed string is just itself backwards, a brute force solution could be to use the indices, and iterate from the back to the front.
See the code attached and try to run it using Run Sample Code
. You'll see that we log out each character from the back of the string!
xxxxxxxxxx
def reverse_str(s):
new_str = ""
i = len(s)
while i > 0:
new_str += s[ i - 1 ]
i = i - 1
return new_str
print(reverse_str("jake"))