DSA interview question
You're designing a task-scheduling optimizer where jobs have "batch sizes," and a batch of size A can only be merged into a batch of size B if B is an exact multiple of A (this avoids leftover/fractional work when consolidating batches). Given a set of distinct positive integers representing available batch sizes, you want to find the largest group of batch sizes you can chain together for consolidation — where for every pair (a, b) in the chosen group (with a <= b), b is divisible by a.
Example: nums = [1,2,4,8] — the entire set works since 1|2, 2|4, 4|8 (and transitively all pairs divide). Answer: [1,2,4,8].
vector<int> largestDivisibleSubset(vector<int>& nums);
Input nums | Output (one valid answer) | Explanation |
|---|---|---|
[1,2,3] | [1,2] or [1,3] | Both are valid length-2 divisible subsets; either is acceptable |
[1,2,4,8] | [1,2,4,8] | Every pair divides — full set works |
[4,8,10,240] | [4,8,240] | `4 |
[1] | [1] | Single element |
[3,5,7] | [3] or [5] or [7] | No two share a divisibility relation — any single element is length 1 |
[2,3,4,8,16] | [2,4,8,16] | Longest chain skips 3 entirely |
(Always confirm: the problem asks for any one valid maximum-size subset when multiple exist — output isn't unique.)
nums? (Confirms O(n²) DP is acceptable vs needing something smarter.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in