#1446

Consecutive Characters

Easy
StringTwo PointersSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking all substrings, we can traverse the string once and count consecutive characters, which reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize 'max_power' to 1 and 'current_power' to 1.
  2. 2Step 2: Loop through the string from the second character to the end.
  3. 3Step 3: If the current character is the same as the previous one, increment 'current_power'. Otherwise, reset 'current_power' to 1.
  4. 4Step 4: Update 'max_power' with the maximum of itself and 'current_power'.
solution.py11 lines
1# Full working Python code
2s = 'abbcccddddeeeeedcba'
3max_power = 1
4current_power = 1
5for i in range(1, len(s)):
6    if s[i] == s[i - 1]:
7        current_power += 1
8    else:
9        current_power = 1
10    max_power = max(max_power, current_power)
11print(max_power)

Complexity note: We only traverse the string once, leading to O(n) time complexity, and we use a constant amount of space.

  • 1The problem can be solved efficiently by recognizing patterns in consecutive characters.
  • 2Using a single pass reduces time complexity significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.