Skip to main content

Command Palette

Search for a command to run...

Remove Duplicates from Sorted Array

Published
2 min read
Remove Duplicates from Sorted Array
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

Given an integer array 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.

LeetCode Problem: Link | Click Here

class Solution {
    public int removeDuplicates(int[] nums) {
        // If the array is empty or has only one element, no duplicates to remove
        if (nums.length == 0 || nums.length == 1) {
            return nums.length;
        }

        int uniqueCount = 1; // Initialize with the first element as it's always unique
        for (int i = 1; i < nums.length; i++) {
            // Check if the current element is different from the previous one
            if (nums[i] != nums[i - 1]) {
                nums[uniqueCount] = nums[i]; // Update the array in place with the unique element
                uniqueCount++; // Move to the next unique element position
            }
        }

        return uniqueCount; // Return the count of unique elements
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.