Ctrl K

Close Letters Subsequence

Medium
You are given a string text of lowercase English letters and an integer gap. Cross out some letters, keeping the rest in order, so that any two neighbouring remaining letters are at most gap positions apart in the alphabet. The alphabet does not wrap around: a and z are 25 apart. Return the greatest possible length of the remaining string.
Example 1
text="dbgace", gap=2 → 5

"dbace" works: neighbouring letters are at most 2 apart in the alphabet (d–b, b–a, a–c, c–e). The g cannot be included.

Example 2
text="azby", gap=1 → 2

Either "ab" or "zy" works. The alphabet does not wrap around: a and z are 25 apart.

Example 3
text="mmm", gap=0 → 3

With gap = 0 neighbouring letters must be equal, so take all three m.

Constraints
  • 1 ≤ len(text) ≤ 10⁵
  • 0 ≤ gap ≤ 25
  • text consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSplit Into Dictionary Words MediumWords Hidden in a Text MediumWord Growth Chain MediumCuts With Equal Variety MediumSubstring Pairs With One Typo Medium
loading Python…
Input
text="dbgace", gap=2
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.