LeetCode Day-3
Hey there,
Welcome to Day 3 of my LeetCode journey! I'm excited to have you here as I continue my coding journey. As promised, I'm staying committed to solving one problem every day and sharing my progress with you through this blog.
Let's get started!
80. Remove Duplicates from Sorted Array II
Intuition :
integer array nums, sorted in ascending order
remove duplicates in-place
each unique element must appear at most twice
relative order must be the same
k elements will be left after removing duplicates
return k (the unique elements)
Approach :
- Create a temporary list of unique elements. You can create it using set on the nums array. And sort the temporary list.
temp = list(set(nums))
temp = sorted(temp)
- Initialize a variable k (which is the number of elements in the final result)
k = 0
- Create a count dictionary such that, for every unique element, you have the number of times the element appears in nums
count = {i:nums.count(i) for i in temp}
Loop through the numbers in the temp array (sorted, unique)
If the count of the number is greater than or equal to 2, the number must appear twice in the final array.
If the count of the number is equal to 1, the number must appear once in the final array.
for num in temp:
if count[num] >= 2 :
nums[k] = num
nums[k+1] = num
k += 2
elif count[num] == 1 :
nums[k] = num
k += 1
- return k
return k
Here is the code :
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
temp = list(set(nums))
temp = sorted(temp)
k = 0
count = {i:nums.count(i) for i in temp}
for num in temp:
if count[num] >= 2 :
nums[k] = num
nums[k+1] = num
k += 2
elif count[num] == 1 :
nums[k] = num
k += 1
return k
169. Majority Element
Intuition :
array nums of size n
majority element: an element that appears more than n/2 number of times
return the majority element
Approach :
Create a count list (this will have only one element due to conditions provided in list comprehension)
the count list will store the number having its count greater than n/2
You will traverse through unique elements in nums and find the number having its count greater than n/2
count = [i for i in list(set(nums))
if nums.count(i)>len(nums)//2]
- Since the list will have only one element, return the first element
return count[0]
Here is the full code :
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = [i for i in list(set(nums)) if nums.count(i)>len(nums)//2]
return count[0]
That's it for Day 3 of my LeetCode journey. If you have any questions, doubts, or suggestions for improvement, please feel free to share them. Your support and engagement means a lot to me.
Happy Coding!