703269. Count subsets having distinct even numbers

Easy

Count Subsets Having Distinct Even Numbers

Summary

Given an array arr containing integers, write a program to count the number of subsets that have distinct even numbers. The problem requires us to find all possible subsets of the given array and then check if each subset contains only distinct even numbers.

Detailed Explanation

The problem can be solved by generating all possible subsets of the given array using recursion or dynamic programming. We will use the recursive approach here. For each subset, we will iterate through its elements and count the number of distinct even numbers.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to store the total count of subsets with distinct even numbers.
  2. Define a recursive function countDistinctEvenSubsets that takes an array arr, an index i, and a subset subset.
  3. If i >= arr.length, it means we have processed all elements in the array, so add 1 to count (since this is a valid subset with distinct even numbers) and return.
  4. For each possible value of j from 0 to arr.length - i - 1, recursively call countDistinctEvenSubsets with the subarray arr(i+1..i+j+1) and the updated subset subset + arr[i].
  5. If j == 0, it means we are considering the empty set, so simply return without adding anything to count.
  6. After processing all subsets, return the final value of count.

Time complexity: O(2^n), where n is the length of the array. Space complexity: O(n), for storing the recursive function calls.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static int countDistinctEvenSubsets(int[] arr) {
        return countDistinctEvenSubsets(arr, 0, new ArrayList<>());
    }

    private static int countDistinctEvenSubsets(int[] arr, int i, List<Integer> subset) {
        if (i >= arr.length) {
            return 1;
        }
        int count = 0;
        for (int j = 0; j <= arr.length - i - 1; j++) {
            subset.add(arr[i]);
            count += countDistinctEvenSubsets(arr, i + j + 1, subset);
            subset.remove(subset.size() - 1);
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {2, 4, 6};
        System.out.println(countDistinctEvenSubsets(arr));
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.