LeetCode 1859: Sorting the Sentence Solution

Master LeetCode problem 1859 (Sorting the Sentence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1859. Sorting the Sentence

Problem Explanation

Explanation

To reconstruct the original sentence from the shuffled sentence, we can follow these steps:

  1. Split the shuffled sentence by space to get individual words with their indices.
  2. Sort the words based on their indices.
  3. Remove the indices from the sorted words and concatenate them to form the original sentence.

Time complexity: O(n log n) where n is the number of words in the sentence. Space complexity: O(n) where n is the number of words in the sentence.

Solution Code

class Solution {
    public String sortSentence(String s) {
        String[] words = s.split(" ");
        Arrays.sort(words, (a, b) -> a.charAt(a.length() - 1) - b.charAt(b.length() - 1));
        StringBuilder sb = new StringBuilder();
        for (String word : words) {
            sb.append(word, 0, word.length() - 1).append(" ");
        }
        return sb.toString().trim();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1859 (Sorting the Sentence)?

This page provides optimized solutions for LeetCode problem 1859 (Sorting the Sentence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1859 (Sorting the Sentence)?

The time complexity for LeetCode 1859 (Sorting the Sentence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1859 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1859 in Java, C++, or Python.

Back to LeetCode Solutions