The Indian Engineer

Problem 3133 Minimum Array End

Posted on 4 mins

Bit-Manipulation

Problem Statement

Link - Problem 3133

Question

You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x.

Return the minimum possible value of nums[n - 1].

 

Example 1:

Input: n = 3, x = 4

Output: 6

Explanation:

nums can be [4,5,6] and its last element is 6.

Example 2:

Input: n = 2, x = 7

Output: 15

Explanation:

nums can be [7,15] and its last element is 15.

 

Constraints:

Solution

class Solution {
public:
    long long minEnd(int n, int x) {

        long long res = x;
        n=n-1;
        while(n--){
            res = (res+1)|x;
        }
        return res;
    }
};

Complexity Analysis

| Algorithm                  | Time Complexity | Space Complexity |
| -------------------------- | --------------- | ---------------- |
| Bit-manipulation traversal | O(n)            | O(1)             |

Explanation

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Each element of the array should be obtained by “merging” x and v where v = 0, 1, 2, …(n - 1).

To merge x with another number v, keep the set bits of x untouched, for all the other bits, fill the set bits of v from right to left in order one by one.

So the final answer is the “merge” of x and n - 1.