VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-all-ordered-pairs-a-b-such-that-a-and-b-are-disjoint/

⇱ Count all ordered pairs (A, B) such that A and B are disjoint - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count all ordered pairs (A, B) such that A and B are disjoint

Last Updated : 29 Feb, 2024

Given an array arr[] of size n contains distinct elements, the task is to find the number of ordered pairs (A, B) that can be made where A and B are subsets of the given array arr[] and A ∩ B = Φ (i.e, Both A and B subset should be disjoint or no common elements between them).

Example:

Input: arr = {1, 2}
Output: 9
Explanation: The subsets of the array are {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, and {1, 2, 3}. The ordered pairs (A, B) where A and B disjoint subsets are: ({}, {}), ({}, {1}), ({}, {2}), ({1}, {}), ({2}, {}), ({1, 2}, {}), ({}, {1, 2}, ({1}, {2}, ({2}, {1})

Input: arr = {1, 2, 3}
Output: 27

Approach:

Every element has three options, It will either be included in A, B, or not included in either A or B. Hence, there would be 3^n possible combinations for given array of size n.

Steps-by-step approach:

  • Set the modulo constant MOD to 1e9 + 7.
  • Define a function binpow() that calculates the power using binary exponentiation.
    • Take the modulo of the base to keep it within the specified range.
    • Initialize result to 1.
    • Iterate until the exponent is greater than 0.
    • If the current bit of the exponent is 1, multiply the result by the base.
    • Square the base and divide the exponent by 2 in each iteration.
    • Return the final result.
  • Solve Function:
    • Define a function solve that takes an integer n and a vector arr.
    • Call binpow(3, n) to calculate (3^n) mod (1e9 + 7).
    • Return the result.

Below is the implementation of the above approach:


Output
27

Time Complexity: O(log(n))
Auxiliary Space: O(log(n))

Comment