Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 29, 2025 05:44
Show Gist options
  • Select an option

  • Save Ifihan/d5aa4535976e8548ff0b800e561698ef to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/d5aa4535976e8548ff0b800e561698ef to your computer and use it in GitHub Desktop.
Minimum Operations to Make Array Sum Divisible by K

Question

Approach

I observe that each decrement reduces the total sum by exactly 1. Let r = sum(nums) % k be the remainder we need to remove to make the sum divisible by k. I can always perform exactly r single-unit decrements across the elements (never needing any fancy distribution beyond reducing the total by r), so the minimum number of operations is r. If r == 0 no operations are needed.

Implementation

class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        total = sum(nums)
        return total % k

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment