Prepin
Log in

Invert a Sentence

Approach / Explanation

This question requires you to create a function or algorithm that takes a sentence, represented as a string of words separated by spaces, and returns a new string with the words in reverse order. This means that the first word will become the last, the second word will be the second to last, and so on. Here are some key points to keep in mind while solving this: Make sure to handle instances of multiple spaces between words in the input sentence. Think about how to address the end of the sentence, particularly if it lacks a space. Consider whether capitalization is relevant in this situation. Indicate the programming language you will use to implement the solution.

Suggested Answer

Let's create a solution using Python : def reverse_sentence ( sentence : str ) - > str : words_list = sentence . split ( ) # Break the sentence into a list of words reverse_words_list = words_list [ : : - 1 ] # Reverse the order of words reversed_sentence = ' ' . join ( reverse_words_list ) # Combine reversed words into a single string separated by spaces return reversed_sentence In the code provided, we first divide the sentence into a list of individual words, then reverse that list, and finally, we combine the words back into a string with spaces in between. The Python list slicing method [::-1] is an effective way to reverse a list.

Alternative Answer

Here’s another illustration using JavaScript : function reverseSentence ( sentence ) { var words = sentence . split ( ' ' ) ; // Split the sentence into an array of words var reverseWords = words . reverse ( ) ; // Reverse the array of words var reversedSentence = reverseWords . join ( ' ' ) ; // Combine reversed words into a string with spaces return reversedSentence ; } This JavaScript example employs a method similar to that used in Python. We break the sentence into an array of words, reverse this array, and subsequently reassemble it into a string. The main distinction lies in the utilization of JavaScript Array methods .split() , .reverse() , and .join() , which handle the more complex operations for us.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Microsoft

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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