11. Adding Ones
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To solve the problem, I have used the following approach:
Initialize a vector out
of size n+1 with all elements initially set to 0. This vector will be used to store the counts of each number.
Traverse the updates
array and increment the count in the out
vector for each number encountered.
Initialize the first element of the arr
array as the count of 1 in the out
vector.
Traverse the arr
array starting from the second element. Set each element as the sum of the previous element in the arr
array and the count of the corresponding number in the out
vector.
Finally, the arr
array stores the cumulative counts of each number from 1 to n.
Time Complexity: O(k + n)
, where k
is the size of the updates
array and n
is the size of the arr
array. We traverse the updates
array once and the arr
array once, performing constant-time operations in each iteration.
Auxiliary Space Complexity: O(n)
since we use an additional vector out
of size n+1
to store the counts of each number.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.