LeetCode Entry

2033. Minimum Operations to Make a Uni-Value Grid

28.04.2026 medium 2026 kotlin rust

Min ops to make all numbers equal by +-X

2033. Minimum Operations to Make a Uni-Value Grid medium substack youtube

https://dmitrysamoylenko.com/leetcode/

28.04.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1341

Problem TLDR

Min ops to make all numbers equal by +-X

Intuition

    // 1 4       x=3
    //+3
    //
    // 1 8 8 8 8  x=7
    //
    // is the baseline binary searchable?
    //
    // 1 1 3 5 5   x=2
    // 2 2 1 0 0
    // 1 1 0 1 1
    // 0 0 1 2 2
    //
    // 1 1 1 1 1    %2 same reminder
    // subtract reminder
    // 0 0 2 4 4, then divide by x
    // 0 0 1 2 2  this is array of counts from zero
    //            now find a median?
    // 2 4 6 8   x=2
    // 1 2 3 4 sum=10
    //          maybe consider each item as base and check
    // *
    // 1 *
    // 2 1 *
    // 3 2 1 *
    // 2 1 * 1
    // 1 * 1 2
    // * 1 2 3
    //
    // 1 4 4 5 8
    // * 3 3 4 7  right=3+3+4+7=17 left = 0
    // 3 * 0 1 4  right=  0+1+4=5=17-4*(4-1) left=0+(4-1)=3
    // 3 0 * 1 4  right= 5-3*(0-0) left=3+(0-0)
    // 4 1 1 * 3  right= 5-2*(5-4)=3 left=3+3*(5-4)=6
    // 7 4 4 3 *  right= 3-1*(8-5)=0 left=6+4*(8-5)=18
    //
  1. baseline of each value sequence is value %X
  2. number of ops is (V - V%X)/X
  3. scan from left to right, see how number of ops to the right changes after each move

Approach

  • if you know math, just use median, it is the middle of the array
  • kotlin&rust has a cool way to flatten grid

Complexity

  • Time complexity: \(O(nm)\)

  • Space complexity: \(O(nm)\)

Code

    fun minOperations(g: Array<IntArray>, v: Int) = g.reduce{a,b->a+b}
    .sorted().run{sumOf {if((it-get(0))%v>0)return-1;abs(it-get(size/2))/v}}
    pub fn min_operations(g: Vec<Vec<i32>>, x: i32) -> i32 {
        let mut a=g.concat();a.sort();let m=a[a.len()/2];
        if a.iter().any(|v|(v-a[0])%x!=0){-1}else{a.iter().map(|v|(v-m).abs()/x).sum()}
    }