Remove duplicates from sorted array

Arrays Logic Building Easy
  • Fun Fact: The concept of removing duplicates from an array, as illustrated in the programming problem, is commonly applied in the real world software industry
  • One well-known example is in database management systems
  • If we consider a database as an array where each row corresponds to an array element, removing duplicates is equivalent to the SQL operation "SELECT DISTINCT", which is frequently used to obtain a list of unique records
  • Furthermore, this operation is often implemented in Javascript-based web development for data manipulation in various web apps to ensure data integrity and avoid redundancy

Given an integer array nums sorted in non-decreasing order, remove all duplicates in-place so that each unique element appears only once. Return the number of unique elements in the array.


If the number of unique elements be k, then,

  • Change the array nums such that the first k elements of nums contain the unique values in the order that they were present originally.
  • The remaining elements, as well as the size of the array does not matter in terms of correctness.


An array sorted in non-decreasing order is an array where every element to the right of an element in either equal to or greater in value than that element.

Examples:

Input: nums = [0, 0, 3, 3, 5, 6]

Output: [0, 3, 5, 6, _, _]

Explanation: There are 4 distinct elements in nums and the elements marked as _ can have any value.

Input: nums = [-2, 2, 4, 4, 4, 4, 5, 5]

Output: [-2, 2, 4, 5, _, _, _, _]

Explanation: There are 4 distinct elements in nums and the elements marked as _ can have any value.

Input: nums = [-30, -30, 0, 0, 10, 20, 30, 30]

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

Hints

  • Since the array is sorted, duplicates will always be consecutive. Compare adjacent elements to identify duplicates and move unique elements forward.
  • Keep a counter to track the number of unique elements as you traverse the array.

Company Tags

Unity Technologies Byju's Electronic Arts JPMorgan Chase Reddit Roche Freshworks Walmart Mastercard Medtronic Shopify Rakuten Swiggy Seagate Technology Docker Philips Healthcare Cerner Twilio Zomato PayPal NVIDIA Zynga Uber Red Hat Qualcomm TCS Cognizant Accenture Infosys Capgemini Wipro