#2490

Circular Sentence

Easy
StringString ManipulationArray
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)

Instead of checking each word pair, we can directly check the first and last characters of the entire sentence after splitting it into words, which reduces unnecessary comparisons.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the sentence into words.
  2. 2Step 2: Check if the last character of the last word matches the first character of the first word.
  3. 3Step 3: Loop through the words and check if the last character of each word matches the first character of the next word.
solution.py8 lines
1def isCircularSentence(sentence):
2    words = sentence.split()
3    if words[-1][-1] != words[0][0]:
4        return False
5    for i in range(len(words) - 1):
6        if words[i][-1] != words[i + 1][0]:
7            return False
8    return True

Complexity note: The time complexity is O(n) because we only loop through the words a couple of times, which is linear in relation to the number of characters. The space complexity is O(n) due to the storage of the words in an array.

  • 1The circular condition requires both the last character of each word and the last word's last character to match the first word's first character.
  • 2Efficiently checking character pairs reduces unnecessary comparisons.

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