LeetCode Entry

3392. Count Subarrays of Length Three With a Condition

27.04.2025 easy 2025 kotlin rust

subarrays 2a + 2c == b

3392. Count Subarrays of Length Three With a Condition easy blog post substack youtube 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/971

Problem TLDR

3-subarrays 2a + 2c == b #easy

Intuition

Constrains are small, even the brute-force solution is O(n)

Approach

  • let’s golf it
  • some CPU-cache friendliness possible

Complexity

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

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

Code


// 31ms
    fun countSubarrays(n: IntArray) = n.asList()
    .windowed(3).count { 2 * it.sum() == 3 * it[1] }


// 2ms
    fun countSubarrays(n: IntArray): Int {
        var c = 0; var l = 0; var m = -300
        for (r in n) {
            if (l + l + r + r == m) c++
            l = m; m = r
        }
        return c
    }


// 0ms
    pub fn count_subarrays(n: Vec<i32>) -> i32 {
        n[..].windows(3).filter(|w| 2 * w[0] + 2 * w[2] == w[1]).count() as _
    }


// 0ms
    int countSubarrays(vector<int>& n) {
        int c = 0, l = 0, m = 300;
        for (int r: n) c += l + l + r + r == m, l = m, m = r;
        return c;
    }