Solve LeetCode 80 "Remove Duplicates from Sorted Array II" in Python with this intermediate tutorial! This medium problem requires removing duplicates from a sorted array in-place, allowing each element to appear at most twice, and returning the new length. We’ll use `itertools.groupby` to handle cases like `[1, 1, 1, 2, 2, 3]` and explain the in-place modification. Perfect for coding interview prep, Python learners, or anyone tackling LeetCode array challenges!
🔍 *What You'll Learn:*
Understanding the Remove Duplicates II problem
Using `itertools.groupby` to group duplicates
Modifying arrays in-place with at most two occurrences
Testing with LeetCode test cases
💻 *Code Used in This Video:*
from itertools import groupby
class Solution:
def removeDuplicates(self, nums):
Type: List[int]
rtype: int
Keep at most 2 occurrences of each number
nums[:] = [x for k, g in groupby(nums) for x in list(g)[:2]]
return len(nums)
Test cases
nums1 = [1, 1, 1, 2, 2, 3]
print(Solution().removeDuplicates(nums1)) # Output: 5
print(nums1[:5]) # Output: [1, 1, 2, 2, 3]
nums2 = [0, 0, 1, 1, 1, 1, 2, 3, 3]
print(Solution().removeDuplicates(nums2)) # Output: 7
print(nums2[:7]) # Output: [0, 0, 1, 1, 2, 3, 3]
🌟 *Why Solve LeetCode 80?*
This problem tests advanced array manipulation and in-place operations—crucial for coding interviews at top tech companies! We’ll break down how `groupby` clusters duplicates, `list(g)[:2]` keeps at most two occurrences, and the solution meets constraints (arrays up to 10^5 elements). Master this, and you’ll be ready for more complex array challenges—ideal for interview prep or Python practice!
📚 *Who’s This For?*
Python learners tackling LeetCode
Coders prepping for tech interviews
LeetCode enthusiasts solving medium problems
👍 Like, subscribe, and comment: What LeetCode problem should we solve next? Next up: LeetCode 1 Two Sum—stay tuned!
#PythonTutorial #LeetCode80 #RemoveDuplicatesII #CodingInterview #LearnPython
from itertools import groupby
class Solution:
def removeDuplicates(self, nums):
Type: List[int]
rtype: int
Use groupby to group duplicates, keep at most 2 occurrences
nums[:] = [x for k, g in groupby(nums) for x in list(g)[:2]]
return len(nums)
groupby(nums) groups consecutive duplicates
list(g)[:2] takes up to 2 instances of each number
Test cases
nums1 = [1, 1, 1, 2, 2, 3]
print(Solution().removeDuplicates(nums1)) # Output: 5 (length with at most 2 duplicates)
print(nums1[:5]) # Output: [1, 1, 2, 2, 3] (first 5 elements match new length)
nums2 = [0, 0, 1, 1, 1, 1, 2, 3, 3]
print(Solution().removeDuplicates(nums2)) # Output: 7 (length with at most 2 duplicates)
print(nums2[:7]) # Output: [0, 0, 1, 1, 2, 3, 3] (first 7 elements match new length)
Информация по комментариям в разработке