Leetcode 2429: Minimize XOR

grid47
grid47
Exploring patterns and algorithms
Mar 9, 2024 6 min read

You are given two positive integers, num1 and num2. Your task is to find a positive integer x such that: 1. x has the same number of set bits (1’s in binary representation) as num2, and 2. The value of x XOR num1 is minimized. The XOR operation is performed bitwise. Your goal is to return the integer x.
Problem
Approach
Steps
Complexity
Input: You are given two positive integers num1 and num2.
Example: num1 = 4, num2 = 7
Constraints:
• 1 <= num1, num2 <= 10^9
Output: Return the integer x that satisfies the given conditions.
Example: Output: 5
Constraints:
• There will always be a unique solution.
Goal: The goal is to find the integer x such that it has the same number of set bits as num2 and minimizes the value of x XOR num1.
Steps:
• 1. Count the number of set bits (1's) in num2.
• 2. Try to set bits of x to match the set bits of num2 from the higher bits of num1, aiming to minimize the XOR result.
• 3. If there are still set bits remaining, set them in the lowest possible positions.
Goal: The solution must work within the provided constraints.
Steps:
• The number of set bits in num2 determines how many bits must be set in the result.
• The range of input values is large (1 <= num1, num2 <= 10^9).
Assumptions:
• The inputs num1 and num2 are positive integers.
• There is always a unique solution.
Input: num1 = 3, num2 = 5
Explanation: In this example, num1 is 3 (binary 0011) and num2 is 5 (binary 0101). We need to find a number with the same number of set bits as num2 and that minimizes the XOR with num1. The number 3 (binary 0011) is the answer, as it has the same number of set bits and gives the minimal XOR value (0).

Input: num1 = 1, num2 = 12
Explanation: Here, num1 is 1 (binary 0001) and num2 is 12 (binary 1100). The integer 3 (binary 0011) satisfies the condition as it has the same number of set bits as 12 and gives the minimal XOR with num1, resulting in a value of 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus