↓Skip to main content
  1. LeetCode/

LeetCode 1446: Consecutive Characters

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Wrong Answer → Accepted

Approach
#

Extend the current run when a character equals the previous one, otherwise reset to 1 (the new character is itself a run of length 1), tracking the maximum. itertools.groupby also works.

My Attempts
#

Attempt 1 reset the run to 0 on a change, leaving out the new character: "baa" should be 2; it returned 1. Resetting to 1 passed.

Solution
#

class Solution:
    def maxPower(self, s: str) -> int:
        best = cur = 1
        for i in range(1, len(s)):
            cur = cur + 1 if s[i] == s[i - 1] else 1
            best = max(best, cur)
        return best

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Reset to 1, not 0.

Interview Explanation
#

In one pass I extend the run on equal neighbors and reset it to 1 otherwise, keeping the maximum. Time O(n), space O(1).

Related

LeetCode 1869: Longer Contiguous Segments of Ones than Zeros
·1 min
LeetCode Easy String
LeetCode 1869 note: find the longest run of 1s and of 0s and compare; split does it in one line
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 459: Repeated Substring Pattern
·1 min
LeetCode Easy String String-Matching Z-Algorithm Knuth-Morris-Pratt-Algorithm
LeetCode 459 note: s is a repetition of a substring exactly when s occurs in s + s with its first and last characters removed
LeetCode 482: License Key Formatting
·2 mins
LeetCode Easy String
LeetCode 482 note: remove every dash and uppercase first, then cut groups of k from the end so only the first group may be shorter
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes
LeetCode 344: Reverse String
·1 min
LeetCode Easy Two-Pointers String
LeetCode 344 note: swap with two pointers and move inward to reverse in place