Destroy Sequential Targets — LeetCode 2453 Python Solution

MediumArrayHash TableCounting
Problem
#2453
Pattern
Hash Map
Reading time
2 min

The problem

You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.

Example

Input
nums = [3,7,8,1,1,5], space = 2
Output
1
Explanation
If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,...

Python solution

Python
class Solution:
    def destroyTargets(self, nums: List[int], space: int) -> int:
        cnt = Counter(v % space for v in nums)
        ans = mx = 0
        for v in nums:
            t = cnt[v % space]
            if t > mx or (t == mx and v < ans):
                ans = v
                mx = t
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2453. Destroy Sequential Targets is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2453. Destroy Sequential Targets?
LeetCode 2453. Destroy Sequential Targets is rated Medium on LeetCode.
What is the time complexity of LeetCode 2453. Destroy Sequential Targets?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2453. Destroy Sequential Targets?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2453. Destroy Sequential Targets cover?
LeetCode 2453. Destroy Sequential Targets is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview