#1859

Sorting the Sentence

Easy
StringSortingArrayString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a single pass to place each word in its correct position based on the index, which is more efficient than sorting.

⚙️

Algorithm

4 steps
  1. 1Step 1: Split the input string into words using space as a delimiter.
  2. 2Step 2: Create an array of the same length as the number of words to hold the original words in their correct positions.
  3. 3Step 3: For each word, extract the index and place the word in the correct position in the array.
  4. 4Step 4: Join the array into a single string to form the original sentence.
solution.py9 lines
1# Full working Python code
2s = 'is2 sentence4 This1 a3'
3words = s.split()
4original_words = [''] * len(words)
5for word in words:
6    index = int(word[-1]) - 1
7    original_words[index] = word[:-1]
8original_sentence = ' '.join(original_words)
9print(original_sentence)

Complexity note: The time complexity is O(n) because we only make a single pass through the words. The space complexity is O(n) due to the storage of the original words in an array.

  • 1Understanding how to manipulate strings and extract information is crucial.
  • 2Recognizing the need for sorting or indexing can lead to more efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.