Questions worksheet (behavioral)
Minimum remove to make valid parentheses (Leetcode 1249)
nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.s.
Examples:
nums = [1,1,2], Output: 2. The resulting nums will look lie: nums = [1,2,_]nums = [0,0,1,1,1,2,2,3,3,4], Output: 5. The resulting nums will look lie: nums = [0,1,2,3,4,_,_,_,_,_]
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# use two pointers: left and right.
# the left tracks the non-duplicated array; the right tracks how many elements
# we have seen so far.
l,r = 0,1
n = len(nums)
while r < n:
if nums[r] == nums[l]:
# duplicate, move right index
r+=1
else:
l+=1
# replace the next element in nums[l] w the current in nums[r]
nums[l] = nums[r]
r+=1
return l+1If we wanted to run it on an example:
## [0, 1, 2, 3, 4]
The time complexity of this solution is \(O(N)\), since there is no nested loop.
Array, Two pointers