algoadvance

Leetcode 2490. Circular Sentence

Problem Statement

You are given a sentence represented as a string s consisting of lowercase English letters and spaces. A sentence can be considered a circular sentence if the last character of each word matches the first character of the next word. The last word should also match the first word to be categorized as a circular sentence.

Write a function isCircularSentence that determines if the given sentence is circular.

Example 1:

Input: s = "leetcode exercises sound delightful"
Output: true
Explanation: The sentence "leetcode exercises sound delightful" is a circular sentence. The last character of each word matches the first character of the next word, and the last character of the sentence matches the first character of the first word.

Example 2:

Input: s = "eetcode"
Output: true
Explanation: The sentence "eetcode" is a circular sentence. The last character of the single word matches the first character of the same word.

Example 3:

Input: s = "Leetcode is cool"
Output: false
Explanation: The sentence "Leetcode is cool" is not a circular sentence because the last character of the word "Leetcode" is "e" and it does not match the first character of the next word "is".

Clarifying Questions

  1. Case sensitivity: Should the comparison be case-insensitive for matching characters?
    • Based on the examples provided, input and comparison are case-sensitive.
  2. Input constraints:
    • Input s is a non-empty string consisting of lowercase English letters and spaces.
  3. Sentence Structure: Can there be multiple consecutive spaces or trailing spaces in the sentence?
    • For simplicity, assume the input is a properly formatted sentence with single spaces between words and no leading/trailing spaces.

Strategy

  1. Split the Sentence: Split the input string s by spaces to get individual words.
  2. Check Circular Property: Validate that the last character of each word matches the first character of the next word.
  3. Edge Case: Ensure that the last character of the last word matches the first character of the first word.
  4. Return Result: Return true if all checks pass; otherwise, return false.

Code

public class Solution {
    public boolean isCircularSentence(String s) {
        // Split the sentence into words
        String[] words = s.split(" ");
        
        // Check for the circular property between words
        for (int i = 0; i < words.length; i++) {
            int nextIndex = (i + 1) % words.length;
            if (words[i].charAt(words[i].length() - 1) != words[nextIndex].charAt(0)) {
                return false;
            }
        }
        
        // If all checks pass, return true
        return true;
    }
}

Time Complexity

This should provide an efficient solution to determining if a sentence is circular based on the problem constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI