Continuous Subarray Sum

Medium · Arrays & Hashing · Array · Hash Table · Math · Prefix Sum

Problem

You are given an array of non-negative integers nums and a positive integer k.

Return true if some contiguous subarray of length at least two has a sum that is a multiple of k, and false otherwise.

0 is a multiple of every k, so a subarray of two or more elements that sums to zero counts.

Examples

Input: nums = [5,1,4,2], k = 5
Output: true

The subarray [1, 4] has two elements and sums to 5.

Input: nums = [5,3], k = 5
Output: false

The only subarray with two or more elements is [5, 3], and 8 is not a multiple of 5.

Input: nums = [4,0,0], k = 7
Output: true

The subarray [0, 0] sums to 0, a multiple of 7.

Constraints

Approaches

Follow-up

Keeping the first index matters: it gives the longest stretch for each remainder, so the length check is as easy to pass as possible. The same "equal remainders" trick finds the shortest or the longest such subarray (keep the latest or the first index); those are the use cases below. If nums could be negative, Python's % still gives a remainder in [0, k), but in Java, C++ and Go you must fix negative remainders yourself.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…