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
outof size n+1 with all elements initially set to 0. This vector will be used to store the counts of each number.Traverse the
updatesarray and increment the count in theoutvector for each number encountered.Initialize the first element of the
arrarray as the count of 1 in theoutvector.Traverse the
arrarray starting from the second element. Set each element as the sum of the previous element in thearrarray and the count of the corresponding number in theoutvector.Finally, the
arrarray stores the cumulative counts of each number from 1 to n.
Time and Auxiliary Space Complexity
Time Complexity:
O(k + n), wherekis the size of theupdatesarray andnis the size of thearrarray. We traverse theupdatesarray once and thearrarray once, performing constant-time operations in each iteration.Auxiliary Space Complexity:
O(n)since we use an additional vectoroutof sizen+1to store the counts of each number.
Code (C++)
class Solution{
public:
void update(int arr[], int n, int updates[], int k){
vector<int> out(n+1, 0);
for(int i = 0; i < k; ++i){
++out[updates[i]];
}
arr[0] = out[1];
for(int i = 2; i <= n; ++i){
arr[i-1] = arr[i-2] + out[i];
}
}
};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
Was this helpful?