Leetcode 1859: Sorting the Sentence

grid47
grid47
Exploring patterns and algorithms
May 5, 2024 6 min read

You are given a shuffled sentence where each word is tagged with a number that represents its position in the original sentence. Your task is to reconstruct the sentence in its original order and return it.
Problem
Approach
Steps
Complexity
Input: The input is a shuffled sentence containing words followed by a number that represents the word's original position in the sentence.
Example: s = "apple2 banana1 cherry4 mango3"
Constraints:
• 2 <= s.length <= 200
• s contains lowercase and uppercase English letters, spaces, and digits from 1 to 9.
• The number of words in s is between 1 and 9.
• Words in the sentence are separated by a single space.
Output: The output should be the original sentence with the words placed in their correct order and the numbers removed.
Example: s = "banana apple mango cherry"
Constraints:
• The output sentence must contain no leading or trailing spaces.
Goal: Reconstruct the original sentence by sorting the words based on their attached numbers and removing the numbers.
Steps:
• Iterate over the shuffled sentence and extract each word and its attached position number.
• Store each word along with its number in a pair.
• Sort the words based on their numerical positions.
• Remove the position number from each word and reconstruct the sentence.
Goal: The problem has constraints based on the length of the sentence and the number of words.
Steps:
• 2 <= s.length <= 200
• s contains only valid characters (letters, digits from 1 to 9, spaces).
• The number of words is between 1 and 9.
Assumptions:
• The input sentence is well-formed and contains no leading or trailing spaces.
Input: Input: s = "apple2 banana1 cherry4 mango3"
Explanation: In the shuffled sentence, the words are 'apple2', 'banana1', 'cherry4', 'mango3'. When sorted by their numbers (1, 2, 3, 4), the original sentence is 'banana apple mango cherry'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus