Problem 523

Abstract / Summary

Given a list of integers and a number, check if there is a continuous part of the list whose elements sum to that number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0523.py

class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        # the math behind my solution:
        # if   sum([a,b]) % k == sum([a,b,c,d]) % k
        # then sum([c,d]) % k == 0

        # store position of the first time we observe a modulo
        modulo = { }

        total = 0
        for i, n in enumerate(nums):
            total += n
            group  = total % k

            # a good subarray could start with the very first element
            if group == 0 and i >= 1:
                return True

            # we had the same modulo
            if group in modulo:
                # but good subarrays have at least 2 elements
                if i - modulo[group] >= 2:
                    return True
            else:
                modulo[group] = i

        # the whole input may be good, after all
        return False
28 lines | 897 bytes | submitted March 27, 2024 | GitHub   53% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 32% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Math
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether a contiguous sub-array of length at least two exists whose sum is a multiple of a given integer k. It relies on the mathematical observation that two prefix sums sharing the same remainder when divided by k imply that the intermediate segment’s sum is divisible by k. The algorithm walks through the input once, maintaining a running total and a dictionary that records the earliest index at which each remainder appears.

Key Steps

Initialization

The method begins by creating an empty dictionary to map remainders to their first occurrence index and a variable to accumulate the running sum.

modulo = {}
total = 0

Iterating Through the Array

For each element, the running total is updated and the current remainder (group) with respect to k is computed.

for i, n in enumerate(nums):
    total += n
    group = total % k

Immediate Success When Remainder Is Zero

If the remainder becomes zero and the current position is at least the second element, the sub-array from the start up to the current index satisfies the condition, and the function returns True.

if group == 0 and i >= 1:
    return True

Detecting Repeated Remainders

When the current remainder has been seen before, the distance between the present index and the stored index is examined. A distance of two or more guarantees a sub-array of the required minimum length, prompting an early return.

if group in modulo:
    if i - modulo[group] >= 2:
        return True
else:
    modulo[group] = i

Completion Without Finding a Valid Sub-array

If the loop finishes without triggering any of the early returns, the method concludes that no qualifying sub-array exists and returns False.

return False

Edge Cases Handled

The algorithm explicitly checks for a remainder of zero after processing at least two elements, which covers the scenario where the qualifying sub-array begins at the very first element. By storing only the first occurrence of each remainder, it ensures that any later matching remainder will produce the longest possible distance, thereby respecting the minimum length requirement. The condition i - modulo[group] >= 2 prevents false positives from sub-arrays of length one.

Performance Optimizations

The solution processes the input list in a single linear pass, updating the running total and performing constant-time dictionary lookups for each element. By returning immediately upon detecting a valid sub-array, it avoids unnecessary further iteration. The dictionary holds at most one entry per distinct remainder, which limits auxiliary storage to the number of unique remainders encountered. This combination of early exit and minimal bookkeeping yields an efficient execution profile for large input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like a game where numbers are lined up in a row. The goal is to see if any group of neighbors adds up to a special number, which is k. Imagine you are walking down the line of numbers and keeping a running tally of how much you have collected so far.

Every time the tally gets big, you divide it by k and keep the leftover part. This leftover part is like a reminder that helps track where you are. If you ever see the same leftover part again, it means the numbers you picked up in between those two spots add up to a multiple of k. Because the code wants to make sure there are at least two numbers in the group, it checks how far apart those two spots are. If there is enough space between them, the search is a success. If the running tally divides perfectly by k right from the start, that also counts as a win. Everything is simply a way to keep track of the math so the computer can find the right group of numbers without checking every single tiny combination.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.14

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
lzl124631x C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
lzl124631x C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
yuanliu666 Kotlin
zfang399 C++
39 links | 26 authors | 11 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 medium 3 hard
5 solutions   March 27, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality