Talentd
FleetCode
Make and follow sheets.Sign in

Find the Maximum Length of Valid Subsequence II solution and explanation

MediumArrayDynamic Programming6 min read57.2% acceptanceUpdated 9 Apr 2026
Find the Maximum Length of Valid Subsequence | Part I | Part II | Leetcode 3201 | 3202 | MIKcodestorywithMIK · 45:23 · 14K viewsWatch on YouTube
9 more videos on this problem
  1. Find the Maximum Length of Valid Subsequence | Part I | Part II | Leetcode 3201 | 3202 | MIKcodestorywithMIK · 45:23 · 14K views
  2. 3201, 3202. Find the Maximum Length of Valid Subsequence II | | Math | DP | LIS SimilarAryan Mittal · 37:26 · 10K views
  3. Find the Maximum Length of Valid Subsequence II | Leetcode 3202Techdose · 29:59 · 4K views
  4. Find the Maximum Length of Valid Subsequence II | LeetCode 3202|Leetcode potd | dynamic programmingCode Thoughts · 14:15 · 3K views
  5. 3202. Find the Maximum Length of Valid Subsequence II | Leetcode Daily - PythonLeetcode Daily · 5:23 · 2K views
  6. 3202. Find the Maximum Length of Valid Subsequence II | Weekly Leetcode 404codingMohan · 21:10 · 1K views
  7. Leetcode 3202. Find the Maximum Length of Valid Subsequence II | DP | Python Solution ExplainedStatLearn Tech · 22:56 · 1K views
  8. 3202. Find the Maximum Length of Valid Subsequence II (Leetcode Medium)Programming Live with Larry · 14:17 · 1K views
  9. Daily Leetcode #1934: Jul 17, 2025 - 3202. Find the Maximum Length of Valid Subsequence IIProgramming Live with Larry · 15:56 · 1K views
  10. 🔥 LeetCode 3202 - Max Length of Valid Subsequence II | DP with Modulo Optimization | Java ExplainedcodingX krishna · 31:29 · 837 views

The problem

You are given an integer array nums and a positive integer k.

A subsequence sub of nums with length x is called valid if it satisfies:

  • (sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.
Return the length of the longest valid subsequence of nums.

Example 1:

Input: nums = [1,2,3,4,5], k = 2

Output: 5

Explanation:

The longest valid subsequence is [1, 2, 3, 4, 5].

Example 2:

Input: nums = [1,4,2,3,1,4], k = 3

Output: 4

Explanation:

The longest valid subsequence is [1, 4, 1, 4].

Constraints:

  • 2 <= nums.length <= 103
  • 1 <= nums[i] <= 107
  • 1 <= k <= 103

Approach overview

Problem Overview: You are given an integer array and a value k. The goal is to build the longest subsequence such that every adjacent pair in the subsequence has the same remainder when their sum is taken modulo k. Order must follow the original array, so the problem becomes finding the longest valid chain of elements whose pairwise modulo condition stays constant.

Approach 1: Prefix Sum and Modulo Grouping (Dynamic Programming) (Time: O(n * k), Space: O(k))

The key observation is that the condition (a + b) % k = target can be rewritten using remainders. If a % k = r, then the next element must have remainder (target - r + k) % k. Iterate through the array and reduce each number to its remainder modulo k. For every possible target remainder 0..k-1, maintain a small DP structure that tracks the longest subsequence ending with each remainder. When you process a new element, compute the required previous remainder that would satisfy the pair condition and extend that subsequence by one. This effectively turns the problem into remainder transitions rather than raw value comparisons. The method works well because the modulo range is limited to k, making the DP compact. This approach directly uses ideas from dynamic programming and remainder grouping from array problems.

Approach 2: Frequency Map for Remainder Conditions (Time: O(n + k^2), Space: O(k))

Another way to view the problem is through remainder frequencies. Convert every value to num % k and count how often each remainder appears. For a fixed target value t, a valid adjacent pair must satisfy (r1 + r2) % k = t. This means remainder r1 pairs with (t - r1 + k) % k. Iterate through all possible target remainders and simulate building the longest alternating chain of compatible remainders using the frequency map. Each step extends the sequence by consuming counts of matching remainders. Because only k remainder classes exist, exploring all pair relationships costs O(k^2). This approach is easier to reason about when you focus on remainder compatibility rather than element positions and relies on constant-time lookups with a hash map or frequency array, a common pattern in hash map based solutions.

Recommended for interviews: The dynamic programming remainder-transition approach is what most interviewers expect. It shows you can transform a numeric constraint into a state transition over modulo classes. Mentioning the brute reasoning about pair remainders demonstrates understanding, but implementing the DP efficiently demonstrates stronger algorithmic thinking.

Approach 1: Prefix Sum and Modulo Grouping

Use the prefix sum technique and modulo operation to find common remainders. By converting the problem into grouping numbers by their mod results, you can efficiently find the longest subsequence that meets the condition.

def maxValidSubsequence(nums, k):
    from collections import defaultdict
    mod_count = defaultdict(int)
    prefix_sum = 0
    for num in nums:
        prefix_sum += num
        remainder = prefix_sum % k
        mod_count[remainder] += 1
    return max(mod_count.values())

# Example Usage
nums = [1, 4, 2, 3, 1, 4]
k = 3
print(maxValidSubsequence(nums, k)) # Output: 4
function maxValidSubsequence(nums, k) {
    const modCount = new Map();
    let prefixSum = 0;
    nums.forEach(num => {
        prefixSum += num;
        const remainder = prefixSum % k;
        modCount.set(remainder, (modCount.get(remainder) || 0) + 1);
    });
    return Math.max(...modCount.values());
}

// Example Usage
let nums = [1, 4, 2, 3, 1, 4];
let k = 3;
console.log(maxValidSubsequence(nums, k)); // Output: 4

This solution uses a dictionary to count how many times each remainder occurs when progressively adding elements of the array and taking modulo k. The maximum count of a remainder signals the longest subsequence satisfying the condition.

Complexity

Time Complexity: O(n), where n is the length of the nums array.
Space Complexity: O(k), since at most k unique remainders will be stored.

Try this approach in the editor

Approach 2: Frequency Map for Remainder Conditions

Use a frequency map to group numbers by the remainder of their sums when divided by k. This allows finding sequences that have consistent remainder values.

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public static int maxValidSubsequence(int[] nums, int k) {
        Map<Integer, Integer> modCount = new HashMap<>();
        int prefixSum = 0;
        for (int num : nums) {
            prefixSum += num;
            int remainder = prefixSum % k;
            modCount.put(remainder, modCount.getOrDefault(remainder, 0) + 1);
        }
        return modCount.values().stream().max(Integer::compare).orElse(0);
    }

    public static void main(String[] args) {
        int[] nums = {1, 4, 2, 3, 1, 4};
        int k = 3;
        System.out.println(maxValidSubsequence(nums, k)); // Output: 4
    }
}
#include <stdio.h>
#include <stdlib.h>

int maxValidSubsequence(int* nums, int numsSize, int k) {
    int modCount[k];
    for (int i = 0; i < k; ++i) modCount[i] = 0;
    int prefixSum = 0;
    for (int i = 0; i < numsSize; ++i) {
        prefixSum += nums[i];
        int remainder = prefixSum % k;
        modCount[remainder]++;
    }
    int max = 0;
    for (int i = 0; i < k; ++i) {
        if (modCount[i] > max) {
            max = modCount[i];
        }
    }
    return max;
}

int main() {
    int nums[] = {1, 4, 2, 3, 1, 4};
    int k = 3;
    printf("%d\n", maxValidSubsequence(nums, 6, k)); // Output: 4
    return 0;
}

This solution maps integers to their remainder counts from prefix sums. By iterating through the array, it accumulates these counts and finds the highest frequency of the same remainder, which indicates the longest valid subsequence.

Complexity

Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(k), as at most k different remainder counts need to be stored.

Try this approach in the editor

Approach 3: Dynamic Programming

Based on the problem description, we know that for a subsequence a_1, a_2, a_3, cdots, a_x, if it satisfies (a_1 + a_2) bmod k = (a_2 + a_3) bmod k, then a_1 bmod k = a_3 bmod k. This means that the result of taking modulo k for all odd-indexed elements is the same, and the result for all even-indexed elements is the same as well.

We can solve this problem using dynamic programming. Define the state f[x][y] as the length of the longest valid subsequence where the last element modulo k equals x, and the second to last element modulo k equals y. Initially, f[x][y] = 0.

Iterate through the array nums, and for each number x, we get x = x bmod k. Then, we can enumerate the sequences where two consecutive numbers modulo j yield the same result, where j \in [0, k). Thus, the previous number modulo k would be y = (j - x + k) bmod k. At this point, f[x][y] = f[y][x] + 1.

The answer is the maximum value among all f[x][y].

The time complexity is O(n times k), and the space complexity is O(k^2). Here, n is the length of the array nums, and k is the given positive integer.

class Solution {
public:
    int maximumLength(vector<int>& nums, int k) {
        int f[k][k];
        memset(f, 0, sizeof(f));
        int ans = 0;
        for (int x : nums) {
            x %= k;
            for (int j = 0; j < k; ++j) {
                int y = (j - x + k) % k;
                f[x][y] = f[y][x] + 1;
                ans = max(ans, f[x][y]);
            }
        }
        return ans;
    }
};
function maximumLength(nums: number[], k: number): number {
    const f: number[][] = Array.from({ length: k }, () => Array(k).fill(0));
    let ans: number = 0;
    for (let x of nums) {
        x %= k;
        for (let j = 0; j < k; ++j) {
            const y = (j - x + k) % k;
            f[x][y] = f[y][x] + 1;
            ans = Math.max(ans, f[x][y]);
        }
    }
    return ans;
}
public class Solution {
    public int MaximumLength(int[] nums, int k) {
        int[,] f = new int[k, k];
        int ans = 0;
        foreach (int num in nums) {
            int x = num % k;
            for (int j = 0; j < k; ++j) {
                int y = (j - x + k) % k;
                f[x, y] = f[y, x] + 1;
                ans = Math.Max(ans, f[x, y]);
            }
        }
        return ans;
    }
}
func maximumLength(nums []int, k int) (ans int) {
	f := make([][]int, k)
	for i := range f {
		f[i] = make([]int, k)
	}
	for _, x := range nums {
		x %= k
		for j := 0; j < k; j++ {
			y := (j - x + k) % k
			f[x][y] = f[y][x] + 1
			ans = max(ans, f[x][y])
		}
	}
	return
}
impl Solution {
    pub fn maximum_length(nums: Vec<i32>, k: i32) -> i32 {
        let k = k as usize;
        let mut f = vec![vec![0; k]; k];
        let mut ans = 0;
        for x in nums {
            let x = (x % k as i32) as usize;
            for j in 0..k {
                let y = (j + k - x) % k;
                f[x][y] = f[y][x] + 1;
                ans = ans.max(f[x][y]);
            }
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Prefix Sum and Modulo Grouping

Time Complexity: O(n), where n is the length of the nums array.
Space Complexity: O(k), since at most k unique remainders will be stored.

Frequency Map for Remainder Conditions

Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(k), as at most k different remainder counts need to be stored.

Dynamic Programming–

Complexity analysis

ApproachTimeSpaceWhen to Use
Prefix Sum and Modulo Grouping (DP)O(n * k)O(k)General case when processing elements in order and extending subsequences dynamically
Frequency Map for Remainder ConditionsO(n + k^2)O(k)Useful when focusing on remainder compatibility and counts rather than element positions

Frequently asked questions

Is Find the Maximum Length of Valid Subsequence II easy or hard?

Find the Maximum Length of Valid Subsequence II is generally classified as a Medium problem. The challenge comes from recognizing that the pair condition can be rewritten using modulo arithmetic and then modeled as a dynamic programming transition between remainder states.

Find the Maximum Length of Valid Subsequence II Python/Java solution

Python, Java, JavaScript, and C implementations typically follow the same idea: compute num % k, maintain DP states for valid remainder transitions, and update the longest subsequence length while scanning the array. The algorithm runs in O(n * k) time and O(k) space.

How to solve Find the Maximum Length of Valid Subsequence II in O(n)?

Strict O(n) is difficult because the target remainder can be any value from 0 to k-1. Most optimized implementations achieve O(n * k) by maintaining DP states for remainder transitions. Each element updates at most k states, which is efficient when k is small relative to n.

What is the best approach for Find the Maximum Length of Valid Subsequence II?

The most reliable approach uses dynamic programming with modulo grouping. Convert each number to its remainder modulo k and track the longest subsequence that satisfies a fixed target remainder for adjacent pair sums. This approach runs in O(n * k) time and O(k) space because transitions only depend on remainder classes rather than the full values.

Is Find the Maximum Length of Valid Subsequence II asked at Google/Amazon/Meta?

Problems involving modulo constraints, subsequences, and dynamic programming are common in interviews at companies like Google, Amazon, and Meta. While this exact problem may appear on platforms like LeetCode, its underlying pattern—modulo-based DP transitions—frequently appears in technical interviews.

What data structure is used in Find the Maximum Length of Valid Subsequence II?

The solution primarily uses arrays or hash maps to store counts or DP states for each remainder modulo k. These structures allow constant-time lookup when determining which remainder can extend the current subsequence.

What is the time complexity of Find the Maximum Length of Valid Subsequence II?

The typical dynamic programming solution runs in O(n * k) time, where n is the length of the array and k is the modulo value. Space complexity is O(k) since only remainder states are stored. Alternative remainder-frequency approaches may run in O(n + k^2) time.

Comments

Now write it yourselfClose this page and solve Find the Maximum Length of Valid Subsequence II in the editor, without looking.
Practise Find the Maximum Length of Valid Subsequence II