2859. Sum of Values at Indices With K Set Bits
Problem Description
You have an array called nums
, and each element in the array is associated with an index from 0 to the length of the array minus 1. Your goal is to calculate the sum of elements whose indexes have a specific number of bits set to 1 when viewed in binary. This specific number of set bits is given by the integer k
.
For instance, if k
is 3 and you're looking at the index 7 (which is 0111
in binary), since 7 has three set bits, you would include the value of nums[7]
in your sum. You repeat this process for all indices in the nums
array and return the total sum.
Intuition
To solve this problem efficiently, you can iterate over each index of the nums
array while simultaneously checking how many set bits are in the binary representation of that index. If the count of set bits is equal to k
, then you add the value at that index to your running total sum.
For the implementation:
- You iterate through
nums
array usingenumerate
to get both index (i
) and value (x
). - For each index
i
, you check how many set bits it has by using the built-in Python methodbit_count()
. - If
i.bit_count()
is equal tok
, you include the valuex
in your sum. - You aggregate these values to determine the final answer, which is the sum of all the numbers at indices with
k
set bits.
This solution is direct and leverages Python's built-in functions to handle binary operations efficiently, avoiding the need for manual bit-counting or more complex bitwise manipulation.
Solution Approach
The solution uses a simple linear scan algorithm which is quite effective for this problem. No complex data structures or patterns are necessary.
Here is a step-by-step breakdown of the implementation using the provided solution code as a reference:
- We use a
for
loop in combination withenumerate
to iterate over thenums
array. This gives us access to both the index and the value at that index. - For each index
i
, we check the number of set bits in its binary representation. This is done using thebit_count()
method. - We include the value
x
if the number of set bits (1s in the binary form) of the indexi
is equal tok
. The conditioni.bit_count() == k
evaluates toTrue
orFalse
based on whether the number of set bits matchesk
. - We use the built-in
sum
function to add up all the valuesx
for which the corresponding indexi
satisfies the condition mentioned above.
In terms of algorithms and data structures, this solution can be categorized as a brute-force approach since it evaluates the condition for every element in the array without using a more nuanced algorithm or data structure to optimize the process. However, since the problem has to do with checking each index individually, the brute-force method is appropriate and efficient in this context, especially since Python's bit_count()
method is optimized internally.
The sum
expression employs a generator expression, which is more memory-efficient than building an intermediary list of elements to sum, as it calculates the sum on the fly.
In short, the solution is elegant, taking advantage of Python's language features to achieve the goal with minimal code.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's take an example where nums = [0, 1, 2, 4, 8, 16, 3, 5]
and k = 2
. We want to find the sum of elements in nums
where the indices have exactly two bits set to 1 when viewed in binary.
- We start with the first element,
nums[0]
which is0
. The index0
has 0 bits set to 1 when viewed in binary (0b0
), so it does not matchk
. - Move to the second element,
nums[1]
which is1
. The index1
has 1 bit set to 1 in binary (0b1
), so it also does not matchk
. - Continue to
nums[2]
which is2
. The index2
in binary is0b10
, which has1
bit set, not matchingk
. - Next is
nums[3]
at index3
, with a value of4
. Binary3
is0b11
, which has2
bits set. This matchesk
, so we include4
in our sum. - Move to
nums[4]
, value8
and index4
(0b100
). Index4
has only1
bit set, so we do not add8
to our sum. - For
nums[5]
, value16
at index5
(0b101
), the binary representation has2
set bits, matchingk
. We include16
. - At
nums[6]
, index6
(0b110
) has2
bits set. Sincek
is2
, we add value3
to our sum. - Lastly,
nums[7]
is5
, with index7
(0b111
), which has3
set bits, so it's not included.
Now, we sum up the included numbers: 4 + 16 + 3 = 23
.
So the final sum of the values in the nums
array at indices with exactly k
set bits is 23
.
Using the provided solution approach:
- We iterate over
nums
with the index and value. - For each index, we use
bit_count()
to count set bits. - We check if the count matches
k
- We conclude with the sum of values that match the condition.
In this example, we can see how the algorithm steps through each element and uses the bit_count()
function to filter and sum the correct elements efficiently.
Solution Implementation
1# Import the typing module to use the List type for type hinting
2from typing import List
3
4class Solution:
5 def sum_indices_with_k_set_bits(self, nums: List[int], k: int) -> int:
6 # Initialize the variable to store the sum of indices
7 sum_of_indices = 0
8
9 # Loop through each index and value in the list of numbers
10 for index, value in enumerate(nums):
11 # If the number of set bits (1s) in the binary representation of the index
12 # is equal to k, add the current index to the sum_of_indices
13 if bin(index).count("1") == k:
14 sum_of_indices += value
15
16 # Return the final sum of indices with exactly k set bits
17 return sum_of_indices
18
1public class Solution {
2
3 /**
4 * This function calculates the sum of the elements in the nums array at indices that have exactly k bits set to 1 in their binary representation.
5 * @param nums An array of integers.
6 * @param k The number of set bits (bits set to 1) desired in the index's binary representation.
7 * @return The sum of the elements at indices with exactly k set bits.
8 */
9 public int sumIndicesWithKSetBits(int[] nums, int k) {
10 int sum = 0; // Initialize the sum to 0.
11
12 // Iterate through the nums array.
13 for (int index = 0; index < nums.length; ++index) {
14 // If the current index has exactly k set bits, add the corresponding element to the sum.
15 if (bitCount(index) == k) {
16 sum += nums[index];
17 }
18 }
19
20 return sum; // Return the final sum.
21 }
22
23 /**
24 * This helper function counts the number of set bits (bits set to 1) in the binary representation of a number.
25 * @param number The number whose set bits are to be counted.
26 * @return The count of set bits in the number.
27 */
28 private int bitCount(int number) {
29 int count = 0; // Initialize the count of set bits to 0.
30
31 // Continue until all bits are processed.
32 while (number != 0) {
33 // Clear the least significant bit set (Brian Kernighan's Algorithm).
34 number &= (number - 1);
35 count++; // Increment the count for each bit cleared.
36 }
37
38 return count; // Return the count of set bits.
39 }
40}
41
1#include <vector> // Include the necessary header for the vector type
2
3class Solution {
4public:
5 // Function to sum the elements in 'nums' at indices with 'k' bits set
6 int sumIndicesWithKSetBits(vector<int>& nums, int k) {
7 int sum = 0; // Initialize the sum result to 0
8
9 // Iterate over all indices of the 'nums' vector
10 for (int index = 0; index < nums.size(); ++index) {
11 // Use the __builtin_popcount function to count the number of set bits in 'index'
12 // Check if the number of set bits is equal to 'k'
13 if (__builtin_popcount(index) == k) {
14 sum += nums[index]; // If so, add the value at this index to 'sum'
15 }
16 }
17
18 return sum; // Return the final sum of desired elements
19 }
20};
21
1/**
2 * This function calculates the sum of the elements in the nums array at indices that have exactly k bits set to 1 in their binary representation.
3 * @param nums - An array of numbers.
4 * @param k - The number of set bits (bits set to 1) desired in the index's binary representation.
5 * @returns The sum of the elements at indices with exactly k set bits.
6 */
7function sumIndicesWithKSetBits(nums: number[], k: number): number {
8 let sum = 0; // Initialize the sum to 0.
9
10 // Iterate through the nums array.
11 for (let index = 0; index < nums.length; ++index) {
12 // If the current index has exactly k set bits, add the corresponding element to the sum.
13 if (bitCount(index) === k) {
14 sum += nums[index];
15 }
16 }
17
18 return sum; // Return the final sum.
19}
20
21/**
22 * This helper function counts the number of set bits (bits set to 1) in the binary representation of a number.
23 * @param number - The number whose set bits are to be counted.
24 * @returns The count of set bits in the number.
25 */
26function bitCount(number: number): number {
27 let count = 0; // Initialize the count of set bits to 0.
28
29 // Continue until all bits are processed.
30 while (number) {
31 // Clear the least significant bit set (Brian Kernighan's Algorithm).
32 number &= number - 1;
33 count++; // Increment the count for each bit cleared.
34 }
35
36 return count; // Return the count of set bits.
37}
38
Time and Space Complexity
Time Complexity
The time complexity of the provided method sumIndicesWithKSetBits
primarily depends on the number of elements in nums
and the computation of bit_count
for each index.
- Iterating over all indices of the
nums
list: If there aren
elements innums
, this requiresO(n)
time. - For each index
i
, thebit_count()
operation is performed, which takesO(log(i))
time since it counts the number of set bits in the binary representation of the index.
Since i
ranges from 0
to n-1
, in the worst-case scenario, bit_count()
will be called with i = n-1
, which takes O(log(n-1))
time. Therefore, the combined time complexity for the computation over all indices would be O(n log(n))
.
Overall, the Time Complexity is O(n log(n))
.
Space Complexity
The space complexity is fairly straightforward to analyze:
- The sum function generates a temporary generator expression and does not store values, thus it uses constant space.
- No additional data structures are used that scale with the input size.
Therefore, the Space Complexity is O(1)
— constant space complexity, since extra space does not depend on the input size.
Learn more about how to find time and space complexity quickly using problem constraints.
A heap is a ...?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!