In Python, without using built‑in functions, write a function to reverse a string.
💡 Model Answer
To reverse a string in Python without built‑in functions, you can iterate over the string from the end to the beginning and build a new string character by character. One common approach is to use a while loop with an index that starts at the last character and decrements until it reaches the first. At each step, you concatenate the current character to a result string. This method avoids slicing or the reversed() built‑in. The time complexity is O(n) because each character is processed once, and the space complexity is also O(n) for the new string. Here’s a concise implementation:
def reverse_string(s):
result = ''
i = len(s) - 1
while i >= 0:
result += s[i]
i -= 1
return resultThis function works for any string, including empty strings and Unicode characters. It demonstrates fundamental string manipulation and control flow, which are essential skills for a junior Python developer.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500