Skip to main content

Posts

Showing posts from May, 2021

Competitive Programming: Find the two non-repeating elements

 Hello everyone ...  Here we are going to solve a  Competitive Programming  problem related to  Bit Manipulation. Problem Statement Given an array A containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other 2 numbers occur exactly once and are distinct . Find the two non-repeating numbers. Examples Input: N = 2 arr[] = {1, 2, 3, 2, 1, 4} Output: 3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1 arr[] = {2, 1, 3, 2} Output: 1 3 Explanation: 1 3 occur exactly once. Constraints 1 <= Length of array <= 10 6  1 <= Elements in array <= 5 * 10 6 Expectations Expected Time Complexity:  O(N) Expected Space Complexity:  O(1) Problem Link :  https://practice.geeksforgeeks.org/problems/finding-the-numbers0215/1 Solution The first idea that might come to your mind is to use Sorting and comparing adjacent elements in the sorted array to find the non-repeating elements. This solution's time complexity is O(N*logN) . But we are expecte

Competitive Programming: Count Set Bits in an Integer

Hello everyone ...  Here we are going to solve a Competitive Programming problem related to Bit Manipulation. Problem Statement Given a positive integer N , print count of set bits in it. Examples Input: N = 6 Output: 2 Explanation: Binary representation is '110' So the count of the set bit is 2. Input: 8 Output: 1 Explanation: Binary representation is '1000' So the count of the set bit is 1. Problem Link:  https://practice.geeksforgeeks.org/problems/set-bits0143/1  Solution Approach 1 In this approach, we will loop through all the bits of a given integer and check if the bit is set. If it is, then we will increment the count. To loop through the bits of an integer, we will iterate from LSB (Least Significant Bit) to MSB(Most Significant Bit), i.e, from Right to Left. In each iteration, we will increment the count by 1 if LSB (i.e. last bit) is set and then we will perform the Right Shift operation on the given integer by 1 time. C++ Code Time Complexi