Created
August 13, 2025 20:23
-
-
Save SuryaPratapK/d5f4270a5751fab5072db538ae411c30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int sortPermutation(vector<int>& nums) { | |
| int n = nums.size(); | |
| int max_k = pow(2,ceil(log2(n)))-1; | |
| int k = max_k; | |
| // Iterate and find max k value | |
| for(int i=0;i<n;++i){ | |
| // If current element is not at the correct position | |
| if(nums[i] != i) | |
| k &= nums[i]; | |
| } | |
| return k==max_k? 0: k; | |
| } | |
| }; | |
| /* | |
| //JAVA | |
| class Solution { | |
| public int sortPermutation(int[] nums) { | |
| int n = nums.length; | |
| if (n == 0) return 0; | |
| int pow2 = 1; | |
| while (pow2 < n) pow2 <<= 1; | |
| int max_k = pow2 - 1; | |
| int k = max_k; | |
| for (int i = 0; i < n; ++i) { | |
| if (nums[i] != i) k &= nums[i]; | |
| } | |
| return (k == max_k) ? 0 : k; | |
| } | |
| } | |
| #Python | |
| from typing import List | |
| class Solution: | |
| def sortPermutation(self, nums: List[int]) -> int: | |
| n = len(nums) | |
| if n == 0: | |
| return 0 | |
| pow2 = 1 | |
| while pow2 < n: | |
| pow2 <<= 1 | |
| max_k = pow2 - 1 | |
| k = max_k | |
| for i, val in enumerate(nums): | |
| if val != i: | |
| k &= val | |
| return 0 if k == max_k else k | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment