FastPrepContinuous Subarray Sum Multiple

Continuous Subarray Sum Multiple

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given an integer array nums and a positive integer k, return true if some contiguous subarray contains at least two elements and its sum is an integer multiple of k. Return false otherwise.

A subarray uses consecutive positions from nums. A sum s is a multiple when s = m * k for some integer m. Zero is a multiple of every positive k, so a zero-sum range can qualify.

Function

checkSubarraySum(nums: int[], k: int) → boolean

Examples

Example 1

nums = [23,2,4,6,7]k = 6return = true

The adjacent values 2 and 4 sum to 6, so this two-element subarray qualifies.

Example 2

nums = [23,2,6,4,7]k = 6return = true

The whole array has five elements and sums to 42 = 7 * 6, so it qualifies.

Example 3

nums = [23,2,6,4,7]k = 13return = false

No contiguous subarray with at least two elements has a sum that is a multiple of 13.

Constraints

  • 1 <= nums.length <= 10^5.
  • 0 <= nums[i] <= 10^9.
  • 0 <= sum(nums) <= 2147483647.
  • 1 <= k <= 2147483647.

More Microsoft problems

See Microsoft hiring insights
public boolean checkSubarraySum(int[] nums, int k) {
    // write your code here
}
nums[23,2,4,6,7]
k6
expectedtrue
Checking account…