Similar Problems

Similar Problems not available

Circular Permutation In Binary Representation - Leetcode Solution

Companies:

LeetCode:  Circular Permutation In Binary Representation Leetcode Solution

Difficulty: Medium

Topics: math backtracking bit-manipulation  

Problem Statement:

Given an integer n, return a list of all possible strings of length n representing binary numbers with circular permutation.

Example 1:

Input: n = 2 Output: ["00","01","10","11"] Explanation: The circular permutations of "00" are "00", "00". The circular permutations of "01" are "01", "10". The circular permutations of "10" are "10", "01". The circular permutations of "11" are "11", "11".

Example 2:

Input: n = 3 Output: ["000","001","010","101","011","110","111"] Explanation: The circular permutations of "000" are "000", "000", "000". The circular permutations of "001" are "001", "010", "100". The circular permutations of "010" are "010", "100", "001". The circular permutations of "101" are "101", "011", "110". The circular permutations of "011" are "011", "110", "101". The circular permutations of "110" are "110", "101", "011". The circular permutations of "111" are "111", "111", "111".

Solution:

The solution to the problem can be obtained by generating all possible binary numbers of length n and then considering their circular permutations. For generating binary numbers, we can use a recursive function that starts from an empty string and appends either "0" or "1" to it and calls itself with the updated string and depth until the desired length is reached. After generating all binary numbers of length n, we can consider their circular permutations by rotating them left or right and adding them to the result list.

The following is the implementation of the solution in Python:

class Solution: def circularPermutation(self, n: int) -> List[str]: # generate all binary numbers of length n nums = self.generateBinaryNumbers(n) # generate all circular permutations of binary numbers circular_nums = set() for num in nums: for i in range(n): circular_num = num[i:] + num[:i] circular_nums.add(circular_num) # convert set to list and return return list(circular_nums)

def generateBinaryNumbers(self, n: int) -> List[str]:
    # recursive function to generate binary numbers
    def helper(depth, current):
        if depth == n:
            return [current]
        result = []
        result += helper(depth+1, current + "0")
        result += helper(depth+1, current + "1")
        return result
    
    return helper(0, "")

Circular Permutation In Binary Representation Solution Code

1