Subarray Division 2

Sort by

recency

|

116 Discussions

|

  • + 0 comments

    My rust solution:

    fn birthday(s: &[i32], d: i32, m: i32) -> i32 {
        let m = m as usize;
        (0..s.len())
            .filter(|&i| i + m <= s.len())
            .filter(|&i| s[i..i + m].iter().sum::<i32>() == d)
            .count() as i32
    }
    
  • + 1 comment

    // sliding window method

    def birthday(s, d, m):

    c = 0
    for i in range(len(s)):
        if sum(s[i:i + m]) == d:
            c += 1
    return c
    
  • + 0 comments

    o(n), assertions, performance, c++))

    int birthday(vector<int> s, int d, int m) {
        assert(s.size() > 0 && d > 0 && m > 0);
        int sum = accumulate(s.cbegin(), s.cbegin() + m, 0);
        int r = 0;
        
        for (int i = 0, e = s.size() - m; i < e; ++i)
        {
            if (sum == d)
            {
                ++r;
            }
            
            sum += s[i + m];
            sum -= s[i];
        }
        
        if (sum == d)
        {
            ++r;
        }
        
        return r;
    }
    
  • + 0 comments

    O(n) prefix sum solution in Golang

    func birthday(s []int32, d int32, m int32) int32 {
        prefixSums := make([]int32, len(s)+1)
        for i, n := range s {
            prefixSums[i+1] = prefixSums[i] + n
        }
        
        var countOfSegments int32
        for i := m; i < int32(len(prefixSums)); i++ {
            if prefixSums[i] - prefixSums[i-m] == d {
                countOfSegments++
            }
        }
        return countOfSegments
    }
    
  • + 0 comments

    Kotlin version

    fun birthday(s: Array<Int>, d: Int, m: Int): Int {
        return s.toList()
        .windowed(size = m, step = 1)
        .filter { it.sum() == d }.size
    }