algoadvance

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.

Clarifying Questions

  1. Q: What should be returned if nums is empty?
    • A: Return an empty array.
  2. Q: What happens if the digit to be removed is not present in some numbers?
    • A: Return those numbers unchanged.
  3. Q: Can nums contain negative numbers?
    • A: Assume for simplicity the numbers are non-negative integers.
  4. Q: What is the range of numbers in nums and the value of digit?
    • A: Assume that the integers in nums are in the range of 0 to 10^9, and digit is a single digit from 0 to 9.

Strategy

  1. Convert each number in the array nums to a string.
  2. Remove all occurrences of the specified digit in its string form.
  3. Convert the modified string back to an integer. If the resulting string is empty, convert it to 0.
  4. Collect the modified numbers into a new list.
  5. Return the new list.

Code

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]

Time Complexity

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.

Try our interview co-pilot at AlgoAdvance.com