Skip to main content
Back to problems
Leetcode
Medium
Strings
Dynamic Programming
Arrays
Google
Longest Ideal Subsequence

Find the length of the longest subsequence where adjacent chosen characters differ by at most kk in alphabet position.

Acceptance 0%
Problem Statement

You are given a string s consisting of lowercase English letters and an integer k.

A subsequence of s is called ideal if for every pair of adjacent characters in the subsequence, the absolute difference between their alphabet positions is at most k.

Your task is to return the length of the longest ideal subsequence of s.

An alphabet position means a = 0, b = 1, ..., z = 25.

A subsequence keeps the original order of characters, but does not need to be contiguous.

Input Format

  • A string s of lowercase English letters.
  • An integer k.

Output Format

  • Return a single integer: the maximum length of an ideal subsequence.

Constraints

  • 1s1 \le |s|
  • s contains only lowercase English letters
  • 0k250 \le k \le 25
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "acfgbd", k = 2

Output

4

Explanation

One longest ideal subsequence is "acbd".

  • a to c differs by 2
  • c to b differs by 1
  • b to d differs by 2 So the answer is 4.

Example 2

Input

s = "abcd", k = 3

Output

4

Explanation

All adjacent letters in the whole string differ by at most 3, so the entire string is ideal.

Show 1 more example

Example 3

Input

s = "aaaa", k = 0

Output

4

Explanation

Only equal adjacent letters are allowed when k = 0, so all four a characters can be taken.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.