Count Finished Tasks
Given an array of task statuses where each element is 1 (finished) or 0 (not finished), count how many tasks are finished. Return the total count of completed tasks.
For example, statuses [1, 0, 1, 1, 0] has 3 finished tasks. All zeros [0, 0, 0] has 0 finished tasks. All ones [1, 1, 1] has 3 finished tasks. An empty array returns 0.
Counting items that match a condition is a core data aggregation skill. It appears in project management (tracking completed milestones), inventory systems (counting available items), and quality assurance (counting passed tests).
The solution initializes a counter to 0, iterates through each status, and increments when the value equals 1. This accumulates the total count in a single pass with O(1) extra space.
Edge cases include an empty array (return 0), all tasks unfinished (return 0), and all tasks finished (count equals array length).
Example Input & Output
Three tasks are marked as finished.
An empty task list means there is nothing finished to count.
If nothing is finished, the count stays 0.
Algorithm Flow
Solution Approach
Iterate through the array and count elements equal to 1.
Initialize count to 0. Loop through each task status. If the status equals 1 (indicating a finished task), increment the counter. After processing all tasks, return the total count. The algorithm correctly returns 0 for empty arrays since the loop never executes.
Time complexity is O(n), space complexity is O(1). Each element is examined exactly once.
Best Answers
program count_finished_tasks
dictionary
tasks: array[1..100] of integer
finished_count, i, n: integer
algorithm
input(tasks)
finished_count <- 0
n <- tasks.length
for i <- 0 to n - 1 do
if tasks[i] = 1 then
finished_count <- finished_count + 1
endif
endfor
output(finished_count)
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
