Circular Sentence (LeetCode 2490): Solution and Explanation

Easy
String

Decide whether each word ends with the letter the next word starts with, wrapping around from the last word back to the first.

Intuition

Picture the words placed on a ring. Each word is joined to the next by a link, and the last word is joined back to the first. The sentence is circular when every link matches.

You never need to split the words. Two neighboring words meet at exactly one space, so the last letter of the left word is the character just before that space and the first letter of the right word is the character just after it. The wrap-around link is simply the last character of the sentence against the first.

Approach: Compare the neighbors of every space

  1. Scan the sentence for spaces.
  2. At each space i, if sentence[i - 1] != sentence[i + 1], return false.
  3. After the scan, return whether sentence[0] == sentence[n - 1].

Step-by-step example

sentence = "leetcode exercises sound delightful"
  1. The space after "leetcode" has 'e' on the left and 'e' on the right: the link holds.
  2. The space after "exercises" has 's' and 's': the link holds.
  3. The space after "sound" has 'd' and 'd': the link holds.
  4. Close the ring: the sentence ends with 'l' and starts with 'l', so the answer is true.

Code: Python, Java, C++

1class Solution:
2    def isCircularSentence(self, sentence: str) -> bool:
3        n = len(sentence)
4        for i in range(n):
5            if sentence[i] == ' ' and sentence[i - 1] != sentence[i + 1]:
6                return False
7        return sentence[0] == sentence[-1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is visited once.

Space

O(1)

Only an index is kept; no words are extracted.

Other approaches

Split into words (time O(n), space O(n))

Split on spaces and compare words[i][-1] with words[(i + 1) % m][0] for every i. Easier to read, but it allocates a list of words.

Common mistakes

  • Forgetting the wrap-around check between the last word and the first word.
  • Lowercasing the sentence. Uppercase and lowercase letters are different, so "Aa aA" is circular but "Ab ba" is not.
  • Treating a single word as automatically circular. It must still start and end with the same character.

Frequently asked questions

Why is sentence[i - 1] safe to read at a space?

There are no leading or trailing spaces, so a space is never the first or last character. Both neighbors always exist.

Does a one-word sentence need special handling?

No. The loop finds no spaces, and the final check compares the word's first and last characters, which is exactly the rule.

Can I stop early?

Yes. The first mismatched link already makes the answer false.