Circular Sentence - Problem

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 each word in the sentence is equal to the first character of its 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.

Input & Output

Example 1 — Valid Circular Sentence
$ Input: sentence = "leetcode exercises sound delightful"
Output: true
💡 Note: Each word connects properly: leetcodE → Exercises, exerciseS → Sound, sounD → Delightful, and delightfuL loops back to Leetcode
Example 2 — Invalid Connection
$ Input: sentence = "Leetcode is cool"
Output: false
💡 Note: The word 'Leetcode' ends with 'e' but 'is' starts with 'i', so e ≠ i makes it not circular
Example 3 — Single Word
$ Input: sentence = "eetcode"
Output: true
💡 Note: Single word case: first character 'e' equals last character 'e', forming a circle

Constraints

  • 1 ≤ sentence.length ≤ 500
  • sentence consist of only lowercase and uppercase English letters and spaces
  • The words in sentence are separated by a single space
  • There are no leading or trailing spaces

Visualization

Tap to expand
Circular Sentence - Single Pass Approach INPUT leetcode exercises sound delightful e-e s-s d-d l-l "leetcode exercises sound delightful" 4 words to check ALGORITHM STEPS 1 Iterate through string Check each space position 2 At each space: Compare char[i-1] with char[i+1] 3 Check first/last char sentence[0] == sentence[n-1] 4 Return result All checks passed: true Character Comparisons: leetcodE Exercises e == e : OK exerciseS Sound s == s : OK sounD Delightful d == d : OK FINAL RESULT CIRCULAR OK First/Last Check: 'l' == 'l' : OK Output: true Sentence is circular! Key Insight: A circular sentence requires: (1) Last char of each word equals first char of next word, (2) Last char of last word equals first char of first word. Single pass: check char before and after each space, plus first and last characters. Time: O(n), Space: O(1). TutorialsPoint - Circular Sentence | Single Pass - Direct Character Check
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen