Prepin
Log in

G

Invert a string.

Approach / Explanation

This inquiry essentially seeks a function that accepts a string as its input and produces a new string that is the reverse of the original. For clarification, let's use the example string "abc"; its reverse would be "cba". In addressing this question, take into account various elements like data structures, functions, and iteration methods that may be applicable. Consider the process of traversing from the end of the string to the start and how to build the reversed string accordingly.

Suggested Answer

Python offers a simple method to reverse a string using slicing. Below is an example demonstrating how to reverse a string with slicing in Python. def reverse_string ( s ) : return s [ : : - 1 ] The [::-1] slice indicates to start from the end of the string and go to position 0, stepping backwards by -1 . For instance, with the string "abc", it begins with "c", then "b", and finally "a", resulting in the reversed string "cba".

Alternative Answer

In Java , the approach is slightly different since there isn't a built-in method to reverse a string. Instead, you can convert the string into a character array and then rearrange the elements of that array. Below is an example demonstrating how to reverse a string in Java. public String reverseString ( String s ) { char [ ] word = s . toCharArray ( ) ; int i = 0 ; int j = word . length - 1 ; while ( i < j ) { char temp = word [ i ] ; word [ i ] = word [ j ] ; word [ j ] = temp ; i ++ ; j -- ; } return new String ( word ) ; } The underlying principle is to set up two pointers—one at the beginning of the string and the other at the end. You then repeatedly exchange the characters at these pointers and shift them towards the center until they converge, which ultimately gives you a reversed string.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Apple
Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.