Remove Element from Array in Place with Two-Pointer Technique

Day 6: 🫔 [Leet Code] Problem: 🧩 LeetCode Problem: Remove Element (In-Place) Today I solved a classic array problem that testsĀ in-place manipulation and pointer logic. šŸ”¹ Problem Statement Given an integer arrayĀ numsĀ and an integerĀ val, remove all occurrences ofĀ valĀ in-place. The order of elements may be changed. ReturnĀ k, the number of elements not equal toĀ val, such that: The firstĀ kĀ elements ofĀ numsĀ contain valuesĀ not equalĀ toĀ val Elements beyondĀ kĀ do not matter. 🧠 Key Understanding No extra array should be used The array must be modifiedĀ in-place Only the firstĀ kĀ elements matter Time complexity should be efficient šŸ’” Approach Used (Two-Pointer Technique) Use a pointerĀ kĀ to track the position of valid elements Traverse the array using indexĀ i IfĀ nums[i] != val, place it at positionĀ kĀ and incrementĀ k Finally, returnĀ k 🧪 Python Solution class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0 n = len(nums) for i in range(n): if nums[i] != val: nums[k] = nums[i] k += 1 return k ā±ļø Complexity Analysis Time Complexity:Ā O(n) Space Complexity:Ā O(1). LeetCode #Python #DSA #InterviewPreparation #ProblemSolving #Coding

  • graphical user interface

To view or add a comment, sign in

Explore content categories