Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1238: Circular Permutation in Binary Representation

In this guide, we solve Leetcode #1238 Circular Permutation in Binary Representation in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Bit Manipulation, Math, Backtracking

Intuition

We must explore combinations of choices, but many branches can be pruned early.

Backtracking enumerates valid candidates while keeping the search space under control.

Approach

Use DFS to build candidates step by step, and backtrack when constraints are violated.

Pruning keeps the exploration practical for typical constraints.

Steps:

  • Define the decision tree.
  • DFS through choices and backtrack.
  • Prune invalid paths early.

Example

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]

Python Solution

class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: g = [i ^ (i >> 1) for i in range(1 << n)] j = g.index(start) return g[j:] + g[:j]

Complexity

The time complexity is O(2n)O(2^n)O(2n), and the space complexity is O(2n)O(2^n)O(2n). The space complexity is O(2n)O(2^n)O(2n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy