#2859
Sum of Values at Indices With K Set Bits
EasyArrayBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution involves precomputing the number of set bits for all indices up to the length of the nums array. This allows us to quickly check if an index has k set bits without recalculating each time.
⚙️
Algorithm
5 steps- 1Step 1: Create an array to store the count of set bits for each index.
- 2Step 2: Loop through each index and calculate the number of set bits using a helper function.
- 3Step 3: Initialize a variable sum to 0.
- 4Step 4: Loop through the nums array and sum the values where the count of set bits equals k.
- 5Step 5: Return the sum.
solution.py7 lines
1# Full working Python code
2
3def sum_of_set_bits(nums, k):
4 def count_set_bits(n):
5 return bin(n).count('1')
6 set_bits_count = [count_set_bits(i) for i in range(len(nums))]
7 return sum(nums[i] for i in range(len(nums)) if set_bits_count[i] == k)ℹ
Complexity note: The time complexity is O(n) because we compute the set bits count for each index once and then iterate through the nums array. The space complexity is O(n) due to the additional array used to store the set bits count.
- 1Understanding binary representation is crucial for bit manipulation problems.
- 2Precomputing values can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.