What if you were asked how to write a function to reverse a given string?
What if you were asked how to write a function to reverse a given string?
Can you solve it if you were asked about it in an interview tomorrow?
To reverse a string, you need to write a function that takes the input and outputs the reversed version of your string.
For example, if the input string is "hello," the function should return "olleh." Simple enough, right?
Here’s the issue, you are going to be expected to be able to write this without using a built in reverse method. And ou’ll be expected to talk about how to optimize it and why you chose that approach.
These types of questions can seem boring but they can help you solve much more complex problems later! And they are the building blocks of a solid technical interview.
Let’s dive in!
Here’s the expected input and output.
Let’s talk about the pseudocode first.
To reverse a string, we can follow these steps:
1. Define a function `reverseString` that takes a string as the argument.
2. Create an empty string variable, let's call it….. `reversedString`.
3. Next, iterate over the characters of the string from the very last character to the first. And for each character, append it to the `reversedString`.
4. Finally, return the `reversedString`.
Why don’t you try to solve it on your own first before we go on?
I’ll wait…
…..
Got it?
If not, that’s ok!
Let’s talk about how to implement this in JavaScript.
1. Our function `reverseString` takes a string `str` as an argument.
2. Next, we create an empty string variable `reversedString` to store our reversed string.
3. Using a for loop, we loop over the characters of the input string `str` from the last character to the very first.
4. Inside our loop, we append each character from `str` to the `reversedString` variable.
5. Finally, we return the `reversedString`
Okay cool so we’ve talked about the implementation but could you talk about the complexity?
Our approach using a loop will have a time complexity of O(n), where n is simply the length of the input string.