Reverse Bits
Reverse Bits
Section titled “Reverse Bits”
Easy
Day 3 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Reverse bits of a given 32-bits unsigned integer.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
n = 43261596 - Output:
964176192
Constraints:
Input must be a 32-bit unsigned integer
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Extract last bit of n, shift result left, shift n right, 32 times.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Bit Shifting Loop
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD A["Input Integer / Bits"] --> B["Apply Bitwise Operation (AND / XOR / Shift)"] B --> C{"Check Bit Condition"} C -- "Condition Met" --> D["Update Bit Count / Result"] C -- "Continue" --> E["Shift Bits (>>> 1 or & n-1)"] E --> B D --> F["Return Final Result"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function reverseBits(n) { let res = 0; for (let i = 0; i < 32; i++) { res = (res << 1) | (n & 1); n >>>= 1; } return res >>> 0;}- Time Complexity:
O(32) - Space Complexity:
O(1) - Explanation: 32 bit shifts.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function reverseBits(n) { let res = 0; for (let i = 0; i < 32; i++) { res = (res << 1) | (n & 1); n >>>= 1; } return res >>> 0;}- Time Complexity:
O(32) - Space Complexity:
O(1) - Explanation: Bitwise reverse using bit shift.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”Iterate 32 times, extracting lowest bit of n and adding it to res.
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Process all 32 bits from right to left.