Taro Logo

Consecutive Characters

Easy
Asked by:
Profile picture
Profile picture
Profile picture
18 views
Topics:
StringsTwo Pointers

The power of the string is the maximum length of a non-empty substring that contains only one unique character.

Given a string s, return the power of s.

Example 1:

Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input string be empty or null? If so, what should I return?
  2. Is the input string case-sensitive, meaning 'a' and 'A' are considered different characters?
  3. What should I return if multiple characters have the same maximum consecutive occurrence length?
  4. Are there any limitations on the character set of the input string (e.g., ASCII, Unicode)?
  5. Should I return the character itself or the length of the longest consecutive sequence?

Brute Force Solution

Approach

The brute force method for this problem involves checking every possible group of repeating letters. We go through the entire sequence of characters and for each character, determine the longest consecutive sequence it begins.

Here's how the algorithm would work step-by-step:

  1. Start at the beginning of the sequence of characters.
  2. Look at the first character and count how many times it repeats consecutively.
  3. Remember this count as the longest repeating sequence we've found so far.
  4. Move to the next character in the sequence.
  5. Again, count how many times this new character repeats consecutively.
  6. If this new count is bigger than the previous longest count, update our record of the longest count.
  7. Keep doing this for every character in the sequence, making sure to update the longest count whenever we find a longer repeating sequence.
  8. After checking all characters, the longest count we remembered is the answer.

Code Implementation

def longest_consecutive_characters_brute_force(sequence_of_characters):
    longest_repetition = 0

    for index in range(len(sequence_of_characters)):
        current_repetition = 1

        # Count how many times the current character repeats
        for next_index in range(index + 1, len(sequence_of_characters)):
            if sequence_of_characters[index] == sequence_of_characters[next_index]:
                current_repetition += 1
            else:
                break

        # Update the longest repetition found so far
        if current_repetition > longest_repetition:
            longest_repetition = current_repetition

    return longest_repetition

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the input string of size n. For each character, it counts the consecutive occurrences of that character. In the worst case, this inner counting loop will iterate a maximum of n times across all characters. However, the outer loop ensures that each character is considered as the starting point of a consecutive sequence only once. The dominant operation is the single pass through the string, making the time complexity O(n).
Space Complexity
O(1)The algorithm uses a variable to keep track of the current repeating character count and another to store the maximum repeating character count found so far. These variables consume constant space regardless of the input string's length, N. No auxiliary data structures like arrays or hash maps are used to store intermediate results or track visited characters. Therefore, the space complexity is constant.

Optimal Solution

Approach

The goal is to find the longest run of identical characters within a string. We achieve this by traversing the string, keeping track of the current character sequence, and updating the maximum length whenever we find a longer one.

Here's how the algorithm would work step-by-step:

  1. Begin by examining the first character in the string.
  2. Keep track of how many times the current character repeats consecutively.
  3. If the next character is the same as the current one, increase the count of consecutive characters.
  4. If the next character is different, compare the current count to the longest count found so far, and update the longest count if necessary.
  5. After comparing, reset the current count to 1, and start counting the new character.
  6. Repeat the previous steps until the end of the string is reached.
  7. The final longest count will be the result.

Code Implementation

def consecutive_characters(input_string):
    longest_sequence_length = 0
    current_sequence_length = 0

    if not input_string:
        return 0

    previous_character = ''

    for current_character in input_string:

        if current_character == previous_character:
            # Increment the current length if the character repeats
            current_sequence_length += 1
        else:
            # Update longest length and reset current length
            longest_sequence_length = max(longest_sequence_length, current_sequence_length)
            current_sequence_length = 1

        previous_character = current_character

    # Compare one last time in case the longest sequence
    # is at the end of the string
    longest_sequence_length = max(longest_sequence_length, current_sequence_length)

    return longest_sequence_length

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the input string once, examining each character to determine the length of consecutive character sequences. The number of operations performed is directly proportional to the length of the string, which we denote as n. Therefore, the time complexity is linear, O(n).
Space Complexity
O(1)The algorithm uses a fixed number of variables to keep track of the current character, the current count of consecutive characters, and the longest count found so far. These variables consume a constant amount of memory regardless of the input string's length (N). Therefore, the auxiliary space complexity is O(1).

Edge Cases

Null or empty string input
How to Handle:
Return an empty list immediately as there are no characters to process.
String with a single character
How to Handle:
Return an empty list because there is no consecutive character to compare with.
String with all identical characters
How to Handle:
The solution should iterate through and correctly identify runs of identical characters, updating the maximum length as necessary.
Maximum length string (close to memory limits)
How to Handle:
Ensure that the algorithm's memory usage remains within acceptable bounds and doesn't lead to out-of-memory errors.
String with only two different characters alternating frequently
How to Handle:
The solution should handle the transitions between different character runs efficiently, correctly tracking the maximum length.
String contains special characters (e.g., unicode, control characters)
How to Handle:
Ensure the comparison logic works correctly with all valid character types and encodings by comparing character codes.
Consecutive character length exceeds integer limits
How to Handle:
If using an integer to track the maximum length, consider using a larger data type (e.g., long) to prevent overflow.
String with long runs of different repeating characters
How to Handle:
The solution needs to handle multiple runs of different repeating characters to ensure the correct maximum length is always calculated.