11. Adding Ones
The problem can be found at the following link: Question Link
My Approach
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 theout
vector for each number encountered.Initialize the first element of the
arr
array as the count of 1 in theout
vector.Traverse the
arr
array starting from the second element. Set each element as the sum of the previous element in thearr
array and the count of the corresponding number in theout
vector.Finally, the
arr
array stores the cumulative counts of each number from 1 to n.
Time and Auxiliary Space Complexity
Time Complexity:
O(k + n)
, wherek
is the size of theupdates
array andn
is the size of thearr
array. We traverse theupdates
array once and thearr
array once, performing constant-time operations in each iteration.Auxiliary Space Complexity:
O(n)
since we use an additional vectorout
of sizen+1
to store the counts of each number.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated