Feature #13: Reverse Commands
Implement the "Reverse Commands" feature for our "Operating System" project.
Description
We use a command history log file to archive the commands issued by the user. The logging module stores each command word by word in the log file. However, a bug caused the logging module to store the commands in an incorrect order. Instead of appending the commands in the string, it prepended them and added extra spaces. Now, all of the commands are in reverse order. For example, we have "*.html pages.tar.gz czvf tar"
instead of "tar czvf pages.tar.gz *.html"
. Our task is to reverse them back to normal.
Here are the tasks that we will have to perform:
- Trim the string for leading and trailing spaces.
- Remove multiple spaces between commands.
- Reverse the string.
We will be given a string containing the commands and we will have to return the reversed string. Let’s look at a few examples of this:
Solution
We will use the built-in functions to solve this problem. All of these functions will take the optimal time and space complexity.
Here is the algorithm that we will use:
- Trim the leading and trailing spaces.
- Split the words into spaces. Keep in mind that there might be more than one space between each word.
- Reverse the array of strings.
- Convert the reversed array into a string and return it.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.