Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

29. Remove Duplicates from Sorted Array

EasyDay 8 of 60Two Pointers

You are given an integer array nums sorted in non-decreasing order. Remove the repeated values in place so each distinct value appears once, keeping their original order. Return k, the number of distinct values; the first k positions of nums must hold them. What is left after position k does not matter.

Example 1
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Two distinct values remain at the front; the last slot can hold anything.
Example 2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Constraints
  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • `nums` is sorted in non-decreasing order
Hints
Frequently asked at: Microsoft, Meta, Amazon, Accenture, TCS
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min