Leetcode Daily Question 02/11/2024 - 2490. Circular Sentence
Problem Description:
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. | ---------------------------------------------------------------- | For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters are considered different. | ---------------------------------------------------------------- | A sentence is circular if: | ---------------------------------------------------------------- | The last character of a word is equal to the first character of the next word. The last character of the last word is equal to the first character of the first word. For example, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul" are all circular sentences. However, "Leetcode is cool", "happy Leetcode", "Leetcode" and "I like Leetcode" are not circular sentences. | ---------------------------------------------------------------- | Given a string sentence, return true if it is circular. Otherwise, return false.
Solution:
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
words = sentence.split()
for i in range(1, len(words)):
if words[i][0] != words[i-1][-1]:
return False
return words[0][0] == words[-1][-1]
Explanation:
We can solve this problem by systematically checking the start and end of each pair of words.
If any pair has mismatched starting/ending letter, we return false, otherwise we check the condition for the last and first word.
def isCircularSentence(self, sentence: str) -> bool:
words = sentence.split()
for i in range(1, len(words)):
if words[i][0] != words[i-1][-1]:
return False
return words[0][0] == words[-1][-1]
The time complexity is O(n) since we need to iterate through words to create the splitted array as well as to check the conditions for the question.
The space complexity is O(n) as we need to store the splitted words in an array.
The full solution can be found near the top of the page.
I added a Go implementation for the purpose of practicing.
package main
import (
"strings"
)
func isCircularSentence(sentence string) bool {
words := strings.Split(sentence, " ")
for i := 1; i < len(words); i++ {
if words[i][0] != words[i-1][len(words[i-1])-1] {
return false
}
}
return words[0][0] == words[len(words)-1][len(words[len(words)-1])-1]
}