You are given an integer array nums
and another integer digit
. Your task is to remove all instances of the digit
from each number in the array nums
. Return the array after removing the specified digit.
For example, if nums
= [123, 456, 789] and digit
= 5, the answer would be [123, 46, 789] because we remove the digit 5
from the number 456 making it 46.
nums
is empty?
digit
to be removed is not present in some numbers?
nums
contain negative numbers?
nums
and the value of digit
?
nums
are in the range of 0 to 10^9, and digit
is a single digit from 0 to 9.nums
to a string.digit
in its string form.def remove_digit(nums, digit):
digit_str = str(digit) # Convert digit to string for easy removal
result = []
for num in nums:
num_str = str(num) # Convert number to string
new_num_str = num_str.replace(digit_str, '') # Remove specified digit
# Convert back to integer, use 0 if the resulting string is empty
new_num = int(new_num_str) if new_num_str else 0
result.append(new_num)
return result
# Example usage
print(remove_digit([123, 456, 789], 5)) # Output: [123, 46, 789]
.replace()
function operates in O(k) time for each string.Therefore, for an array of length n, the overall time complexity is O(n * k), where n is the length of nums
and k is the maximum number of digits in any number of nums
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?