Leetcode 2859. Sum of Values at Indices With K Set Bits
LeetCode Problem 2859: Sum of Values at Indices With K Set Bits
Description:
Given a 0-indexed integer array nums
and an integer k
, return the sum of the elements of nums
at indices having exactly k
set bits in their binary representation.
Example:
Input: nums = [1,2,3,4], k = 1
Output: 6
Explanation: The indices with one set bit are 01 and 10, respectively indices 1 and 2.
1 <= nums.length <= 10^5
and integer values within standard ranges.k
be greater than the number of bits in the indices?
k
set bits are?
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int sumIndicesWithKSetBits(vector<int>& nums, int k) {
int sum = 0;
int n = nums.size();
for(int i = 0; i < n; ++i) {
if(__builtin_popcount(i) == k) {
sum += nums[i];
}
}
return sum;
}
};
int main() {
Solution sol;
vector<int> nums = {1, 2, 3, 4};
int k = 1;
int result = sol.sumIndicesWithKSetBits(nums, k);
cout << "Sum of values at indices with " << k << " set bits is: " << result << endl;
return 0;
}
__builtin_popcount
to count the number of set bits in the index.k
set bits.O(n)
where n
is the length of the array since we iterate through the array once and the __builtin_popcount
function operates in O(1)
time.O(1)
as we are utilizing a constant amount of extra space not dependent on input size.This method is efficient and leverages built-in functions for simplicity and speed.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?