Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find length of the largest subset where one element in every pair is divisible by other in Python
Given a list of unique numbers, we need to find the largest subset where every pair of elements satisfies the divisibility condition: either i % j = 0 or j % i = 0. This means one element must divide the other in every pair.
For example, if the input is nums = [3, 6, 12, 24, 26, 39], the output will be 4 because the largest valid subset is [3, 6, 12, 24] where 6 is divisible by 3, 12 is divisible by 6, and 24 is divisible by 12.
Algorithm
We use dynamic programming with the following approach ?
- Sort the array to ensure smaller elements come before larger ones
- Use DP array where
dp[i]represents the length of the largest valid subset ending at indexi - For each element, check all previous elements to see if current element is divisible by them
- Update the DP value based on the maximum chain length found
Implementation
def find_largest_divisible_subset(nums):
# Initialize DP array with 1 (each element forms a subset of size 1)
dp = [1] * len(nums)
nums.sort() # Sort to ensure proper order for divisibility check
n = len(nums)
# Handle edge cases
if n <= 1:
return n
max_length = 0
# Fill DP array using dynamic programming
for i in range(1, n):
for j in range(0, i):
# If current element is divisible by previous element
if nums[i] % nums[j] == 0:
dp[i] = max(dp[i], dp[j] + 1)
max_length = max(max_length, dp[i])
return max_length
# Test the function
nums = [3, 6, 12, 24, 26, 39]
result = find_largest_divisible_subset(nums)
print(f"Input: {nums}")
print(f"Largest subset length: {result}")
Input: [3, 6, 12, 24, 26, 39] Largest subset length: 4
How It Works
Let's trace through the algorithm with our example ?
def find_largest_divisible_subset_with_trace(nums):
dp = [1] * len(nums)
nums.sort()
n = len(nums)
print(f"Sorted array: {nums}")
print("DP progression:")
for i in range(1, n):
for j in range(0, i):
if nums[i] % nums[j] == 0:
old_dp = dp[i]
dp[i] = max(dp[i], dp[j] + 1)
print(f" {nums[i]} % {nums[j]} = 0, dp[{i}]: {old_dp} ? {dp[i]}")
print(f"After processing {nums[i]}: dp = {dp}")
return max(dp)
# Trace the algorithm
nums = [3, 6, 12, 24, 26, 39]
result = find_largest_divisible_subset_with_trace(nums)
print(f"\nFinal result: {result}")
Sorted array: [3, 6, 12, 24, 26, 39] DP progression: 6 % 3 = 0, dp[1]: 1 ? 2 After processing 6: dp = [1, 2, 1, 1, 1, 1] 12 % 3 = 0, dp[2]: 1 ? 2 12 % 6 = 0, dp[2]: 2 ? 3 After processing 12: dp = [1, 2, 3, 1, 1, 1] 24 % 3 = 0, dp[3]: 1 ? 2 24 % 6 = 0, dp[3]: 2 ? 3 24 % 12 = 0, dp[3]: 3 ? 4 After processing 24: dp = [1, 2, 3, 4, 1, 1] After processing 26: dp = [1, 2, 3, 4, 1, 1] 39 % 3 = 0, dp[5]: 1 ? 2 After processing 39: dp = [1, 2, 3, 4, 1, 2] Final result: 4
Alternative Implementation with Actual Subset
If you also need to return the actual subset elements ?
def find_divisible_subset_with_elements(nums):
if not nums:
return []
nums.sort()
n = len(nums)
dp = [1] * n
parent = [-1] * n
max_length = 1
max_index = 0
for i in range(1, n):
for j in range(i):
if nums[i] % nums[j] == 0 and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
parent[i] = j
if dp[i] > max_length:
max_length = dp[i]
max_index = i
# Reconstruct the subset
subset = []
current = max_index
while current != -1:
subset.append(nums[current])
current = parent[current]
return subset[::-1] # Reverse to get ascending order
# Test with subset reconstruction
nums = [3, 6, 12, 24, 26, 39]
subset = find_divisible_subset_with_elements(nums)
print(f"Input: {nums}")
print(f"Largest divisible subset: {subset}")
print(f"Subset length: {len(subset)}")
Input: [3, 6, 12, 24, 26, 39] Largest divisible subset: [3, 6, 12, 24] Subset length: 4
Time and Space Complexity
- Time Complexity: O(n²) where n is the length of the input array
- Space Complexity: O(n) for the DP array and additional arrays
Conclusion
This dynamic programming solution efficiently finds the largest subset where every pair satisfies the divisibility condition. The key insight is sorting the array first and using DP to track the maximum chain length ending at each position.
