{"id":6158,"date":"2025-05-29T18:20:54","date_gmt":"2025-05-29T12:50:54","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6158"},"modified":"2025-06-05T18:27:28","modified_gmt":"2025-06-05T12:57:28","slug":"remove-duplicates-from-sorted-array","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/remove-duplicates-from-sorted-array\/","title":{"rendered":"Remove Duplicates from Sorted Array"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n}\n\n.wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n}\n\n.wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242B33 !important;\n}\n\n.wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n}\n\n.wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content > pre {\n    background: #242B33 !important;\n}\n\n.wp_blog_code-tab-content.active {\n    display: block !important;\n}\n\n.wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n}\n\n.wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n}\n\n.wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n}\n\n.wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n}\n\n.wp_blog_explanation h1,\n.wp_blog_explanation h2,\n.wp_blog_explanation h3,\n.wp_blog_explanation h4,\n.wp_blog_explanation h5,\n.wp_blog_explanation h6,\n.wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n}\n<\/style>\n\n<!-- \u2705 START: Blog Explanation -->\n<!-- <div class=\"wp_blog_explanation\">    \n<\/div> -->\n\n<!-- \u2705 END: Blog Explanation -->\n\n      <div class=\"wp_blog_explanation\">\n       \n<p>\nGiven an integer array <code>nums<\/code> 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 <code>nums<\/code>.\n<\/p>\n\n<p>Consider the number of unique elements of <code>nums<\/code> to be <code>k<\/code>. To get accepted, you need to do the following things:<\/p>\n<ul>\n  <li>Change the array <code>nums<\/code> such that the first <code>k<\/code> elements of <code>nums<\/code> contain the unique elements in the order they were present in <code>nums<\/code> initially.<\/li>\n  <li>The remaining elements of <code>nums<\/code> are not important, as well as the size of <code>nums<\/code>.<\/li>\n  <li>Return <code>k<\/code>.<\/li>\n<\/ul>\n<h2>Examples<\/h2>\n<h3>Example 1:<\/h3>\n<pre><code>\nInput: nums = [1,1,2]\nOutput: 2, nums = [1,2,_]\nExplanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 \nrespectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n<\/code><\/pre>\n\n<h3>Example 2:<\/h3>\n<pre><code>\nInput: nums = [0,0,1,1,1,2,2,3,3,4]\nOutput: 5, nums = [0,1,2,3,4,_,_,_,_,_]\nExplanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and \n4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n<\/code><\/pre>\n\n<h2>Constraints:<\/h2>\n<ul>\n  <li>1 &le; <code>nums.length<\/code> &le; 3 * 10<sup>4<\/sup><\/li>\n  <li>-100 &le; <code>nums[i]<\/code> &le; 100<\/li>\n  <li><code>nums<\/code> is sorted in non-decreasing order.<\/li>\n<\/ul>\n\n<h2>Important Points<\/h2>\n\n<ul>\n  <li><strong>Non-decreasing order:<\/strong><br>\n    The array is sorted such that elements can stay the same or increase: <code>nums[i] &lt;= nums[i+1]<\/code>.<br>\n    <strong>Examples:<\/strong><br>\n     Valid: <code>[1, 1, 2, 3, 3, 5]<\/code><br>\n     Invalid: <code>[3, 2, 1]<\/code> (this is decreasing)\n  <\/li>\n  <li><strong>In-place:<\/strong><br>\n    You must modify the given <code>nums<\/code> array itself.<br>\n    You are <strong>not allowed<\/strong> to use extra arrays for storing the result.\n  <\/li>\n<\/ul>\n\n<h2>Approach<\/h2>\n\n<ul>\n  <li><code>x = 0<\/code>: Pointer to track the last unique element&#8217;s position.<\/li>\n  <li>Loop through the array from <code>i = 0<\/code> to <code>nums.length<\/code>.<\/li>\n  <li>Compare <code>nums[i] &gt; nums[x]<\/code>:<\/li>\n  <li>If true (new unique value), increment <code>x<\/code> and update <code>nums[x] = nums[i]<\/code>.<\/li>\n  <li>This shifts the unique value forward in the array.<\/li>\n  <li>At the end, <code>x + 1<\/code> gives the count of unique elements.<\/li>\n<\/ul>\n\n<h2>Time Complexity (TC):<\/h2>\n<ul>\n  <li>The function uses a single loop that iterates through the entire array once.<\/li>\n  <li>Each iteration performs constant-time operations (comparisons and assignments).<\/li>\n  <li><strong>Time Complexity = O(n)<\/strong>, where <code>n = nums.length<\/code>.<\/li>\n<\/ul>\n\n<h2>Space Complexity (SC):<\/h2>\n<ul>\n  <li>The function modifies the array <strong>in-place<\/strong>.<\/li>\n  <li>Uses only a few extra variables: <code>x<\/code> and <code>i<\/code>.<\/li>\n  <li><strong>Space Complexity = O(1)<\/strong> (constant extra space).<\/li>\n<\/ul>\n\n<h2>Dry Run<\/h2>\n\n<pre><code>\nInput: [1, 1, 2, 3, 3, 5]\n\nInitial state:\nx = 0\n\ni = 0: nums[i] = 1, nums[x] = 1 \u2192 NOT greater \u2192 skip\ni = 1: nums[i] = 1, nums[x] = 1 \u2192 NOT greater \u2192 skip\ni = 2: nums[i] = 2, nums[x] = 1 \u2192 GREATER \u2192 x=1, nums[1] = 2\ni = 3: nums[i] = 3, nums[x] = 2 \u2192 GREATER \u2192 x=2, nums[2] = 3\ni = 4: nums[i] = 3, nums[x] = 3 \u2192 NOT greater \u2192 skip\ni = 5: nums[i] = 5, nums[x] = 3 \u2192 GREATER \u2192 x=3, nums[3] = 5\n\nFinal array: [1, 2, 3, 5, 3, 5]\nUnique count: x + 1 = 4\n<\/code><\/pre>\n\n<p><strong>Output:<\/strong> <code>4<\/code> (First 4 elements are unique: [1, 2, 3, 5])<\/p>\n\n\n      <\/div>\n<!-- \u2705 START: Code Tabs -->\n\n  \n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"csharp\">C#<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  var removeDuplicates = function(nums) {\n      let x = 0;\n      for (let i = 0; i < nums.length; i++) {\n          if (nums[i] > nums[x]) {\n              x++;\n              nums[x] = nums[i];\n          }\n      }\n      return x + 1;\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  class Solution {\n  public:\n      int removeDuplicates(vector&lt;int&gt;& nums) {\n          int x = 0;\n          for (int i = 0; i < nums.size(); i++) {\n              if (nums[i] > nums[x]) {\n                  x++;\n                  nums[x] = nums[i];\n              }\n          }\n          return x + 1;\n      }\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n  int removeDuplicates(int* nums, int numsSize) {\n      int x = 0;\n      for (int i = 0; i < numsSize; i++) {\n          if (nums[i] > nums[x]) {\n              x++;\n              nums[x] = nums[i];\n          }\n      }\n      return x + 1;\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  public class Solution {\n      public int removeDuplicates(int[] nums) {\n          int x = 0;\n          for (int i = 0; i < nums.length; i++) {\n              if (nums[i] > nums[x]) {\n                  x++;\n                  nums[x] = nums[i];\n              }\n          }\n          return x + 1;\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  class Solution(object):\n      def removeDuplicates(self, nums):\n          x = 0\n          for i in range(len(nums)):\n              if nums[i] > nums[x]:\n                  x += 1\n                  nums[x] = nums[i]\n          return x + 1\n      <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"csharp\">\n        <pre><code class=\"language-csharp\">public class Solution {\n          public int RemoveDuplicates(int[] nums) {\n              if (nums.Length == 0) return 0;\n      \n              int x = 0;\n              for (int i = 1; i < nums.Length; i++) {\n                  if (nums[i] > nums[x]) {\n                      x++;\n                      nums[x] = nums[i];\n                  }\n              }\n              return x + 1;\n          }\n      }\n      <\/code><\/pre>\n      <\/div>\n      \n      \n  <\/div>\n  \n  \n  \n<!-- \u2705 END: Code Tabs -->\n\n\n<!-- \u2705 JS Tab Switch Logic -->\n<script>\ndocument.addEventListener('DOMContentLoaded', function () {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n    buttons.forEach(button => {\n        button.addEventListener('click', () => {\n            const lang = button.getAttribute('data-lang');\n            buttons.forEach(btn => btn.classList.remove('active'));\n            button.classList.add('active');\n            contents.forEach(content => {\n                content.classList.toggle('active', content.getAttribute('data-lang') === lang);\n            });\n        });\n    });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>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,<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[811,810],"tags":[],"class_list":{"0":"post-6158","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-data-structures-and-algorithms","7":"category-dsa"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6158","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6158"}],"version-history":[{"count":3,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6158\/revisions"}],"predecessor-version":[{"id":6436,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6158\/revisions\/6436"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6158"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6158"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6158"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}