We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Circular Sentence

Number: 2580

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a sentence (a string consisting of words separated by a single space with no extra spaces), determine whether the sentence is circular. A sentence is circular if for every pair of consecutive words the last character of the current word equals the first character of the next word, and additionally, the last character of the last word equals the first character of the first word.


Key Insights

  • Split the sentence into individual words using the space delimiter.
  • Iterate through the word list and compare the last character of the current word with the first character of the next word.
  • Use modulus arithmetic to compare the last word's last character with the first word's first character.
  • The solution iterates through each word only once, leading to an efficient approach.

Space and Time Complexity

Time Complexity: O(n) where n is the number of characters in the sentence. Space Complexity: O(m) where m is the number of words in the sentence (storing the split list).


Solution

The solution splits the sentence into an array (or list) of words. It then iterates through the words, comparing the last character of each word with the first character of the next word. The circular condition is checked by using a wrap-around (modulus) for the comparison between the last word and the first word. This approach leverages simple string manipulation and modular arithmetic to ensure all conditions of a circular sentence are met.


Code Solutions

def isCircularSentence(sentence):
    # Split the sentence into words using space as the delimiter
    words = sentence.split(" ")
    # Iterate through the list of words
    for i in range(len(words)):
        # Determine the next index using modulus to wrap around for the circular condition
        next_index = (i + 1) % len(words)
        # Compare the last character of the current word to the first character of the next word
        if words[i][-1] != words[next_index][0]:
            return False
    return True

# Example Test Cases
print(isCircularSentence("leetcode exercises sound delightful"))  # Expected output: True
print(isCircularSentence("eetcode"))                               # Expected output: True
print(isCircularSentence("Leetcode is cool"))                      # Expected output: False
← Back to All Questions