#2960

Count Tested Devices After Test Operations

Easy
ArraySimulationCountingSimulationArray Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the observation that we can keep track of the number of previously tested devices. A device can be tested if its battery percentage is greater than the number of devices tested so far, allowing us to avoid unnecessary iterations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a count of tested devices to 0.
  2. 2Step 2: Loop through each device in the batteryPercentages array.
  3. 3Step 3: If the current device's battery percentage is greater than the count of tested devices, increment the count.
  4. 4Step 4: The battery percentage of the current device will affect the subsequent devices, so we adjust the count accordingly.
solution.py12 lines
1# Full working Python code
2
3def countTestedDevices(batteryPercentages):
4    tested_count = 0
5    n = len(batteryPercentages)
6    for i in range(n):
7        if batteryPercentages[i] > tested_count:
8            tested_count += 1
9    return tested_count
10
11# Example usage
12print(countTestedDevices([1, 1, 2, 1, 3]))

Complexity note: The time complexity is O(n) since we only loop through the array once, making it much more efficient than the brute force approach.

  • 1Devices can only be tested if their battery percentage is greater than the number of devices tested so far.
  • 2The brute force method can be inefficient due to repeated updates on the battery percentages.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.