← Home

1238. Circular Permutation in Binary Representation

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
123

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1238. Circular Permutation in Binary Representation, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • Hint 1: Use gray code to generate a n-bit sequence.
  • Hint 2: Rotate the sequence such that its first element is start.
  • https://openhome.cc/Gossip/AlgorithmGossip/GrayCode.htm

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are circularPermutation, p.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Hint 1: Use gray code to generate a n-bit sequence.
02//Hint 2: Rotate the sequence such that its first element is start.
03//Runtime: 176 ms, faster than 68.14% of C++ online submissions for Circular Permutation in Binary Representation.
04//Memory Usage: 15 MB, less than 100.00% of C++ online submissions for Circular Permutation in Binary Representation.
05//https://openhome.cc/Gossip/AlgorithmGossip/GrayCode.htm
06
07class Solution {
08public:
09    vector<int> circularPermutation(int n, int start) {
10        //gray code
11        int N = pow(2, n);
12        vector<int> p(N, 0);
13        
14        for(int i = 1; i < N; i++){
15            p[i] = p[i-1];
16            
17            if(i % 2 == 1){
18                //for odd's bit, invert last bit
19                p[i] += (p[i]%2) ? -1 : 1;
20            }else{
21                //for even's bit
22                //(the order is starting from most singificant bit)
23                //invert the bit before last 1
24                //find the last 1
25                int pos = N-1;
26                while(!(p[i] & (int)pow(2, N-1-pos))){
27                    pos--;
28                }
29                //the position before first 1
30                pos--;
31                //invert the bit
32                p[i] += p[i] & (int)pow(2, N-1-pos) ? -(int)pow(2, N-1-pos) : pow(2, N-1-pos);
33            }
34        }
35        
36        int startIndex = find(p.begin(), p.end(), start) - p.begin();
37        
38        //do rotation
39        p.insert(p.end(), p.begin(), p.begin()+startIndex);
40        p.erase(p.begin(), p.begin()+startIndex);
41        
42        return p;
43    }
44};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.