Reversing a string is a fundamental problem in computer programming and interviewers often ask this question to test one’s understanding of basic string manipulation. There are different ways to reverse a string in various languages, but for this question, I’ll demonstrate using Python because of its simplicity and readability.
Here is a straightforward solution using Python’s slicing syntax:
def reverse_string(input_str):
return input_str[::-1]
In the above code, ‘[::-1]‘ is a slice that steps backwards, -1 step at a time, through the entire string. This effectively reverses the string.
But if you must write it from scratch without using language built-in functions, you could follow these steps:
- Define a function that takes a string as input.
- Initialize an empty string as a variable where you will store the reversed string.
- Loop through the input string from the end to the beginning.
- In each iteration append current character to the reversed string.
Here’s what the code would look like in Python:
def reverse_string(str):
reversed_str = ''
for i in range(len(str) - 1, -1, -1):
reversed_str += str[i]
return reversed_str
Another way to reverse a string, which is often seen in an interview setup, is using a stack. This method is due to the LIFO (Last In First Out) property of the stack data structure.
Here’s what the code would look like in Python:
def reverse_stringStack(input_str):
stack = list(input_str)
result = ''
while len(stack):
result += stack.pop()
return result
In the above code:
- We convert the input string to a list (i.e., a stack in Python).
- We then pop the elements from the stack one by one (which will pop from the end of the list) and append it into the result string.
- We keep doing this until the stack is empty, and return the result string which will be the reversed input string.
Please note that the time complexity for these solutions is O(n), where n is the length of the string.