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

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...