VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-original-number-by-flipping-k-unique-bits/

⇱ Find the original number by flipping K unique bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the original number by flipping K unique bits

Last Updated : 18 Mar, 2024

Given three numbers X, Y and Z and an integer K. The number X is obtained by flipping K unique bits in the binary representation of N. Additionally, Y and Z are further obtained by flipping K unique bits in the binary representation of N. The task is to determine the original number N.

Examples:

Input: X = 9, Y = 17, Z = 29, K=1
Output: 25
Explanation: X = 01001, Y = 10001, Z = 11101
since k = 1 only one bit is flipped from the original number
To get X from N 5th position from left is flipped
To get Y from N 4th position from left is flipped
To get Z from N 3rd position from left is flipped
so, original number would be 25: 11001

Input: X = 11, Y = 16, Z = 61, K = 2
Output: 25

Approach: To solve the problem, follow the below idea:

The approach involves identifying the common set of bit positions flipped in generating two given numbers from the original number and then flipping those bits in one of the numbers to reconstruct the original number.

Step-by-step algorithm:

  • Define a helper function helper(X, Y) that takes two numbers x and y and returns a HashSet containing the positions where bits are flipped between X and Y.
  • In the findNumber() function:
    • Call helper(X, Y) and helper(X, Z) to obtain the sets of flipped bit positions between X and Y, and X and Z respectively.
    • Intersect these sets to find the common set of flipped bit positions and store it in set A.
    • Iterate over each position in set A and flip the corresponding bit in X.
    • Return the updated X as the original number.

Below is the implementation of the algorithm:


Output
25

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment