Similar Problems

Similar Problems not available

Circular Sentence - Leetcode Solution

Companies:

LeetCode:  Circular Sentence Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement:

Given a string s, you need to output the first recurring character in it, or return null if there is no recurring character.

A recurring character is a character that appears more than once in the given string s and whose first and last occurrences are consecutive.

Example:

Input: "abca" Output: "a" Explanation: The first recurring character is "a" because it appears more than once and its first and last occurrences are consecutive.

Solution:

To solve this problem, we can use a technique called the slow and fast pointers. We can start with two pointers, the slow pointer and the fast pointer, both pointing to the first character of the string.

Then, we can move the fast pointer one step at a time, and the slow pointer two steps at a time. If they ever meet, that means that we have found a recurring character, and we can return it.

However, we need to check whether the first and last occurrences of the character are consecutive. We can do this by keeping track of the index of the first occurrence of the character. If we find the same character again, we can check whether the difference between the current index and the first index is equal to 1.

If it is, we have found a recurring character whose first and last occurrences are consecutive, and we can return it.

If we reach the end of the string without finding a recurring character, we can return null.

Here is the code for the solution:

def circularSentence(s: str) -> str:
    # initialize slow and fast pointers
    slow = 0
    fast = 0

    # initialize dictionary to keep track of character indices
    indices = {}

    # iterate through the string
    while fast < len(s):
        # move the fast pointer one step at a time
        fast += 1

        # if we find the same character again
        if s[fast-1] in indices:
            # check whether the first and last occurrences are consecutive
            if fast - indices[s[fast-1]] == 1:
                return s[fast-1]

        # add the current character to the dictionary
        indices[s[fast-1]] = fast-1

        # move the slow pointer two steps at a time
        if (fast - slow) % 2 == 0:
            slow += 1

    # if we reach the end of the string without finding a recurring character, return null
    return None

Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input string s.

Space Complexity:

The space complexity of this algorithm is O(n), where n is the length of the input string s. This is because we need to store the indices of each character in a dictionary in the worst case.

Circular Sentence Solution Code

1