Problem Description
Given an array of distinct integers and an integer k, count how many subsets of the array (including the empty set) do not contain any two numbers with an absolute difference equal to k. Such subsets are called k–Free subsets.
Key Insights
- Two numbers x and y conflict if |x - y| equals k.
- Because conflicts only occur between numbers differing exactly by k, any conflict graph forms disjoint chains (or isolated nodes).
- For any chain (i.e. an arithmetic progression having consecutive differences equal to k), the allowed selections are equivalent to choosing an independent set in a line graph.
- The number of independent sets in a chain of length L can be computed with a simple Fibonacci-style recurrence: dp[i] = dp[i – 1] + dp[i – 2].
- Since there is no conflict between numbers in different connected components, the overall count is the product of counts for each component.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the input array (plus a small extra factor for processing each connected component which is bounded by n). Space Complexity: O(n), for storing the set of numbers and the visited markers during the DFS.
Solution
We solve the problem by first recognizing that a conflict only exists between a number x and another number x+k (or x-k). Therefore, build a graph with nodes as the given numbers and an edge between x and x+k (if both exist). This graph is a collection of disjoint chains (or isolated nodes).
For each connected component:
- Perform a DFS to retrieve all nodes in the component.
- Sort the component. (Due to the nature of the edge, nodes in a component will form an arithmetic progression with difference k.)
- Compute the number of valid independent sets using dynamic programming. For a chain of length L, the recurrence is:
- dp[0] = 1 (base case for empty prefix)
- dp[1] = 2 (pick the single node or not)
- dp[i] = dp[i - 1] + dp[i - 2]
Since components are independent, multiply the counts for all components to get the final result.