Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Dynamic Programming
Longest Unequal Adjacent Groups Subsequence II

Find the longest subsequence of words such that adjacent chosen words come from different groups and their lengths differ by exactly one character.

Acceptance 100%
Problem Statement

Problem

You are given an array of strings words and an array of integers groups, both of length n.

Choose a subsequence of indices i1 < i2 < ... < ik such that:

  • groups[ij] != groups[ij+1] for every adjacent pair in the subsequence.
  • The chosen words are pairwise comparable under a one-step difference rule: for any adjacent chosen words, the two words must have the same length and differ in exactly one character or differ by exactly one insertion/deletion in the way defined by the original problem setting.

Return the longest valid subsequence of indices, or its maximum length depending on the exact task formulation.

This is a dynamic programming problem where each state considers the best subsequence ending at a given word and transitions from earlier compatible words.

Input Format

  • words: array of strings
  • groups: array of integers of the same length as words

The exact platform version may ask for the length of the subsequence rather than the subsequence itself.

Output Format

Return the maximum length of a valid subsequence.

Constraints

  • 1 <= n <= $10^{3}$ is a safe interview-scale assumption for this formulation.
  • String lengths are small to moderate.
  • groups.length == words.length.
  • The answer should respect the alternating-group constraint on adjacent chosen elements.
Examples
Sample cases returned by the problem API.

Example 1

Input

words = ["a","b","ab","ac"], groups = [1,2,1,2]

Output

4

Explanation

One valid subsequence is ["a", "b", "ab", "ac"]. Adjacent groups alternate, and each step satisfies the allowed word-compatibility rule.

Example 2

Input

words = ["abcd","abce","abde"], groups = [1,1,2]

Output

2

Explanation

"abcd" and "abce" cannot both be used if the adjacent group condition is violated. A best valid subsequence has length 2.

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.