FastPrepLongest Repeated Letter Block with Adjacent Swaps

Longest Repeated Letter Block with Adjacent Swaps

Intuit logoIntuit● HardFULLTIMEOA
Learn

Problem statement

You are given a string s and a non-negative integer k. In one operation, swap the characters at two adjacent positions.

After at most k operations, choose any letter and any contiguous block consisting only of that letter. Return the maximum possible length of such a block.

You may leave some occurrences of the chosen letter outside the block. Characters cannot be inserted, deleted, or replaced, and each adjacent swap costs one operation. You do not have to use the entire budget.

Practice domain

For this exercise, assume s is nonempty and contains only lowercase English letters. The result is the block length, not a transformed string.

Function

longestRepeatedBlock(s: String, k: int) → int

Examples

Example 1

s = "aabaa"k = 2return = 4

Swap the middle b rightward twice: aabaa → aaaba → aaaab. The four as form one block. No block can have length five because the string has only four copies of a.

Example 2

s = "ababa"k = 1return = 2

One swap can produce aabba, whose longest block has length two. Gathering all three as requires two adjacent swaps, so length three is unavailable.

Example 3

s = "abcabc"k = 0return = 1

With no swaps allowed, every existing block has length one.

Constraints

  • For this exercise, assume 1 <= s.length <= 2000.
  • s contains only characters from a through z.
  • For this exercise, assume 0 <= k <= 10^9.

More Intuit problems

See Intuit hiring insights
public int longestRepeatedBlock(String s, int k) {
    // write your code here
}
s"aabaa"
k2
expected4
Checking account…