Problem 697

Abstract / Summary

Find the highest frequency of any number in the list and how many numbers have that frequency.

Note

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

Python 0697.py

class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        # count nums and track first and last position of each number
        freq  = defaultdict(int)
        first = {}
        last  = {}
        for i in range(len(nums)):
            n = nums[i]
            freq[n] += 1
            if n not in first:
                first[n] = i
            last[n] = i

        degree = max(freq.values())
        if degree == 1:
            return 1

        # minimum distance between last and first for each number of highest degree
        highest = set(f for f in freq if freq[f] == degree)

        result = len(nums)
        for h in highest:
            result = min(result, last[h] - first[h] + 1)

        return result
25 lines | 771 bytes | submitted September 13, 2023 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
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 defines a Solution class with a single method findShortestSubArray. The method receives a list of integers and returns the length of the shortest contiguous subarray whose degree (the maximum frequency of any element) matches the degree of the entire input list. The algorithm proceeds in a single linear scan to collect frequency information and positional boundaries for each distinct value, then derives the minimal subarray length from the elements that achieve the overall degree.

Frequency Counting and Position Tracking

The first loop iterates over the indices of nums. For each element n it increments a frequency counter, records the first occurrence if it has not been seen before, and updates the last occurrence on every visit. This simultaneous collection of three pieces of information-frequency, first index, and last index-eliminates the need for multiple passes.

freq  = defaultdict(int)
first = {}
last  = {}
for i in range(len(nums)):
    n = nums[i]
    freq[n] += 1
    if n not in first:
        first[n] = i
    last[n] = i

By using a defaultdict for freq and plain dictionaries for first and last, the code achieves constant-time updates and lookups for each element.

Determining the Global Degree

After the scan, the algorithm computes the degree of the whole array by taking the maximum of the frequency values. An immediate check for a degree of one handles the edge case where every element is unique; in that situation the shortest subarray is any single element, so the method returns 1 without further work.

degree = max(freq.values())
if degree == 1:
    return 1

Selecting Elements with Maximal Frequency

The next step isolates the set of numbers whose frequency equals the global degree. This is performed with a set comprehension that filters the keys of freq. The resulting collection, highest, contains exactly those candidates that could define the minimal subarray.

highest = set(f for f in freq if freq[f] == degree)

Using a set ensures that each candidate is considered once, even if the underlying dictionary contains many entries.

Computing the Minimal Subarray Length

The algorithm initializes result with the length of the entire array, guaranteeing an upper bound. It then iterates over each element h in highest, calculating the length of the subarray that spans from the first to the last occurrence of h. The expression last[h] - first[h] + 1 yields the inclusive distance between those positions. The min function updates result whenever a shorter span is found.

result = len(nums)
for h in highest:
    result = min(result, last[h] - first[h] + 1)

Finally, result is returned as the length of the shortest subarray sharing the array’s degree.

return result

Edge Cases Handled

The implementation gracefully handles several boundary conditions:

  • Single-element input: The loop records a frequency of one, the degree check triggers the early return, and the method yields 1.
  • All distinct elements: The degree is 1, invoking the early return path, which correctly identifies any single element as the minimal subarray.
  • Multiple elements sharing the maximal frequency: By collecting all such elements in highest, the code evaluates each candidate’s span and selects the smallest, ensuring correctness when more than one value attains the degree.
  • Elements whose first and last occurrences coincide: For a value that appears only once but still participates in the degree (possible only when the degree is 1), the early return covers this scenario. For values with higher frequency, the calculation last[h] - first[h] + 1 naturally yields 1 when the first and last indices are identical, though this cannot happen when the frequency exceeds one.

Performance Optimizations

The solution is optimized for speed and memory usage through several deliberate choices:

  • Single traversal: All required statistics are gathered in one pass over nums, avoiding redundant scans.
  • In-place updates: The dictionaries are updated directly without auxiliary data structures, keeping the memory footprint proportional to the number of distinct values.
  • Early exit for trivial degree: Detecting a degree of 1 allows the method to bypass the later set construction and loop, saving work for the common case of all unique elements.
  • Set comprehension for candidate selection: Building highest as a set filters the relevant keys in a concise expression, avoiding an explicit loop that would otherwise require additional condition checks.
  • Incremental minimization: Maintaining a running result and applying min inside the loop prevents the need for a separate pass to find the smallest span after all candidates have been examined.

These design decisions collectively ensure that the algorithm runs efficiently even for large input arrays, leveraging constant-time dictionary operations and minimizing the number of iterations required.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of numbered toy blocks. Some numbers show up a lot, some only once, and a few are the champions because they appear more often than any others. The goal is to find those champion numbers and zoom in on the smallest section of the line that holds all of them.

First, the code walks down the line of blocks one by one to keep a diary. In this diary, it writes down how many times each number appears. It also remembers exactly where each number first starts to show up and where it finally stops waving hello.

After filling out the diary, the code looks to see how many times the most popular number shows up. This is called the degree. If every number only appears once, the answer is just one.

Next, the code hunts for all the numbers that share that top championship score. It looks at the very first time and the very last time one of those champion numbers appeared. By subtracting the start spot from the end spot and adding one, it figures out how long that specific section of the line is. It keeps checking every champion number to see which one creates the shortest path from start to finish. Once it checks all the champions, it knows the tiniest length needed to capture all the appearances of a champion number.

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.07

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
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
zfang399 C++
37 links | 24 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

14 solutions   September 13, 2023

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