Leetcode 2490: Circular Sentence

grid47
grid47
Exploring patterns and algorithms
Mar 3, 2024 5 min read

You are given a sentence where words are separated by spaces. A sentence is considered circular if the last character of each word matches the first character of the next word, and the last character of the last word matches the first character of the first word.
Problem
Approach
Steps
Complexity
Input: The input is a string, where words are separated by spaces and consist of only uppercase and lowercase English letters.
Example: sentence = 'hello ox oxo awesome endo'
Constraints:
• 1 <= sentence.length <= 500
• sentence consists of lowercase and uppercase English letters and spaces.
• Words in sentence are separated by a single space.
• There are no leading or trailing spaces.
Output: Return 'true' if the sentence is circular, otherwise return 'false'.
Example: Output: true
Constraints:
• The sentence will always be non-empty.
Goal: To check if the sentence satisfies the circular condition where the last character of each word matches the first character of the next word.
Steps:
• 1. Split the sentence into words.
• 2. Compare the last character of each word with the first character of the next word.
• 3. Also compare the last character of the last word with the first character of the first word.
Goal: The input sentence follows all given constraints, and the words are composed of only English letters and spaces.
Steps:
• Sentence will always contain valid words with no leading or trailing spaces.
• The words in the sentence will be separated by exactly one space.
Assumptions:
• Words in the sentence are non-empty.
• Words consist only of uppercase and lowercase English letters.
Input: sentence = 'hello ox oxo awesome endo'
Explanation: In this example, 'hello' ends with 'o' which matches the first character of 'ox', 'ox' ends with 'x' which matches 'oxo's first character 'x', and so on, forming a circular sentence.

Input: sentence = 'Leetcode is amazing'
Explanation: In this case, 'Leetcode' ends with 'e' but 'is' starts with 'i', so the sentence is not circular.

Input: sentence = 'ax aa a'
Explanation: Here, 'ax' ends with 'x' but the next word 'aa' starts with 'a', and the pattern does not satisfy the circular condition.

Link to LeetCode Lab


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