Leetcode 1238. Circular Permutation in Binary Representation

Problem Explanation

The problem is about finding a circular permutation of binary numbers, which starts with a given number. In mathematics, a circular permutation is an ordered arrangement in which an increment of one position shifts every element by one place, and the first element fills in the vacated position.

For example, if we have 3 elements (1,2,3), we have the three following circular permutations: (1,2,3) โ†’ (2,3,1) โ†’ (3,1,2).

In this problem we're dealing with binary numbers, so if n is 3 and the starting number is 2 (010 in binary), one possible solution can be [2,6,7,5,4,0,1,3] where each number differs only by one bit in their binary representation.

Solution Description

The direct approach might not be feasible due to time and complexity constraints as generating and checking all permutations can be computationally heavy, especially when n is large.

An optimal approach is to use a gray code sequence generation. Gray code sequence is a sequence of binary numbers where each two consecutive numbers differ by one bit. The trick here is to use XOR (exclusive or) to generate the gray code sequence.

Algorithm walk through

Suppose n is 2 and start is 3. We need to generate a sequence of length 2โฟ = 4, Let's walk through each iteration:

  1. For i = 0, the generated number is 3 ^ 0 ^ 0 >> 1 = 3, so we push 3 to the answer vector.
  2. For i = 1, the generated number is 3 ^ 1 ^ 1>>1 = 2, so we push 2 to the answer vector.
  3. For i = 2, the generated number is 3 ^ 2 ^ 2>>1 = 0, so we push 0 to the answer vector.
  4. For i = 3, the generated number is 3 ^ 3 ^ 3>>1 = 1, so we push 1 to the answer vector.

Python Solution

1
2python
3class Solution:
4    def circularPermutation(self, n: int, start: int) -> List[int]:
5        #initialize empty res array
6        res = []
7        for i in range(1<<n):
8            # bitwise XOR operation to find the gray code and append in res array
9            res.append(start ^ i ^ i>>1)
10        return res

Java Solution

1
2java
3class Solution {
4    public List<Integer> circularPermutation(int n, int start) {
5        List<Integer> res = new ArrayList<>();
6        for (int i = 0; i < 1 << n; ++i)
7            res.add(start ^ i ^ i >> 1);
8        return res;
9    }
10}

C++ Solution

1
2cpp
3class Solution {
4public:
5    vector<int> circularPermutation(int n, int start) {
6        vector<int> res;
7        for (int i = 0; i < 1 << n; ++i)
8            res.push_back(start ^ i ^ i >> 1);
9        return res;
10    }
11};

JavaScript Solution

1
2javascript
3class Solution {
4    circularPermutation(n, start) {
5        let res = [];
6        for(let i = 0; i < 1<<n; i++)
7            res.push(start ^ i ^ i >> 1);
8        return res;
9    }
10}

C# Solution

1
2csharp
3public class Solution {
4    public IList<int> CircularPermutation(int n, int start) {
5        IList<int> res = new List<int>();
6        for (int i = 0; i < 1 << n; ++i)
7            res.Add(start ^ i ^ i >> 1);
8        return res;
9    }
10}

Conclusion

In summary, this problem requires generating a gray code sequence starting from a given number. By using bitwise XOR operation, we can easily accomplish the task in linear time complexity. In terms of space complexity, it needs O(2^n) to store the resulting sequence, where n is the input integer. The solution code is simple and easy to understand, leveraging the property of bitwise operations to generate a sequence where each two successive numbers differ by only one bit.

The implementation in the provided Python, Java, C++, JavaScript and C# codes are alike. They demonstrate versatility in different programming languages but all follow the same algorithm:

  1. Iterate from 0 to 2^n, inclusive.
  2. In each iteration, do the bitwise XOR operation with the start number and the gray code (i ^ (i >> 1)).
  3. Add the result to the array or list.

Bitwise operations are an essential aspect of computer science. They provide a way to manipulate a bit of data at the smallest scale, and are highly efficient. Understanding these operations can greatly enhance your problem-solving ability on binary related problems like this one.

This problem is a good exercise to get familiar with bitwise operations and understanding gray code sequences. As an extension, you can explore more about other binary sequences and their properties, such as the Hamming sequence. For further improvement, you might want to think about how to generate a circular permutation for any given array.

As a takeaway, remember to always break down complex problems into simpler parts, seek patterns, and leverage the given constraints to your advantage. This will help to reduce the problem to a simpler and easier format that can be solved with more straightforward methods. Happy coding!


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ