Programming basics · Build it
Reverse a string without library functions
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Write a function that reverses a string in place, without using any library function for reversing. Then use the same idea to check whether a string is a palindrome.
Then
Follow-ups the interviewer asks next
- What are the time and space complexity?
- How does your code handle an empty string and a single character?
- Make the palindrome check ignore spaces and capital letters, so "Never odd or even" counts.
- Now reverse the order of words instead: "I love coding" becomes "coding love I".
- Strings can't be changed in Java. How would you do it there?
The answer
What a strong answer covers
- Two indexes: i from the start and j from the end; swap
s[i]ands[j], move both inward, stop when i is no longer less than j. O(n) time, O(1) extra space. - In C, find the length by walking to '\0' if strlen isn't allowed either.
- Empty and one-character strings: the loop never runs, which is correct.
- Palindrome: compare
s[i]ands[j]moving inward and stop at the first difference; no reversed copy needed. - Ignoring case and spaces: skip characters that aren't letters or digits (isalnum) and compare lowercase versions (tolower).
- Reversing words: reverse the whole string, then reverse each word; still O(n).
- Java: copy to a char array (toCharArray), swap, and make a new String; StringBuilder's reverse if libraries are allowed. Building the result with
+in a loop is O(n²). - Byte-by-byte reversal breaks text with multi-byte characters, such as Hindi in UTF-8: a good point to mention.
The red pen
Common traps
Avoid:off-by-one errors (starting j at the length); using a library reverse after being told not to; building a reversed copy just to compare when two indexes are enough.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.