Minimum Flips to Make a OR b Equal to c - Problem

Given three positive numbers a, b, and c, return the minimum number of bit flips required to make (a OR b) == c.

A flip operation consists of changing any single bit from 1 to 0 or from 0 to 1 in the binary representation of a number.

The bitwise OR operation returns 1 if at least one of the corresponding bits is 1, otherwise 0.

Input & Output

Example 1 — Basic Case
$ Input: a = 2, b = 7, c = 5
Output: 2
💡 Note: Binary: a=010, b=111, c=101. Current a|b=111, target=101. Need to flip bits 1 in both a and b to make them 0.
Example 2 — No Flips Needed
$ Input: a = 4, b = 2, c = 6
Output: 0
💡 Note: Binary: a=100, b=010, c=110. Current a|b=110 equals target c=110, so no flips needed.
Example 3 — Need More 1s
$ Input: a = 1, b = 2, c = 7
Output: 1
💡 Note: Binary: a=001, b=010, c=111. Current a|b=011, need 111. Must flip bit 2 in either a or b to 1.

Constraints

  • 1 ≤ a, b, c ≤ 109

Visualization

Tap to expand
Minimum Flips to Make a OR b Equal to c INPUT Binary Representations a = 2: 0 1 0 b = 7: 1 1 1 c = 5: 1 0 1 bit 2 bit 1 bit 0 Current: a OR b 1 1 1 = 7 Input Values: a=2, b=7, c=5 ALGORITHM STEPS 1 Compare bit by bit Check each position in a, b, and c 2 If c bit = 0 Both a and b bits must be 0 (flip each 1) 3 If c bit = 1 At least one of a or b must be 1 (flip if both 0) 4 Count total flips Sum all required bit changes Bit Analysis: Pos2: a=0,b=1 OR=1 c=1 OK Pos1: a=1,b=1 OR=1 c=0 +2 Pos0: a=0,b=1 OR=1 c=1 OK Total Flips: 2 FINAL RESULT Before (a OR b): 1 1 1 = 7 Flip 2 bits After (a OR b) = c: 1 0 1 = 5 Flips Required: Bit 1 of a: 1 --> 0 Bit 1 of b: 1 --> 0 Output: 2 Key Insight: When c's bit is 0, we need BOTH a and b bits to be 0. If a=1 and b=1, we need 2 flips (not 1). When c's bit is 1, we need at least one of a or b to be 1. If both are 0, we need just 1 flip. Time Complexity: O(max(log a, log b, log c)) | Space Complexity: O(1) TutorialsPoint - Minimum Flips to Make a OR b Equal to c | Optimal Solution
Asked in
Facebook 15 Microsoft 12 Amazon 8
28.0K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen