Minimum Operations to Make a Special Number - O(n) - Two Pointers [JS]
Solution: Two Pointers
Find the minimum operations to make num end with one of ['00', '25', '50', '75']
.
Use two pointers and iterate through num from right to left, greedily matching the end digits.
Special case: We can also turn num into 0
, which will take n - 1
operations if num contains '0'
, otherwise n
operations.
Time Complexity: O(5n)
Space Complexity: O(1)
var minimumOperations = function(num) {
let possibleEndDigits = ['00', '25', '50', '75'];
let minOperations = num.includes('0') ? num.length - 1 : num.length; // turn number into 0
for (let endDigits of possibleEndDigits) {
minOperations = Math.min(minOperations, operationsToEndWith(num, endDigits));
}
return minOperations;
};
function operationsToEndWith(num, endDigits) {
let n = num.length, operations = 0, j = endDigits.length - 1;
for (let i = n - 1; i >= 0; i--) {
if (num[i] === endDigits[j]) {
j--;
if (j === -1) return operations;
} else {
operations++;
}
}
return n;
}
Comments
Post a Comment