Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Binary Subarrays With Sum

Posted on October 28, 2018July 26, 2020 by braindenny

Binary Subarrays With Sum



Similar Problems:

  • Subarray Product Less Than K
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #subarray, #presum, #inspiring, #classic

In an array A of 0s and 1s, how many non-empty subarrays have sum S?

Example 1:

Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation: 
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

Note:

  1. A.length <= 30000
  2. 0 <= S <= A.length
  3. A[i] is either 0 or 1.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/binary-subarrays-with-sum
// Basic Ideas: Presum + Dynamic Programming
//     Count how many subarray ends with current item
// Complexity: Time O(n), Space (n)
func numSubarraysWithSum(A []int, S int) int {
    res, preSum := 0, 0
    h := map[int]int{0: 1}
    for _, v := range A {
       preSum += v
       res += h[preSum - S]
       h[preSum]++
    }
    return res
}
linkedin
github
slack

Post Views: 0
Posted in MediumTagged #classic, #inspiring, #subarray, presum

Post navigation

LeetCode: Unique Email Addresses
LeetCode: Number of Recent Calls

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.