Circular Sentence - Problem

Imagine you're creating a word game where sentences must form a perfect circle! A circular sentence is one where each word connects to the next like links in a chain, and the last word connects back to the first.

A sentence is a list of words separated by single spaces with no leading or trailing spaces. For example: "Hello World", "HELLO", or "hello world hello world".

Circular Rules:

  • The last character of each word must equal the first character of the next word
  • The last character of the final word must equal the first character of the first word
  • Case matters: 'A' ≠ 'a'

Examples:

  • "leetcode exercises sound delightful" → e→e, s→s, d→d, l→l
  • "eetcode" → single word where first 'e' = last 'e'
  • "Leetcode is cool" → 'e' ≠ 'i', 's' ≠ 'c', 'l' ≠ 'L'

Given a string sentence, return true if it forms a circular sentence, false otherwise.

Input & Output

example_1.py — Circular Sentence
$ Input: "leetcode exercises sound delightful"
Output: true
💡 Note: All words connect properly: leetcode ends with 'e' and exercises starts with 'e', exercises ends with 's' and sound starts with 's', sound ends with 'd' and delightful starts with 'd', and delightful ends with 'l' which matches the first character of leetcode.
example_2.py — Non-Circular Sentence
$ Input: "Leetcode is cool"
Output: false
💡 Note: The connection fails at the first word boundary: Leetcode ends with 'e' but is starts with 'i'. Since 'e' ≠ 'i', the sentence is not circular.
example_3.py — Single Word
$ Input: "eetcode"
Output: true
💡 Note: Single word case: we only need to check if the first character equals the last character. Here 'e' == 'e', so it's circular.

Constraints

  • 1 ≤ sentence.length ≤ 500
  • sentence consists 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 as Chain Linksleetcodel...eexercisese...ssounds...ddelightfuld...le → e ✓s → s ✓d → d ✓l → l ✓
Understanding the Visualization
1
Identify Links
Each word is a chain link with connection points at first and last characters
2
Check Connections
Verify each link connects properly to the next one
3
Complete Circle
Ensure the last link connects back to the first link
Key Takeaway
🎯 Key Insight: We can check circular connectivity in O(1) space by scanning for spaces and comparing adjacent characters, plus checking first/last characters match.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.4K Views
Medium Frequency
~8 min Avg. Time
845 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