3011. Find if Array Can Be Sorted #798
-
Topics: You are given a 0-indexed array of positive integers In one operation, you can swap any two adjacent elements if they have the same number of set bits1. You are allowed to do this operation any number of times (including zero). Return Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if the array can be sorted by only swapping adjacent elements that have the same number of set bits in their binary representation. Here’s the plan: Solution Steps:
Let's implement this solution in PHP: 3011. Find if Array Can Be Sorted <?php
/**
* Helper function to count set bits in a number
*
* @param $n
* @return int
*/
function countSetBits($n) {
$count = 0;
while ($num > 0) {
$count += $num & 1;
$num >>= 1;
}
return $count;
}
/**
* @param Integer[] $nums
* @return Boolean
*/
function canSortArray($nums) {
$prevSetBits = null; // Track the set bits count of the previous segment
$prevMax = PHP_INT_MIN; // Maximum value of the previous segment
$currMax = PHP_INT_MIN; // Maximum value of the current segment
$currMin = PHP_INT_MAX; // Minimum value of the current segment
foreach ($nums as $num) {
$setBits = countSetBits($num);
// If we're in a new segment (set bit count changed)
if ($setBits !== $prevSetBits) {
// Check if previous segment’s max is greater than current segment’s min
if ($prevMax > $currMin) {
return false;
}
// Start a new segment
$prevSetBits = $setBits;
$prevMax = $currMax;
$currMax = $num;
$currMin = $num;
} else {
// Continue with the current segment
$currMax = max($currMax, $num);
$currMin = min($currMin, $num);
}
}
// Final check: last segment's max should be <= last segment's min
return $prevMax <= $currMin;
}
// Test cases
$nums1 = [8, 4, 2, 30, 15];
$nums2 = [1, 2, 3, 4, 5];
$nums3 = [3, 16, 8, 4, 2];
$nums4 = [75, 34, 30];
echo canBeSorted($nums1) ? 'true' : 'false'; // Expected output: true
echo "\n";
echo canBeSorted($nums2) ? 'true' : 'false'; // Expected output: true
echo "\n";
echo canBeSorted($nums3) ? 'true' : 'false'; // Expected output: false
echo "\n";
echo canBeSorted($nums4) ? 'true' : 'false'; // Expected output: false
?> Explanation:
Complexity Analysis
This solution ensures that we only swap adjacent elements with the same set bit count, achieving a sorted order if possible. |
Beta Was this translation helpful? Give feedback.
We need to determine if the array can be sorted by only swapping adjacent elements that have the same number of set bits in their binary representation. Here’s the plan:
Solution Steps:
Key Observation: The operation allows us to swap adjacent elements only if they have the same number of set bits. This restricts swapping across elements with different numbers of set bits.
Plan: