logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

27. Remove Element

1 min read
On this pageIntuition
IntuitionApproachComplexityCode

Given an array and a val remove all it occurrences in-place and return the number of remaining elements

Input: 
nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]

if there are k occurrence of val change the array nums such that the first k elements of nums contain the elements which are not equal to val.


# Intuition

  • An element shifts by the occurrence amount of val before it.

# Approach

  • Start from beginning of the array tracking the occurrence of val (lets say its tracked by i)
  • Move an elements i steps forward in array if there are i occurrence of val before it.

# Complexity

  • Time complexity : O(n)\text{O}(n)O(n)
    • as we iterate the array only once
  • Space complexity : O(1)\text{O}(1)O(1)
    • No extra space is needed as everything is done in place

# Code

public int removeElement(int[] nums, int val) {
	// This will track the occurrence count of the val
	int placesToBeMovedBy = 0;
	
	for (int i = 0; i < nums.length; ++i) {
	    // If current value is val increase the occurrence count and continue 
		if(nums[i] == val) {
			placesToBeMovedBy++;
			continue;
		} 
	
		// If there is an occurence of val we can overwrite it
		nums[i - placesToBeMovedBy] = nums[i];
	}
	
	return nums.length - placesToBeMovedBy;
}
←Previous26. Remove Duplicates from Sorted ArrayNext→42. Trapping Rain Water

On this page

IntuitionApproachComplexityCode