Skip to main content

Practice: Contiguous Subarray Sum

Hard

This is an example coding practice lesson. These lessons include solutions in multiple programming languages and detailed explanations. Some also feature mock interview videos demonstrating how candidates approach the problem in real-time.

Use this coding practice to gauge your proficiency level. We recommend practicing a combination of both medium and hard questions since technical interviews usually include both.

Determine if a given array contains a subarray of at least two elements whose sum is a multiple of a specified number k.

An array is considered to have a "good subarray" if there exists at least one subarray (consisting of two or more elements) such that the sum of the elements in this subarray is a multiple of k.

For example, the array [23, 2, 4, 7] with k = 6 has a "good subarray" ([2, 4]), as the sum 6 is a multiple of k = 6. The array [5, 0, 0, 0] with k = 3 does not have any "good subarray", as no subarray of two or more elements sums to a multiple of 3.

Examples

nums = [23, 2, 4, 7], k = 6 output: true nums = [5, 0, 0, 0], k = 3 output: false nums = null, k = 1 output: false

In these examples, the output is true if there exists a "good subarray" in the given array nums for the specified k, and false otherwise.

Can you come up with a solution with a time complexity of O(n)?

Can you come up with a solution with a space complexity of O(n)?