Pages

Saturday, May 31, 2025

Remove Duplicates using Recursion in C++

 #include<iostream>

#include<vector>
#include<cmath>
using namespace std;

void removeDuplicates(string str, string ans, int i, int map[26]) {
    // Base case
    if(i == str.size()) {
        cout << "ans: " << ans << endl;
    return;
    }

    int mapIdx = (int)(str[i] - 'a');

    if(map[mapIdx]) { // duplicate
            removeDuplicates(str, ans, i+1, map);


    } else {// not duplicate
    map[mapIdx] = true;
    removeDuplicates(str, ans+str[i], i+1, map);
    }
}

int main() {
    string str = "appnnacollege";
    string ans = "";
    int map[26] = {false};



    removeDuplicates(str, ans,0, map);
return 0;

}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...