Count Tested Devices After Test Operations — LeetCode 2960 Python Solution

EasyArrayCountingSimulation
Problem
#2960
Pattern
Hash Map
Reading time
2 min

The problem

You are given a 0-indexed integer array batteryPercentages having length n, denoting the battery percentages of n 0-indexed devices. Your task is to test each device i in order from 0 to n - 1, by performing the following test operations: If batteryPercentages[i] is greater than 0: Increment the count of tested devices.

Example

Input
batteryPercentages = [1,1,2,1,3]
Output
3
Explanation
Performing the test operations in order starting from device 0:

Python solution

Python
class Solution:
    def countTestedDevices(self, batteryPercentages: List[int]) -> int:
        ans = 0
        for x in batteryPercentages:
            ans += x > ans
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2960. Count Tested Devices After Test Operations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it 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 2960. Count Tested Devices After Test Operations?
LeetCode 2960. Count Tested Devices After Test Operations is rated Easy on LeetCode.
What is the time complexity of LeetCode 2960. Count Tested Devices After Test Operations?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2960. Count Tested Devices After Test Operations?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2960. Count Tested Devices After Test Operations cover?
LeetCode 2960. Count Tested Devices After Test Operations is tagged Array, Counting and Simulation 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