The Find the Number of Subsequences With Equal GCD interview question is an advanced algorithmic challenge that combines number theory with combinatorial counting. You are given an array of integers and asked to find the number of pairs of non-empty, disjoint subsequences such that the Greatest Common Divisor (GCD) of the first subsequence is equal to the Greatest Common Divisor of the second subsequence. This problem requires a deep understanding of how GCD behaves across different sets of numbers and how to count these occurrences efficiently.
Companies like Infosys ask the Find the Number of Subsequences With Equal GCD coding problem to evaluate a candidate's ability to handle complex state transitions and optimization techniques. It tests your proficiency in Dynamic Programming and Number Theory. The problem is particularly effective at identifying candidates who can move beyond basic brute force and leverage mathematical properties (like the limited range of GCD values) to design an efficient solution.
This problem is best solved using the Dynamic Programming interview pattern.
dp[g1][g2] can represent the number of ways to form two disjoint subsequences with GCDs g1 and g2.x in the array, you have three choices:
x to the first subsequence: New GCD is gcd(g1, x).x to the second subsequence: New GCD is gcd(g2, x).x in either.Suppose the array is [2, 2, 4].
[2], Subsequence 2: [4]. GCDs: gcd(2)=2, gcd(4)=4. Not equal.[2], Subsequence 2: [2]. GCDs: gcd(2)=2, gcd(2)=2. Equal![2], Subsequence 2: [4, 2]. GCDs: gcd(2)=2, gcd(4, 2)=2. Equal!
The algorithm counts all such valid disjoint pairs.Master the properties of GCD. Remember that and that adding a number to a set can only decrease or maintain the GCD. This "monotonic" property is what makes GCD-based DP problems solvable within restricted value ranges.