#3757

Number of Effective Subsequences

Hard
ArrayMathDynamic ProgrammingBit ManipulationCombinatoricsHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Identify bits that contribute to the overall strength. Effective subsequences are those that remove all instances of a bit contributing to the strength.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total strength using bitwise OR of all elements.
  2. 2Step 2: Count occurrences of each unique number in the array.
  3. 3Step 3: For each unique number, calculate effective subsequences as 2^(count) - 1 and sum them.
solution.py12 lines
1def countEffectiveSubsequences(nums):
2    from collections import Counter
3    MOD = 10**9 + 7
4    total_strength = 0
5    for num in nums:
6        total_strength |= num
7    count = Counter(nums)
8    total = 0
9    for num, cnt in count.items():
10        if (total_strength & num) == num:
11            total += (pow(2, cnt, MOD) - 1) % MOD
12    return total % MOD

Complexity note: Counting occurrences and calculating powers is linear with respect to the number of elements.

  • 1Effective subsequences remove bits contributing to strength.
  • 2Count unique elements and their occurrences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.