Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Abdullah AlKheshen
Three approaches!

Abdullah AlKheshen

Jun 22, 2024

Sure, here are the three approaches without the main function, focusing solely on the core algorithms:

 

Approach 1: Using slow_ptr and fast_ptr with Initialization of slow_ptr to 1

 

class Solution { public:     static int removeDuplicates(vector<int> &arr) {         int slow_ptr = 1;         for (int fast_ptr = 1; fast_ptr < arr.size(); fast_ptr++) {             if (arr[slow_ptr - 1] != arr[fast_ptr]) {                 arr[slow_ptr] = arr[fast_ptr];                 slow_ptr++;             }         }         return slow_ptr;     } };

 

Approach 2: Using slow_ptr and fast_ptr with Initialization of slow_ptr to 0

 

class Solution { public:     static int removeDuplicates(vector<int> &nums) {         int slow_ptr = 0;         for (int fast_ptr = 0; fast_ptr < nums.size(); fast_ptr++) {             if (nums[slow_ptr] != nums[fast_ptr]) {                 slow_ptr++;                 nums[slow_ptr] = nums[fast_ptr];             }         }         return slow_ptr + 1;     } };

 

Approach 3: Using slow_ptr and fast_ptr with Initialization of slow_ptr to 1

 

class Solution { public:     static int removeDuplicates(vector<int> &nums) {         int slow_ptr = 1;         for (int fast_ptr = 1; fast_ptr < nums.size(); fast_ptr++) {             if (nums[fast_ptr - 1] != nums[fast_ptr]) {                 nums[slow_ptr] = nums[fast_ptr];                 slow_ptr++;             }         }         return slow_ptr;     } };

 

Explanation:

  • Approach 1: The slow_ptr starts at 1, and for each fast_ptr, it checks if the previous element in the slow_ptr is different from the current element at fast_ptr. If they are different, the element at fast_ptr is moved to slow_ptr and slow_ptr is incremented.

  • Approach 2: The slow_ptr starts at 0, and for each fast_ptr, it checks if the current element at slow_ptr is different from the current element at fast_ptr. If they are different, slow_ptr is incremented, and the element at fast_ptr is moved to slow_ptr. Finally, the function returns slow_ptr + 1 since slow_ptr is zero-based.

  • Approach 3: Similar to Approach 1, but slow_ptr starts at 1 and the comparison is between the element before fast_ptr and the current element at fast_ptr. If they are different, the element at fast_ptr is moved to slow_ptr and slow_ptr is incremented.

0

0

Comments
Comments

On this page

Problem Statement

Solution

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity