Problem · String

Longest Contiguous Character Run

Learn this problem
EasyBoston Consulting Group logoBoston Consulting GroupNEW GRADINTERNOA

Problem statement

You are given a non-empty string source consisting of lowercase English letters.

Find the longest contiguous substring that consists of the same character. If several such substrings have the same maximum length, choose the rightmost one.

Return a string containing the chosen character followed by the number of times it occurs in that substring.

A solution with time complexity no worse than O(source.length^2) fits within the execution time limit.

Function

solution(source: String) → String

Examples

Example 1

source = "bbacccdbbab"return = "c3"

The character a appears in two runs of length 1. The character b appears in three runs: two of length 2 and one of length 1. The single c run has length 3, so it is the longest run and the result is "c3".

Example 2

source = "bbaacaa"return = "a2"

The runs "bb", the first "aa", and the final "aa" all have the maximum length 2. The final "aa" is the rightmost maximum run, so the result is "a2".

Constraints

  • For this exercise, source.length >= 1.
  • source consists only of lowercase English letters.

More Boston Consulting Group problems

drafts saved locally
public String solution(String source) {
    // write your code here
}
source"bbacccdbbab"
expected"c3"
checking account