- Published on
Remove Duplicates from Sorted Array
- Authors

- Name
- QuickFeed
- @sahul_22_jr
Problem Statement
Solution
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
// Initialize a variable i to keep track of the position to overwrite in nums
int i = 0;
// Iterate through each element num in nums
for (const int num : nums)
// Check if either i is less than 1 (meaning first element) or num is greater than the previous element
if (i < 1 || num > nums[i - 1])
// If the condition is true, update the current element in nums and increment i
nums[i++] = num;
// Return the length of the modified nums array
return i;
}
};
Algorithm steps:
- Start with an index
iset to 0. - Iterate through each element
numin the given arraynums. - Check if
iis less than 1 (indicating the first element) or if the current elementnumis greater than the previous element innums. - If the condition is true, update the element at index
iinnumswith the current elementnumand incrementi. - Repeat steps 3-4 for all elements in
nums. - Return the value of
i, which represents the length of the modifiednumsarray without duplicates.
Time complexity:
- The time complexity of this code is O(n), where n is the length of the input array
nums. This is because we iterate through each element ofnumsonce.
Space complexity:
- The space complexity of this code is O(1), as we only use a constant amount of extra space regardless of the size of the input array
nums.
To reduce complexity, we can simplify the code by directly using the std::unique function from the <algorithm> header in C++. Here's the modified code:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
// Use the std::unique function to remove duplicates
nums.erase(std::unique(nums.begin(), nums.end()), nums.end());
// Return the new length of the modified nums array
return nums.size();
}
};
The time complexity of the modified code remains O(n), where n is the length of the input array nums, because std::unique has linear time complexity. However, the space complexity is O(1) because std::unique modifies the array in place without using any additional space.