1238. Circular Permutation in Binary Representation LeetCode Solution
In this guide, you will get 1238. Circular Permutation in Binary Representation LeetCode Solution with the best time and space complexity. The solution to Circular Permutation in Binary Representation problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Circular Permutation in Binary Representation solution in C++
- Circular Permutation in Binary Representation solution in Java
- Circular Permutation in Binary Representation solution in Python
- Additional Resources
Problem Statement of Circular Permutation in Binary Representation
Given 2 integers n and start. Your task is return any permutation p of (0,1,2…..,2^n -1) such that :
p[0] = start
p[i] and p[i+1] differ by only one bit in their binary representation.
p[0] and p[2^n -1] must also differ by only one bit in their binary representation.
Example 1:
Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]
Example 2:
Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n
Complexity Analysis
- Time Complexity:
- Space Complexity:
1238. Circular Permutation in Binary Representation LeetCode Solution in C++
class Solution {
public:
vector<int> circularPermutation(int n, int start) {
vector<int> ans;
for (int i = 0; i < 1 << n; ++i)
ans.push_back(start ^ i ^ i >> 1);
return ans;
}
};
/* code provided by PROGIEZ */
1238. Circular Permutation in Binary Representation LeetCode Solution in Java
class Solution {
public List<Integer> circularPermutation(int n, int start) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < 1 << n; ++i)
ans.add(start ^ i ^ i >> 1);
return ans;
}
}
// code provided by PROGIEZ
1238. Circular Permutation in Binary Representation LeetCode Solution in Python
class Solution:
def circularPermutation(self, n: int, start: int) -> list[int]:
return [start ^ i ^ i >> 1 for i in range(1 << n)]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.