Solution critique: reversing words in a sentence

reverse words in a sentence
reverse words in a sentence python
c program to reverse the order of words in a sentence
reverse words in a sentence java
reverse each word in a string c++
reverse words in a string in c using pointers
reverse words in a string java without using functions
reverse words in a string ii

I had a technical interview and was given the following question:

Write a function that takes a sentence and returns the sentence with the words in reverse order (i.e. "hello world" becomes "world hello").

Here is the solution that I gave in Java:

/** Takes a sentence as an input and returns the sentence with the words in
 *  reversed order. */
private static String reverseSentence(String sentence) {
    String[] words = sentence.split("\\s+");
    String reversedString = "";
    for (int k = words.length - 1; k >= 0; k -= 1) {
        reversedString += " " + words[k];
    }
    return reversedString.substring(1);
}

I got to thinking that there has to be a more efficient way to solve this problem than this. I don't see this being asked in a technical interview for a top company if this solution turns out to be the best one and there isn't one more efficient/elegant.

Can anyone think of a better way to do this?

Here are better ways to concatenate the elements of the sentence: What's the most elegant way to concatenate a list of values with delimiter in Java?

Also, sentence.split("\\s+") only works when the input is clean (people do make typos). There is also the questions what should happen to punctuation. World! Hello, does look very odd.

How to Reverse a String in place in Java - Example, How do you reverse a word in a sentence in C? All your code in one place. Over 40 million developers use GitHub together to host and review code, project manage, and build software together across more than 100 million projects. Sign up for free See pricing for teams and enterprises. Iterative Java solution to reversing words in a sentence.

Except the comment, to use a more efficient data structure (StringBuilder) to create the string, I don't think there is much you can do. The time complexity to reverse an array is n/2 (How do I reverse an int array in Java?) but afterwards you would still need to concatenate all of the items, which should be n - since you're concatenating them right away you get down from 3n/2 to only n.

Reverse words in a given string, How do you reverse words in a sentence in Python? Programming Interview Questions 12: Reverse Words in a String. being contrived to exist for many projects simply so it can be run will be the first to hit the wall, but those projects where the functions to make existing transactions cheaper in real world applications will find the elusive real world demand.

Once you have reversed the array by swapping references (0 with length-1, etc) you can

String reversedSentence = String.join( " ", words );

But I think it is better to avoid a String array.

String s = "the quick brown fox";
StringBuilder sb = new StringBuilder();
int p = s.length();
int np = -1;
while( (np = s.lastIndexOf( " ", p-1 )) != -1 ){
    sb.append( s.substring( np + 1, p ) ).append( " " );
    p = np; 
}
sb.append( s.substring( 0, p ) );
System.out.println( sb.toString() );

This assumes that the input string is properly "normalized".

Reverse words in a given String in Python, Initially, reverse the individual words of the given string one by one, for the above example, after Function to reverse words*/ Solution proposed bu Uttam  Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”. Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Sometimes this question is asked with a constraint asking for it to be done without using any extra memory.

One answer to this modified question is:

  1. First reverse each word in the sentence ("Hello World" -> "olleH dlroW")
  2. Then reverse the entire sentence ("olleH dlroW" -> "World Hello")

How to reverse the order of words in a sentence, Asymptotic Analysis · Worst, Average and Best Cases · Asymptotic Notations · Little o and little omega This problem has existing solution please refer Reverse words in a given String link. Print words of list, in string form after joining each word with space using ” “.join() method in python. def rev_sentence(sentence):. Write a function that takes a sentence and returns the sentence with the words in reverse order (i.e. "hello world" becomes "world hello"). Here is the solution that I gave in Java:

Reverse the words in a sentence – C++ solution and test code, Implementation. One interesting thing about this problem is that all of its solutions are very language-dependent. Consider the implementations shown below: C++. Given a long sentence, reverse each word of the sentence individually in the sentence itself. Examples: Input : Geeks For Geeks is good to learn Output : skeeG roF skeeG si doog ot nrael Input : Split Reverse Join Output : tilpS esreveR nioJ

Reverse words in a sentence., Here is a solution to the standard interview questions of reversing the letters in the words of a sentence. It is a more complex version of the even  In water-cooled condensers it is usual to arrange that the water passes through a large number of small pipes contained in a larger one through which the gas flows, and as it constantly happened that condenser pipes became choked by naphthalene, the so-called reversible condenser, in which the stream of gas may be altered from time to time and the walls of the pipes cleaned by pumping tar over

Interview solutions to reverse a string and reverse a sentence , Reverse words in a sentence. Ex: 2, reverse every word in the sentence code: Solution using recursive approach without modifying the original content. A word is defined as a sequence of non-space characters. Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. You need to reduce multiple spaces between two words to a single space in the reversed string. Follow up:

Comments
  • Ya.. Use a StringBuilder instead of String reversedString. String concatenation (especially within a loop) isn't efficient.
  • There is a Collections.reverse method: docs.oracle.com/javase/7/docs/api/java/util/… you can probably make use of it.
  • what if hello<tab>world? What if my string contains just a space? Although i wasn't the interviewer there but they certainly look for exception/edge case handling.
  • Yes but will you get back \t when you reverse?
  • Always ask about the use case before delving in with an answer. There's often a trade-off between speed and maintainability.
  • String.join is a good choice, too. Even if it might not be quite as efficient, it's "out of the box".