Find array elements with rightmost set bit at the position of the rightmost set bit in K

Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K.
Examples:
Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7
Output: { 3, 7, 9, 15 }
Explanation:
Binary representation of K (= 7) is 0111.
Rightmost set bit in 7 is at position 1.
Therefore, all odd array elements will have rightmost set bit at position 1.Input: arr[] = { 1, 2, 3, 4, 5 }, K = 3
Output: {1, 3, 5}
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say mask, to store the mask of K.
- Initialize a variable, say pos, to store the position of the rightmost set bit in K.
- Calculate the Bitwise AND of the mask and K i.e. pos = (mask & K)
- Traverse the array arr[] and for each array element:
- If mask & arr[i] == pos: Print arr[i].
- Otherwise, continue.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include "bits/stdc++.h"using namespace std;Â
// Function to find the mask for// finding rightmost set bit in KÂ Â Â Â int findMask(int K)Â Â Â Â {Â Â Â Â Â Â Â Â int mask = 1;Â Â Â Â Â Â Â Â while ((K & mask) == 0) Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â mask = mask << 1;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return mask;Â Â Â Â }Â
    // Function to find all array elements    // with rightmost set bit same as that in K    void sameRightSetBitPos(        int arr[], int N, int K)    {               // Stores mask of K        int mask = findMask(K);Â
        // Store position of rightmost set bit        int pos = (K & mask);Â
        // Traverse the array        for (int i = 0; i < N; i++)        {Â
            // Check if rightmost set bit of            // current array element is same as            // position of rightmost set bit in K            if ((arr[i] & mask) == pos)                cout << arr[i] << " ";        }    }Â
// Driver Codeint main(){    // Input        int arr[] = { 3, 4, 6, 7, 9, 12, 15 };        int N = sizeof(arr) / sizeof(arr[0]);        int K = 7;Â
        // Function call to find        // the elements having same        // rightmost set bit as of K        sameRightSetBitPos(arr, N, K);Â
    return 0;}Â
// This code is contributed by susmitakundugoaldanga. |
Java
// Java program for// the above approachÂ
import java.io.*;Â
class GFG {Â
    // Function to find the mask for    // finding rightmost set bit in K    static int findMask(int K)    {        int mask = 1;        while ((K & mask) == 0) {            mask = mask << 1;        }        return mask;    }Â
    // Function to find all array elements    // with rightmost set bit same as that in K    public static void sameRightSetBitPos(        int[] arr, int N, int K)    {        // Stores mask of K        int mask = findMask(K);Â
        // Store position of rightmost set bit        final int pos = (K & mask);Â
        // Traverse the array        for (int i = 0; i < N; i++) {Â
            // Check if rightmost set bit of            // current array element is same as            // position of rightmost set bit in K            if ((arr[i] & mask) == pos)                System.out.print(arr[i] + " ");        }    }Â
    // Driver Code    public static void main(String[] args)    {        // Input        int[] arr = { 3, 4, 6, 7, 9, 12, 15 };        int N = arr.length;        int K = 7;Â
        // Function call to find        // the elements having same        // rightmost set bit as of K        sameRightSetBitPos(arr, N, K);    }} |
Python3
# Python program for# the above approachÂ
# Function to find the mask for# finding rightmost set bit in Kdef findMask(K):Â Â Â Â mask = 1;Â Â Â Â while ((K & mask) == 0):Â Â Â Â Â Â Â Â mask = mask << 1;Â
    return mask;Â
# Function to find all array elements# with rightmost set bit same as that in Kdef sameRightSetBitPos(arr, N, K):Â Â Â Â Â Â Â # Stores mask of KÂ Â Â Â mask = findMask(K);Â
    # Store position of rightmost set bit    pos = (K & mask);Â
    # Traverse the array    for i in range(N):Â
        # Check if rightmost set bit of        # current array element is same as        # position of rightmost set bit in K        if ((arr[i] & mask) == pos):            print(arr[i], end=" ");Â
Â
# Driver Codeif __name__ == '__main__':    # Input    arr = [3, 4, 6, 7, 9, 12, 15];    N = len(arr);    K = 7;Â
    # Function call to find    # the elements having same    # rightmost set bit as of K    sameRightSetBitPos(arr, N, K);Â
    # This code contributed by shikhasingrajput |
C#
// C# program for the above approachusing System;public class GFG{Â
  // Function to find the mask for  // finding rightmost set bit in K  static int findMask(int K)  {    int mask = 1;    while ((K & mask) == 0) {      mask = mask << 1;    }    return mask;  }Â
  // Function to find all array elements  // with rightmost set bit same as that in K  public static void sameRightSetBitPos(    int[] arr, int N, int K)  {    // Stores mask of K    int mask = findMask(K);Â
    // Store position of rightmost set bit    int pos = (K & mask);Â
    // Traverse the array    for (int i = 0; i < N; i++) {Â
      // Check if rightmost set bit of      // current array element is same as      // position of rightmost set bit in K      if ((arr[i] & mask) == pos)        Console.Write(arr[i] + " ");    }  }Â
Â
  // Driver Code  static public void Main ()  {    // Input    int[] arr = { 3, 4, 6, 7, 9, 12, 15 };    int N = arr.Length;    int K = 7;Â
    // Function call to find    // the elements having same    // rightmost set bit as of K    sameRightSetBitPos(arr, N, K);  }}Â
// This code is contributed by code_hunt. |
Javascript
<script>// JavaScript program for the above approachÂ
// Function to find the mask for// finding rightmost set bit in KÂ Â Â Â function findMask(K)Â Â Â Â {Â Â Â Â Â Â Â Â let mask = 1;Â Â Â Â Â Â Â Â while ((K & mask) == 0)Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â mask = mask << 1;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return mask;Â Â Â Â }Â
    // Function to find all array elements    // with rightmost set bit same as that in K    function sameRightSetBitPos(arr, N, K)    {             // Stores mask of K        let mask = findMask(K);Â
        // Store position of rightmost set bit        let pos = (K & mask);Â
        // Traverse the array        for (let i = 0; i < N; i++)        {Â
            // Check if rightmost set bit of            // current array element is same as            // position of rightmost set bit in K            if ((arr[i] & mask) == pos)                document.write(arr[i] + " ");        }    }Â
// Driver CodeÂ
    // Input        let arr = [ 3, 4, 6, 7, 9, 12, 15 ];        let N = arr.length;        let K = 7;Â
        // Function call to find        // the elements having same        // rightmost set bit as of K        sameRightSetBitPos(arr, N, K);Â
// This code is contributed by Manoj.</script> |
Â
Â
3 7 9 15
Time Complexity: O(N)
Auxiliary Space: O(1)Â
Approach#2: Using list comprehension with bitwise operations
This approach to find the position of the rightmost set bit in the given number K, and then check if the rightmost set bit in each element of the given array is at the same position as K. If it is, then the element is added to the result list.
Algorithm
1. Find the position of the rightmost set bit in K using the bitwise AND operation with its 2’s complement.
2. Initialize an empty list result to store the elements of the array that have the rightmost set bit at the same position as K.
3. Iterate through each element num in the array:
a. Check if the rightmost set bit in num is at the same position as K using the bitwise AND operation with rightmost_set_bit.
b. If the rightmost set bit is at the same position, add num to the result list.
4. Return the result list.
C++
// C++ implementation of the above approach#include <iostream>#include <vector>using namespace std;Â
vector<int> find_elements(vector<int> arr, int K){    // bit in K get the position of the rightmost set    int rightmost_set_bit = K & -K;    vector<int> result;    for (int num : arr) {        // check if the rightmost set bit in num is at the        // same position as K        if (num & rightmost_set_bit == rightmost_set_bit) {            // add num to the result vector            result.push_back(num);        }    }    return result;}Â
int main(){Â Â Â Â vector<int> arr = { 3, 4, 6, 7, 9, 12, 15 };Â Â Â Â int K = 7;Â Â Â Â vector<int> result = find_elements(arr, K);Â Â Â Â for (int num : result) {Â Â Â Â Â Â Â Â cout << num << " ";Â Â Â Â }Â Â Â Â cout << endl;Â Â Â Â return 0;}Â
// This code is contributed by Sakshi |
Java
import java.util.ArrayList;import java.util.List;Â
public class Main {    public static List<Integer> findElements(List<Integer> arr, int K) {        // Bit in K to get the position of the rightmost set bit        int rightmostSetBit = K & -K;        List<Integer> result = new ArrayList<>();Â
        for (int num : arr) {            // Check if the rightmost set bit in num is at the same position as K            if ((num & rightmostSetBit) == rightmostSetBit) {                // Add num to the result list                result.add(num);            }        }        return result;    }// Driver Code    public static void main(String[] args) {        List<Integer> arr = List.of(3, 4, 6, 7, 9, 12, 15);        int K = 7;        List<Integer> result = findElements(arr, K);Â
        for (int num : result) {            System.out.print(num + " ");        }        System.out.println();    }} |
Python3
def find_elements(arr, K):    rightmost_set_bit = K & -K # get the position of the rightmost set bit in K    # check if the rightmost set bit in num is at the same position as K and add num to the result list    return [num for num in arr if num & rightmost_set_bit == rightmost_set_bit]Â
Â
arr = [3, 4, 6, 7, 9, 12, 15]K = 7result = find_elements(arr, K)print(" ".join(str(num) for num in result)) |
C#
using System;using System.Collections.Generic;Â
class Program{    static List<int> FindElements(List<int> arr, int K)    {        // Bit in K to get the position of the rightmost set bit        int rightmostSetBit = K & -K;        List<int> result = new List<int>();Â
        foreach (int num in arr)        {            // Check if the rightmost set bit in num is at the same position as K            if ((num & rightmostSetBit) == rightmostSetBit)            {                // Add num to the result list                result.Add(num);            }        }Â
        return result;    }Â
    static void Main()    {        List<int> arr = new List<int> { 3, 4, 6, 7, 9, 12, 15 };        int K = 7;Â
        List<int> result = FindElements(arr, K);Â
        foreach (int num in result)        {            Console.Write(num + " ");        }Â
        Console.WriteLine();    }} |
Javascript
// Javascript implementation of the above approachÂ
function find_elements(arr, K) {    // bit in K get the position of the rightmost set    let rightmost_set_bit = K & -K;    let result = [];    for (let num of arr) {        // check if the rightmost set bit in num is at the        // same position as K        if ((num & rightmost_set_bit) === rightmost_set_bit) {            // add num to the result vector            result.push(num);        }    }    return result;}Â
let arr = [3, 4, 6, 7, 9, 12, 15];let K = 7;let result = find_elements(arr, K);for (let num of result) {Â Â Â Â console.log(num);} |
3 7 9 15
Time complexity: O(n), where n is the length of the input array. This is because the code iterates through each element of the array once to check if the rightmost set bit is at the same position as K.
Auxiliary Space: Â O(m), where m is the length of the result list. In the worst case, all elements of the array could have the rightmost set bit at the same position as K, so the result list could have m elements. However, in practice, the size of the result list will likely be much smaller than the size of the input array, so the space complexity will be closer to O(1) in most cases.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



