Prefix Sum

Count Unique Characters of All Substrings

January 28, 2024
medium
Prefix Sum

Problem Statement # Given a string s, return the sum of the number of unique characters in all substrings of s. In other words, you will be given a string and you need to sum up the total number of unique characters that appear in every possible substring of the string. Example: Input: s = “ABA” Output: 9 Explanation: The unique characters in all substrings are [“A”,“B”,“A”,“AB”,“BA”,“ABA”], with counts [1,1,1,2,2,2]. ...

Subarray Sums Divisible by K

January 28, 2024
medium
Prefix Sum

Problem Statement # Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum is divisible by k. Example: Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by 5: [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3], [4, 5, 0, -2, -3, 1]. Solution Approach # The solution involves using a hashmap to store the frequency of prefix sum mod k and applying the prefix sum technique. ...

Balanced Subarray Sums

January 11, 2024
medium
Prefix Sum

Problem # Given an array of integers nums, find the length of the longest subarray where the sum of the first half of the subarray is equal to the sum of the second half of the subarray. If no such subarray exists, return 0. Example: Input: nums = [1, 2, 3, 0, 3, 2, 1] Output: 6 (The subarray [1, 2, 3, 0, 3, 2] has a balanced sum) Constraints: ...