Circular Sentence
Easy · Arrays & Hashing · Explanation and code example
Iteration (Space Optimized)
How it works
Instead of splitting the string and storing all words, we can iterate through the sentence and check only the characters around each space. When we find a space, the character before it is the last character of the previous word, and the character after it is the first character of the next word. We also need to check that the first and last characters of the entire sentence match for the circular connection.
Steps
- Iterate through each character in the sentence.
- When a space is found at index
i, comparesentence[i-1](end of previous word) withsentence[i+1](start of next word). - If they do not match, return
false. - After the loop, check if the first character of the sentence equals the last character.
- Return
trueif all checks pass.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Forgetting the Wrap-Around Check
Only checking consecutive word pairs without verifying that the last word connects back to the first word. In the space-optimized approach, this means checking that sentence[0] == sentence[-1].
Index Out of Bounds When Accessing Adjacent Characters
When iterating through the string and finding a space at index i, accessing sentence[i-1] or sentence[i+1] without ensuring the space is not at the start or end of the string. The problem guarantees no leading or trailing spaces, but failing to account for this in other contexts causes errors.
Python code example
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
for i in range(len(sentence)):
if sentence[i] == " " and sentence[i - 1] != sentence[i + 1]:
return False
return sentence[0] == sentence[-1]
C++ code example
class Solution {
public:
bool isCircularSentence(string sentence) {
for (int i = 0; i < sentence.size(); i++) {
if (sentence[i] == ' ' && sentence[i - 1] != sentence[i + 1]) {
return false;
}
}
return sentence.front() == sentence.back();
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.