Input: N =22Output: 32Explanation: Binary representation of 22is`10110`, which is not sparse. The next sparse number is`32`(binary `100000`), which has no adjacent ones.
Input: N =37Output: 37Explanation: Binary representation of 37is`100101`, which is sparse because there are no adjacent ones. Hence, the smallest sparse number greater than or equal to 37is37 itself.
Binary Representation: Observing the binary representation of a number makes it straightforward to identify whether it is sparse.
Non-Adjoining Ones: If adjacent ones exist, they violate the sparse condition and necessitate corrections to the binary digits.
Modifying Bits: To efficiently find the next sparse number greater than or equal to N, manipulate the binary digits of N to eliminate consecutive ones.
Backtracking Propagation: If consecutive ones are found, reset specific bits and propagate changes leftward to ensure higher-order bits maintain sparsity.
classSolution {
publicintsmallestSparse(int n) {
// Store the binary digits of the numberint[] binary =newint[32];
int index = 0;
int num = n;
// Convert to binary and store digits in an arraywhile (num > 0) {
binary[index++]= num % 2;
num /= 2;
}
// Ensure sparsityboolean changed =false;
for (int i = 1; i < index; i++) {
if (binary[i]== 1 && binary[i - 1]== 1) {
binary[i]= 0;
changed =true;
for (int j = i + 1; j < 32; j++) {
binary[j]= 0;
}
num = 0;
for (int k = 0; k < index; k++) {
num = num + binary[k]* (1 << k);
}
break;
}
}
return num;
}
}
classSolution:
defsmallestSparse(self, n: int) -> int:
# Convert the integer to a list of binary digits binary = list(bin(n)[2:])
length = len(binary)
# Flag indicating whether the number was changed changed =False# Traverse the binary representation to identify adjacent onesfor i in range(length -1):
if binary[i] =='1'and binary[i +1] =='1':
# Fix the first "1" and reset the right-side bits changed =True binary[i +1] ='0'for j in range(i +2, length):
binary[j] ='0'# Convert back to an integer result = int("".join(binary), 2)
return self.smallestSparse(result)
# If no changes, the number is already sparsereturn int("".join(binary), 2)
⏰ Time complexity: O(n log n). The algorithm inspects and modifies bits iteratively, moving leftward as needed. Given k as the number of bits of N, the complexity is O(k) because we process at most all bits of N.
🧺 Space complexity: O(1). The algorithm utilises constant auxiliary space for bit manipulation.